@bitcobblers/wod-wiki-tools 0.63.2266 → 0.63.2267
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agentCommands-K7D55BYF.mjs → agentCommands-K5CIVN7W.mjs} +3 -3
- package/dist/{agentCommands-K7D55BYF.mjs.map → agentCommands-K5CIVN7W.mjs.map} +1 -1
- package/dist/bin/wod.cjs +1 -1
- package/dist/bin/wod.cjs.map +1 -1
- package/dist/bin/wod.mjs +2 -2
- package/dist/{chunk-C7RA4HVA.mjs → chunk-456VWJZ4.mjs} +3 -3
- package/dist/{chunk-C7RA4HVA.mjs.map → chunk-456VWJZ4.mjs.map} +1 -1
- package/dist/{chunk-DW2FI2SH.mjs → chunk-JI4E5J7I.mjs} +3 -3
- package/dist/chunk-JI4E5J7I.mjs.map +1 -0
- package/dist/{chunk-SN3DL6QE.mjs → chunk-LRTMQHQA.mjs} +3 -3
- package/dist/{chunk-SN3DL6QE.mjs.map → chunk-LRTMQHQA.mjs.map} +1 -1
- package/dist/{chunk-KUD6PCWA.mjs → chunk-UJCAH7V3.mjs} +8 -8
- package/dist/{chunk-KUD6PCWA.mjs.map → chunk-UJCAH7V3.mjs.map} +1 -1
- package/dist/{chunk-BM5TC4YW.mjs → chunk-ZMPTTKMO.mjs} +3 -3
- package/dist/{chunk-BM5TC4YW.mjs.map → chunk-ZMPTTKMO.mjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +5 -5
- package/dist/{mcp-GF4SDBSL.mjs → mcp-DWME7IX3.mjs} +4 -4
- package/dist/{mcp-GF4SDBSL.mjs.map → mcp-DWME7IX3.mjs.map} +1 -1
- package/dist/{scaffoldFeed-BYGQPAKT.mjs → scaffoldFeed-R7KM3KYZ.mjs} +3 -3
- package/dist/{scaffoldFeed-BYGQPAKT.mjs.map → scaffoldFeed-R7KM3KYZ.mjs.map} +1 -1
- package/dist/server/app.cjs +1 -1
- package/dist/server/app.cjs.map +1 -1
- package/dist/server/app.mjs +3 -3
- package/dist/server-APPXG2WF.mjs +13 -0
- package/dist/{server-4CNPKQHA.mjs.map → server-APPXG2WF.mjs.map} +1 -1
- package/dist/web/playground/assets/{feedSync.worker-3JQ9JWGx.js → feedSync.worker-CTJcuCvq.js} +2 -2
- package/dist/web/playground/assets/{main-BKT_AJGZ.js → main-DA8KxC4c.js} +140 -140
- package/dist/web/playground/index.html +1 -1
- package/dist/web/{server/seed/core/chunks/canvas.51b9a3f6.json → playground/seed/core/chunks/canvas.85bdc613.json} +1 -1
- package/dist/web/{server/seed/core/chunks/dashboards.834deeef.json → playground/seed/core/chunks/dashboards.f533ec13.json} +1 -1
- package/dist/web/{server/seed/core/chunks/efforts.96c7115b.json → playground/seed/core/chunks/efforts.8b1d0244.json} +1 -1
- package/dist/web/playground/seed/core/chunks/{equipment.78504e56.json → equipment.737cbe76.json} +1 -1
- package/dist/web/playground/seed/core/indexes/notebooks/canvas.json +180 -180
- package/dist/web/playground/seed/core/indexes/notebooks/dashboards.json +16 -16
- package/dist/web/playground/seed/core/indexes/notebooks/efforts.json +326 -326
- package/dist/web/playground/seed/core/indexes/notebooks/equipment.json +50 -50
- package/dist/web/playground/seed/core/manifest.json +27 -27
- package/dist/web/playground/seed/core/markdown/canvas/ai-first/README.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/README.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/guide/clock.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/dashboards.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/metrics-summaries.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/guide/metrics.json +12 -12
- package/dist/web/playground/seed/core/markdown/canvas/guide/protocols.json +20 -20
- package/dist/web/playground/seed/core/markdown/canvas/guide/sessions.json +33 -33
- package/dist/web/playground/seed/core/markdown/canvas/guide/start.json +11 -11
- package/dist/web/playground/seed/core/markdown/canvas/guide/structure.json +25 -25
- package/dist/web/playground/seed/core/markdown/canvas/guide/wql.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/home/sample-script.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/home/welcome-1.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-full-session.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-swimming.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-3.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-3.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-4.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/effort-notes.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/measurements.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-4.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-sections.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/named-groups.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-3.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
- package/dist/web/playground/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
- package/dist/web/playground/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
- package/dist/web/playground/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
- package/dist/web/playground/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
- package/dist/web/playground/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
- package/dist/web/playground/seed/core/markdown/dashboards/training-block-review.json +11 -11
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/recovery/rest.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/recovery/stretching.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/backward-running.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/snatch.json +4 -4
- package/dist/web/playground/seed/core/markdown/efforts/strength/back-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/bench-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/carioca.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/cluster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/devils-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/front-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/good-morning.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/l-sit.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/man-maker.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/power-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/push-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sled-push.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/thruster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/air-bike.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/barbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/bench.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/bike-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/climbing-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/clubs.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/dumbbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/ghd.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/jump-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/kettlebell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/macebell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/medicine-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/parallettes.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/plyo-box.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/pull-up-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/rower.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sandbag.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/ski-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/slam-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sled.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sledgehammer.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/weight-vest.json +1 -1
- package/dist/web/playground/seed/core/report.html +13 -13
- package/dist/web/playground/version.json +3 -3
- package/dist/web/server/assets/{feedSync.worker-3JQ9JWGx.js → feedSync.worker-CTJcuCvq.js} +2 -2
- package/dist/web/server/assets/{main-Bvp2Hm9u.js → main-COJt7UId.js} +11 -11
- package/dist/web/server/index.html +1 -1
- package/dist/web/{playground/seed/core/chunks/canvas.51b9a3f6.json → server/seed/core/chunks/canvas.85bdc613.json} +1 -1
- package/dist/web/{playground/seed/core/chunks/dashboards.834deeef.json → server/seed/core/chunks/dashboards.f533ec13.json} +1 -1
- package/dist/web/{playground/seed/core/chunks/efforts.96c7115b.json → server/seed/core/chunks/efforts.8b1d0244.json} +1 -1
- package/dist/web/server/seed/core/chunks/{equipment.78504e56.json → equipment.737cbe76.json} +1 -1
- package/dist/web/server/seed/core/indexes/notebooks/canvas.json +180 -180
- package/dist/web/server/seed/core/indexes/notebooks/dashboards.json +16 -16
- package/dist/web/server/seed/core/indexes/notebooks/efforts.json +326 -326
- package/dist/web/server/seed/core/indexes/notebooks/equipment.json +50 -50
- package/dist/web/server/seed/core/manifest.json +27 -27
- package/dist/web/server/seed/core/markdown/canvas/ai-first/README.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/README.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/guide/clock.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/dashboards.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/metrics-summaries.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/guide/metrics.json +12 -12
- package/dist/web/server/seed/core/markdown/canvas/guide/protocols.json +20 -20
- package/dist/web/server/seed/core/markdown/canvas/guide/sessions.json +33 -33
- package/dist/web/server/seed/core/markdown/canvas/guide/start.json +11 -11
- package/dist/web/server/seed/core/markdown/canvas/guide/structure.json +25 -25
- package/dist/web/server/seed/core/markdown/canvas/guide/wql.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/home/sample-script.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/home/welcome-1.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-full-session.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-swimming.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-3.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-3.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-4.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/effort-notes.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/measurements.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-4.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-sections.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/named-groups.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-3.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
- package/dist/web/server/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
- package/dist/web/server/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
- package/dist/web/server/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
- package/dist/web/server/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
- package/dist/web/server/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
- package/dist/web/server/seed/core/markdown/dashboards/training-block-review.json +11 -11
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/recovery/rest.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/recovery/stretching.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/rowing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/backward-running.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/snatch.json +4 -4
- package/dist/web/server/seed/core/markdown/efforts/strength/back-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/bench-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/carioca.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/cluster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/devils-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/front-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/good-morning.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/l-sit.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/man-maker.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/power-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/push-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sled-push.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/thruster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/air-bike.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/barbell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/bench.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/bike-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/climbing-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/clubs.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/dumbbell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/ghd.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/jump-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/kettlebell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/macebell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/medicine-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/parallettes.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/plyo-box.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/pull-up-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/rower.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sandbag.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/ski-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/slam-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sled.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sledgehammer.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/weight-vest.json +1 -1
- package/dist/web/server/seed/core/report.html +13 -13
- package/dist/web/server/version.json +3 -3
- package/package.json +6 -6
- package/dist/chunk-DW2FI2SH.mjs.map +0 -1
- package/dist/server-4CNPKQHA.mjs +0 -13
|
@@ -151,7 +151,7 @@ query: sum:${r}{notebook:$notebook} by {week}
|
|
|
151
151
|
`)+`
|
|
152
152
|
`}function dx(e){let t=ix(e);if(t.length<2)return{bundles:[],errors:[]};let n=rx(t[0]);if(n[0]!==`recordKind`)try{let t=cx(e);return{bundles:[{sessions:[t.session],events:t.events}],errors:[]}}catch(e){return{bundles:[],errors:[e instanceof Error?e.message:String(e)]}}let r=new Map;n.forEach((e,t)=>r.set(e,t));let i=(e,t)=>{let n=r.get(t);return n===void 0?``:e[n]??``},a=new Map,o=new Map,s=new Map,c=[];for(let[e,n]of t.slice(1).entries()){let t=rx(n);if(t.length===1&&t[0]===``)continue;let r=i(t,`recordKind`),l=ox(i(t,`noteId`));if(!l){c.push(`Row ${e+2}: missing noteId`);continue}if(r===`revision`){let n=ox(i(t,`revisionKind`)),r=ox(i(t,`blockId`)),o=ax(i(t,`blockVersion`)),s=ax(i(t,`revisionSavedAt`));if(!n||!r||!o||s===void 0){c.push(`Row ${e+2}: invalid revision columns`);continue}let u={noteId:l,blockId:r,version:o,kind:n,rawContent:i(t,`revisionRawContent`),savedAt:s,...ox(i(t,`revisionDialect`))?{dialect:ox(i(t,`revisionDialect`))}:{},...ox(i(t,`revisionSport`))?{sport:ox(i(t,`revisionSport`))}:{}},d=a.get(l)??[];d.push(u),a.set(l,d)}else if(r===`parse`){let n=ox(i(t,`parseId`)),r=ox(i(t,`parseStage`)),a=ox(i(t,`parseStatus`)),s=ax(i(t,`timestamp`));if(!n||!r||!a||s===void 0){c.push(`Row ${e+2}: invalid parse columns`);continue}let u={id:n,noteId:l,...ox(i(t,`blockId`))?{blockId:ox(i(t,`blockId`))}:{},...ax(i(t,`blockVersion`))===void 0?{}:{blockVersion:ax(i(t,`blockVersion`))},stage:r,status:a,timestamp:s,...ox(i(t,`parseDiagnosticsJson`))?{diagnostics:sx(i(t,`parseDiagnosticsJson`))}:{},...ox(i(t,`parseMetricsJson`))?{metrics:sx(i(t,`parseMetricsJson`))}:{}},d=o.get(l)??[];d.push(u),o.set(l,d)}else if(r===`session`||r===`event`){let n=ox(i(t,`sessionId`));if(!n){c.push(`Row ${e+2}: missing sessionId`);continue}let r=ex.map(e=>tx(i(t,e))),a=s.get(n)??{noteId:l,lines:[ex.join(`,`)]};a.lines.push(r.join(`,`)),s.set(n,a)}else c.push(`Row ${e+2}: unknown recordKind '${r}'`)}let l=new Map,u=e=>{let t=l.get(e);if(t)return t;let n={sessions:[],events:[]};return l.set(e,n),n};for(let[e,t]of a)u(e).revisions=t;for(let[e,t]of o)u(e).parses=t;for(let[,{noteId:e,lines:t}]of s)try{let n=cx(t.join(`
|
|
153
153
|
`)+`
|
|
154
|
-
`),r=u(e);r.sessions.push(n.session),r.events.push(...n.events)}catch(e){c.push(e instanceof Error?e.message:String(e))}return{bundles:[...l.values()],errors:c}}var Fae=`0.63.2266`,fx=Ns,Iae=`1b671a64-40d5-491e-99b0-da01ff1f3341`,Lae={core:0,community:1,imported:2,user:3};function Rae(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 px(e,t){return Lae[Rae(e,t)]}var mx=`wodwiki.seed`,hx=`feed:index:`;function gx(e,t){return`${hx}${e}:${t}`}var _x=`efforts`,vx=`equipment`,yx=`canvas`;function bx(e){return`seed:${e}`}function zae(e){return e.startsWith(`seed:`)?e.slice(5):e}function xx(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Sx(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function Bae(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 Vae(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:${Bae(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Sx(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}var Cx=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-type`,keyPath:[`type`]},{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:`note_revisions`,keyPath:[`noteId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]}]},{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-session-date`,keyPath:[`sessionDate`]},{name:`by-schedule-item`,keyPath:[`scheduleItemId`]},{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:`notebook_links`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-target`,keyPath:[`targetKind`,`targetId`]},{name:`by-notebook-target`,keyPath:[`notebookId`,`targetKind`,`targetId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`property_overrides`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-kind-slug`,keyPath:[`kind`,`slug`]},{name:`by-owner-note`,keyPath:[`ownerNoteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`schedule_items`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-date-note`,keyPath:[`date`,`noteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],wx=`default`;function Tx(e=Date.now()){return{id:wx,displayName:`Anonymous`,createdAt:e}}var Ex=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`,`notebook_links`,`property_overrides`,`schedule_items`],Hae=Object.fromEntries(Ex.map(e=>[e,!0]));function Dx(e,t,n){if(!Hae[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 Ox(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(`only`in e||`lower`in e||`upper`in e||`lowerOpen`in e||`upperOpen`in e)}function kx(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 Ax(e,t){let n=e.keyPath.map(e=>kx(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}function Uae(e){return encodeURIComponent(JSON.stringify(e))}function jx(e){if(e===void 0)return;if(!Ox(e))return{only:e};if(e.only!==void 0)return e;let t={};return e.lower!==void 0&&e.lower!==null&&(t.lower=e.lower,t.lowerOpen=e.lowerOpen===!0),e.upper!==void 0&&e.upper!==null&&(t.upper=Array.isArray(e.upper)?e.upper.map(e=>Array.isArray(e)&&e.length===0?``:e):e.upper,t.upperOpen=e.upperOpen===!0),t.lower!==void 0||t.upper!==void 0?t:void 0}function Mx(e,t){if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t))return Array.isArray(e)?1:-1;for(let n=0;n<Math.min(e.length,t.length);n++){let r=Mx(e[n],t[n]);if(r!==0)return r}return e.length-t.length}return typeof e==`number`&&typeof t==`number`?e<t?-1:+(e>t):typeof e==`number`||typeof t==`number`?typeof e==`number`?-1:1:e<t?-1:+(e>t)}function Nx(e,t){if(t.only!==void 0)return Mx(e,t.only)===0;if(t.lower!==void 0){let n=Mx(e,t.lower);if(n<0||n===0&&t.lowerOpen===!0)return!1}if(t.upper!==void 0){let n=Mx(e,t.upper);if(n>0||n===0&&t.upperOpen===!0)return!1}return!0}function Px(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fx(e,t){return t.every(t=>e[t]===void 0||typeof e[t]==`string`)}function Ix(e,t){return t.every(t=>typeof e[t]==`number`&&Number.isFinite(e[t]))}function Lx(e){if(!Px(e)||typeof e.id!=`string`||typeof e.title!=`string`||typeof e.rawContent!=`string`||!Number.isSafeInteger(e.sourceRevision)||typeof e.sourceRevision!=`number`||e.sourceRevision<1||!Px(e.blocks)||!Ix(e,[`createdAt`])||e.date!==void 0&&!Ix(e,[`date`])||!Fx(e,[`type`,`sourceId`,`notebookId`,`sourcePath`,`seedOrigin`,`seedChunkId`,`feedOrigin`,`feedSourceId`])||e.tags!==void 0&&(!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)))return!1;try{return Hs(e.rawContent,e.blocks,e.sourceRevision),!0}catch{return!1}}function Wae(e){return Px(e)&&typeof e.id==`string`&&typeof e.noteId==`string`&&typeof e.blockId==`string`&&Ix(e,[`blockVersion`,`sourceRevision`,`from`,`to`,`createdAt`])&&e.id===`${e.noteId}:${e.blockId}`&&typeof e.blockVersion==`number`&&Number.isSafeInteger(e.blockVersion)&&e.blockVersion>0&&typeof e.sourceRevision==`number`&&Number.isSafeInteger(e.sourceRevision)&&e.sourceRevision>0&&typeof e.from==`number`&&Number.isSafeInteger(e.from)&&e.from>=0&&typeof e.to==`number`&&Number.isSafeInteger(e.to)&&e.to>e.from&&[`wod`,`query`,`widget`,`embed`].includes(String(e.dataType))&&typeof e.rawContent==`string`&&typeof e.noteTitle==`string`&&Fx(e,[`blockContentId`,`sourceId`,`sourcePath`,`routeId`])&&(e.position===void 0||Ix(e,[`position`]))&&(e.isStatic===void 0||typeof e.isStatic==`boolean`)}function Gae(e){return Px(e)&&typeof e.id==`string`&&typeof e.label==`string`&&Ix(e,[`createdAt`])&&Fx(e,[`type`])}function Kae(e){return Px(e)&&typeof e.id==`string`&&Ix(e,[`createdAt`])&&Fx(e,[`date`,`slug`,`title`])}function qae(e){return Px(e)&&typeof e.id==`string`&&typeof e.noteId==`string`&&typeof e.pageId==`string`&&Ix(e,[`createdAt`])&&(e.position===void 0||Ix(e,[`position`]))}function Jae(e){return Px(e)&&Lx(e.note)&&Array.isArray(e.tags)&&e.tags.every(Gae)&&Array.isArray(e.links)&&e.links.every(qae)&&Array.isArray(e.pages)&&e.pages.every(Kae)}function Yae(e,t){if(!Px(e)||e.projectionVersion!==5||e.plan!==t||!Array.isArray(e.rows)||typeof e.selectedCount!=`number`||!Number.isSafeInteger(e.selectedCount)||e.selectedCount<0||typeof e.matchedCount!=`number`||!Number.isSafeInteger(e.matchedCount)||e.matchedCount<0||e.matchedCount>e.selectedCount||e.rows.length>e.matchedCount)throw Error(`ApiStorage: invalid or stale domain projection response`);let n={projectionVersion:5,selectedCount:e.selectedCount,matchedCount:e.matchedCount};switch(t){case`notes`:if(e.rows.every(Lx))return{...n,plan:t,rows:e.rows};break;case`blocks`:if(e.rows.every(Wae))return{...n,plan:t,rows:e.rows};break;case`detail`:if(e.rows.every(Jae))return{...n,plan:t,rows:e.rows}}throw Error(`ApiStorage: invalid domain query rows`)}var Rx=(e,t)=>`${e}\u0000${JSON.stringify(t)}`;function zx(e,t,n){if(n?.has(e))return!0;if(!t)return!1;let r=`${e}\u0000`;for(let e of t.keys())if(e.startsWith(r))return!0;return!1}function Xae(e,t,n){if(!n)return;let r=n.get(Rx(e,t));if(r)return r.kind===`put`?{hit:!0,value:r.value}:{hit:!1}}function Zae(e,t,n,r,i,a,o,s){if(!n||!zx(t,n,r))return a===void 0?i:i.slice(0,a);let c=new Map;if(!r?.has(t))for(let t of i)c.set(JSON.stringify(Ax(e,t)),t);let l=`${t}\u0000`;for(let[e,t]of n)e.startsWith(l)&&(t.kind===`put`?c.set(e.slice(l.length),t.value):c.delete(e.slice(l.length)));let u=s?e.indexes.find(e=>e.name===s):void 0;if(s&&!u)throw Error(`unknown index '${s}' for ${t}`);let d=t=>{if(!u)return Ax(e,t);let n=u.keyPath.map(e=>kx(t,e));if(n.some(e=>e===void 0))return;let r=n.filter(e=>e!==void 0);return r.length===1?r[0]:r},f=e=>{if(u?.multiEntry){let t=e;for(let e of u.keyPath[0].split(`.`)){if(typeof t!=`object`||!t||!(e in t))return!1;t=Reflect.get(t,e)}return Array.isArray(t)&&t.some(e=>(typeof e==`string`||typeof e==`number`)&&(!o||Nx(e,o)))}let t=d(e);return t!==void 0&&(!o||Nx(t,o))},p=[...c.values()].filter(f);return p.sort((t,n)=>{let r=Mx(Ax(e,t),Ax(e,n));if(u?.multiEntry)return r;let i=d(t),a=d(n);return i!==void 0&&a!==void 0&&Mx(i,a)||r}),a===void 0?p:p.slice(0,a)}function Qae(e,t,n){let r=new Set(e),i=[];for(let e of n)r.has(e)&&i.push({op:`clear`,store:e});for(let[e,n]of t){let t=e.indexOf(`\0`),a=e.slice(0,t);r.has(a)&&(n.kind===`put`?i.push({op:`put`,store:a,value:n.value}):i.push({op:`delete`,store:a,key:JSON.parse(e.slice(t+1))}))}return i}var Bx=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function Vx(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)=>Vx(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)&&Vx(Reflect.get(e,n),Reflect.get(t,n)))}function Hx(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new Bx(400,`storage row must be an object`);return e}function Ux(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`note_revisions`&&e!==`sessions`&&e!==`block_index`&&e!==`schedule_items`)return;let n=Hx(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.feedOrigin!==void 0&&n.feedOrigin!==`feed`&&n.feedOrigin!==`user`||n.feedOrigin===`feed`&&(n.seedOrigin===void 0||typeof n.feedSourceId!=`string`||n.feedSourceId.length===0)||n.feedOrigin===`user`&&n.seedOrigin===`seed`||n.feedSourceId!==void 0&&n.feedOrigin!==`feed`||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`))||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.provenance!==void 0&&(typeof n.provenance!=`object`||n.provenance===null||Array.isArray(n.provenance)||typeof n.provenance.sourceNoteId!=`string`)||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Bx(400,`invalid whole Note`,`invalid_note_blocks`);try{Hs(n.rawContent,Hx(n.blocks),n.sourceRevision)}catch(e){throw new Bx(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 Bx(400,`invalid block revision`,`invalid_note_blocks`);try{Hs(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 Bx(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`note_revisions`){if(!i(`noteId`)||!r(`version`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.type!==void 0&&typeof n.type!=`string`)throw new Bx(400,`invalid note revision`,`invalid_note_blocks`);try{Hs(n.rawContent,Hx(n.blocks),n.version)}catch(e){throw new Bx(400,e instanceof Error?e.message:`invalid note revision blocks`,`invalid_note_blocks`)}}else if(e===`schedule_items`){if(!i(`id`)||!i(`date`)||!i(`noteId`)||typeof n.position!=`number`||!Number.isFinite(n.position)||![`planned`,`completed`,`skipped`,`moved`].includes(String(n.status))||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||[`pageId`,`sourceNotebookId`,`fallbackTitle`,`blockId`,`slot`,`notes`,`movedFromDate`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Bx(400,`invalid schedule item`,`invalid_schedule_item`)}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||n.noteSourceRevision!==void 0&&!r(`noteSourceRevision`)||n.sessionDate!==void 0&&typeof n.sessionDate!=`string`||n.scheduleItemId!==void 0&&typeof n.scheduleItemId!=`string`||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new Bx(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 Bx(400,`invalid actionable block projection`,`invalid_note_blocks`)}function $ae(e,t){if(e===void 0||Vx(e,t))return;let n=Hx(e),r=Hx(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!Vx(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new Bx(409,`stale Note source revision`,`transaction_conflict`)}function eoe(e,t){if(e===void 0)return;let n=Hx(e),r=Hx(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new Bx(409,`Session pin is immutable`,`invalid_session_pin`)}async function Wx(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 Bx(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 Bx(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}async function Gx(e,t,n,r){let i=r?.params?.toString(),a=await e.fetchImpl(`${e.baseUrl}/v1${n}${i?`?${i}`:``}`,{method:t,headers:r?.body===void 0?void 0:{"content-type":`application/json`},body:r?.body===void 0?void 0:JSON.stringify(r.body)});if(!a.ok)throw Error(`ApiStorage: ${t} /v1${n} → ${a.status}`);return a}async function toe(e,t,n){let r=await e.fetchImpl(`${e.baseUrl}/v1/${t}/get?key=${Uae(n)}`);if(r.status!==404){if(!r.ok)throw Error(`ApiStorage: GET /v1/${t}/get → ${r.status}`);return await r.json()}}async function noe(e,t,n,r,i){let a=new URLSearchParams;return r&&a.set(`range`,JSON.stringify(r)),i!==void 0&&a.set(`count`,String(i)),await(await Gx(e,`GET`,`/${t}/${n}`,{params:a})).json()}async function Kx(e,t,n,r){let i=new URLSearchParams;return n&&i.set(`range`,JSON.stringify(n)),r!==void 0&&i.set(`index`,r),(await(await Gx(e,`GET`,`/${t}/count`,{params:i})).json()).count}async function qx(e,t,n){await Gx(e,`DELETE`,`/${t}`,{params:new URLSearchParams({key:JSON.stringify(n)})})}var roe=class{http;defs;getUserId;writeChain=Promise.resolve();constructor(e=`/api`,t=globalThis.fetch.bind(globalThis),n={}){this.http={baseUrl:e,fetchImpl:t},this.getUserId=n.getUserId,this.defs=Object.fromEntries(Cx.map(e=>[e.name,e]))}def(e){let t=this.defs[e];if(!t)throw Error(`ApiStorage: unknown store '${e}'`);return t}makeView(e,t,n,r,i=!1){return new ioe(this.http,this.def(e),e,t,n,this.getUserId,r,i)}readonly(e){return this.makeView(e)}readwrite(e){return this.makeView(e,void 0,void 0,void 0,!0)}async queryDomain(e){let t=await this.http.fetchImpl(`${this.http.baseUrl}/v1/query`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(t.status===409){let e=await t.json();if(typeof e==`object`&&e&&`code`in e&&e.code===`domain_projection_unavailable`)return}if(!t.ok)throw Error(`ApiStorage: POST /v1/query → ${t.status}`);return Yae(await t.json(),e.plan)}async transaction(e,t,n){let r=async()=>{let r=new Map,i=new Set,a=new Map,o=new Set(e),s=(e,n)=>{if(!o.has(e))throw Error(`store outside transaction scope`);if(n&&t!==`readwrite`)throw Error(`read-only transaction`);return this.makeView(e,r,i,a,n)},c=await n({readonly:e=>s(e,!1),readwrite:e=>s(e,!0)});return await this.flush(r,i,a),c};if(t!==`readwrite`)return r();let i=this.writeChain.then(r,r);return this.writeChain=i.then(()=>void 0,()=>void 0),i}async flush(e,t,n){let r=Qae(Cx.map(e=>e.name),e,t);r.length>0&&await Gx(this.http,`POST`,`/tx`,{body:{ops:[...n.values(),...r]}})}async wipe(){await Gx(this.http,`POST`,`/wipe`)}async close(){}},ioe=class{http;def;store;buffer;cleared;getUserId;checks;mutable;constructor(e,t,n,r,i,a,o,s=!1){this.http=e,this.def=t,this.store=n,this.buffer=r,this.cleared=i,this.getUserId=a,this.checks=o,this.mutable=s}dirty(){return zx(this.store,this.buffer,this.cleared)}async get(e){let t=Ox(e)?e:void 0,n;if(t){if(t.only===void 0)throw Error(`ApiStorage.get: needs a plain key or {only}; bounded ranges match no single row`);n=t.only}else n=e;let r=Xae(this.store,n,this.buffer);if(r)return r.hit?r.value:void 0;if(this.cleared?.has(this.store))return;let i=await toe(this.http,this.store,n),a=Rx(this.store,n);return this.checks?.has(a)||this.checks?.set(a,{op:`check`,store:this.store,key:n,value:structuredClone(i??null)}),i}async getMany(e){return Promise.all(e.map(e=>this.get(e)))}async getAllFromIndexMany(e,t){return Promise.all(t.map(t=>this.getAllFromIndex(e,t)))}async getAll(e,t){let n=jx(e);return this.overlay(await this.serverRows(`all`,n,this.dirty()?void 0:t),t,n)}async getAllFromIndex(e,t,n){let r=jx(t);return this.overlay(await this.serverRows(`index/${encodeURIComponent(e)}`,r,this.dirty()?void 0:n),n,r,e)}async count(e){let t=jx(e);return this.dirty()?this.overlay(await this.serverRows(`all`,t),void 0,t).length:Kx(this.http,this.store,t)}async countFromIndex(e,t){let n=jx(t);return this.dirty()?this.overlay(await this.serverRows(`index/${encodeURIComponent(e)}`,n),void 0,n,e).length:Kx(this.http,this.store,n,e)}async serverRows(e,t,n){if(this.cleared?.has(this.store))return[];let r=await noe(this.http,this.store,e,t,n);for(let e of r){let t=Ax(this.def,e),n=Rx(this.store,t);this.checks?.has(n)||this.checks?.set(n,{op:`check`,store:this.store,key:t,value:structuredClone(e)})}return r}overlay(e,t,n,r){return Zae(this.def,this.store,this.buffer,this.cleared,e,t,n,r)}async put(e,t){if(!this.mutable)throw Error(`read-only store`);let n=this.getUserId?.(),r=n?Dx(this.store,e,n):e,i=Ax(this.def,r);if(this.store===`block_revisions`||this.store===`note_revisions`){let e=this.buffer?.get(Rx(this.store,i));if(e?.kind===`put`&&!Vx(e.value,r))throw Error(this.store===`note_revisions`?`immutable note revision collision`:`immutable block revision collision`)}return this.buffer?(this.buffer.set(Rx(this.store,i),{kind:`put`,value:r}),i):(await Gx(this.http,`POST`,`/tx`,{body:{ops:[{op:`put`,store:this.store,value:r}]}}),i)}async putMany(e,t){if(!this.mutable)throw Error(`read-only store`);if(this.buffer){let t=[];for(let n of e)t.push(await this.put(n));return t}let n=e.map(e=>this.getUserId?Dx(this.store,e,this.getUserId()):e),r=n.map(e=>Ax(this.def,e));return await Gx(this.http,`POST`,`/tx`,{body:{ops:n.map(e=>({op:`put`,store:this.store,value:e}))}}),r}async delete(e){if(!this.mutable)throw Error(`read-only store`);if(this.store===`block_revisions`||this.store===`note_revisions`)throw Error(`block history requires explicit wipe`);let t=Ox(e)?e:void 0;if(t){if(this.buffer){let e=await this.getAll(t);for(let t of e){let e=Ax(this.def,t);this.buffer.set(Rx(this.store,e),{kind:`delete`,key:e})}return}await qx(this.http,this.store,t);return}let n=e;if(this.buffer){this.buffer.set(Rx(this.store,n),{kind:`delete`,key:n});return}await qx(this.http,this.store,n)}async clear(){if(!this.mutable)throw Error(`read-only store`);if(this.store===`block_revisions`||this.store===`note_revisions`)throw Error(`block history requires explicit wipe`);if(this.buffer){this.cleared?.add(this.store);let e=`${this.store}\u0000`;for(let t of[...this.buffer.keys()])t.startsWith(e)&&this.buffer.delete(t);return}await Gx(this.http,`POST`,`/tx`,{body:{ops:[{op:`clear`,store:this.store}]}})}},aoe=`user-deleted-seed:`;function Jx(e){return`${aoe}${e}`}function ooe(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function soe(e){return typeof e==`string`&&e.startsWith(`seed:`)}function Yx(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 Xx(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`property_overrides`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`meta`:return!soe(`key`in t?t.key:void 0);default:return!0}}function Zx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qx(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function $x(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function eS(e){return typeof e==`number`&&Number.isFinite(e)}function tS(e){return typeof e==`string`&&e.length>0&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)}function nS(e){if(typeof e!=`string`||!e.trim())return!1;if(/^https?:\/\//i.test(e))try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password}catch{return!1}return tS(e)}function rS(e){if(!Zx(e))throw Error(`Incompatible seed schema; rebuild seed artifacts`);let t=Array.isArray(e.notebooks);if(e.schema===void 0){if(!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`)}else if(!Qx(e.schema)||e.schema!==9&&!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`);let n=e.schema===void 0?9:e.schema,r=e.version===void 0&&t?1:e.version,i=e.builtAt===void 0&&t?new Date(0).toISOString():e.builtAt,a=e.chunks===void 0&&t?[]:e.chunks;if(!$x(r)||typeof i!=`string`||!Number.isFinite(Date.parse(i))||!Array.isArray(a))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`);for(let t of[`indexBytes`,`chunkBytes`])if(e[t]!==void 0&&!$x(e[t]))throw Error(`invalid seed manifest metadata`);let o=new Set,s=new Set;for(let e of a){if(!Zx(e)||typeof e.id!=`string`||!e.id||typeof e.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(e.path)||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256)||!$x(e.bytes)||!$x(e.count)||e.kind!==void 0&&e.kind!==`notes`||o.has(e.id)||s.has(e.path))throw Error(`seed manifest failed shape validation`);o.add(e.id),s.add(e.path)}let c;if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);c=[];for(let t of e.notebooks){if(!Zx(t)||typeof t.notebookId!=`string`||!t.notebookId||typeof t.label!=`string`||!$x(t.count)||!nS(t.indexPath))throw Error(`seed manifest failed shape validation`);if(`records`in t&&Array.isArray(t.records))throw Error(`seed manifest failed shape validation: manifest.notebooks must not contain inline records`);if(t.version!==void 0&&!$x(t.version)||t.commit!==void 0&&typeof t.commit!=`string`||t.builtAt!==void 0&&typeof t.builtAt!=`string`||t.sha256!==void 0&&typeof t.sha256!=`string`||t.bytes!==void 0&&!$x(t.bytes)||t.indexBytes!==void 0&&!$x(t.indexBytes)||t.chunkBytes!==void 0&&!$x(t.chunkBytes))throw Error(`seed manifest failed shape validation`);c.push({...t,version:t.version??r,commit:t.commit??``,builtAt:t.builtAt??i,sha256:t.sha256??``,bytes:t.bytes??t.indexBytes??0})}}return{...e,schema:n,version:r,builtAt:i,chunks:a,...c===void 0?{}:{notebooks:c}}}function iS(e){if(!Zx(e))throw Error(`notebook index failed shape validation`);if(typeof e.notebookId!=`string`||!e.notebookId||typeof e.label!=`string`||!e.label||!nS(e.indexPath)||!$x(e.count)||!Array.isArray(e.records)||e.version!==void 0&&!$x(e.version)||e.commit!==void 0&&typeof e.commit!=`string`||e.builtAt!==void 0&&typeof e.builtAt!=`string`||e.sha256!==void 0&&typeof e.sha256!=`string`||e.bytes!==void 0&&!$x(e.bytes))throw Error(`notebook index failed shape validation: missing required index summary or records`);let t=[];for(let n of e.records){if(!Zx(n)||typeof n.uuid!=`string`||!n.uuid||!tS(n.path))throw Error(`notebook index failed shape validation: invalid record ref`);let e=n.recordPath!==void 0,r=n.rawUrl!==void 0,i=/\.md$/i.test(n.path);if(e&&!tS(n.recordPath)||r&&!nS(n.rawUrl)||!e&&!r&&!i||n.commit!==void 0&&typeof n.commit!=`string`||n.version!==void 0&&!$x(n.version)||n.sha256!==void 0&&typeof n.sha256!=`string`||n.title!==void 0&&typeof n.title!=`string`||n.date!==void 0&&!eS(n.date))throw Error(`notebook index failed shape validation: invalid record ref`);t.push({...n,commit:n.commit??``,version:n.version??1,sha256:n.sha256??``})}return{...e,version:e.version??1,commit:e.commit??``,builtAt:e.builtAt??new Date(0).toISOString(),sha256:e.sha256??``,bytes:e.bytes??0,records:t}}function coe(e,t){if(e.telemetry===void 0)return;if(!Zx(e.telemetry)||!Array.isArray(e.telemetry.sessions)||!Array.isArray(e.telemetry.events))throw Error(`invalid seed telemetry`);let n=new Map;for(let r of e.telemetry.sessions){if(!Zx(r)||typeof r.id!=`string`||!r.id||n.has(r.id)||typeof r.noteId!=`string`||!r.noteId||typeof e.uuid==`string`&&r.noteId!==e.uuid||typeof r.blockId!=`string`||!Qx(r.blockVersion)||typeof r.blockContentId!=`string`||!eS(r.startTime)||!eS(r.endTime)||!eS(r.duration)||typeof r.completed!=`boolean`||!eS(r.createdAt))throw Error(`invalid seed session`);let i=t.find(e=>Zx(e)&&e.blockId===r.blockId);if(!Zx(i)||i.dataType!==`wod`||i.blockVersion!==r.blockVersion||i.blockContentId!==r.blockContentId)throw Error(`orphan or incompatible seed session pin`);n.set(r.id,r)}let r=new Set;for(let t of e.telemetry.events){if(!Zx(t)||typeof t.id!=`string`||!t.id||r.has(t.id)||typeof t.resultId!=`string`||typeof t.noteId!=`string`||!eS(t.timestamp)||t.grain!==`event`&&t.grain!==`summary`||typeof t.outputType!=`string`||!Array.isArray(t.metrics)||!t.metrics.every(e=>Zx(e)&&typeof e.type==`string`)||t.grain===`summary`&&t.metrics.length!==1)throw Error(`invalid seed event`);let e=n.get(t.resultId);if(!e||t.noteId!==e.noteId||t.blockId!==e.blockId||t.blockVersion!==e.blockVersion||t.blockContentId!==e.blockContentId)throw Error(`orphan or incompatible seed event identity`);r.add(t.id)}}function aS(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!Zx(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!Zx(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(!Zx(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!$x(t.from)||!Qx(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`);Hs(n.content,n.blocks,1,{registeredWidgets:fx});let e=new Set,r=zs(n.content,{registeredWidgets:fx});for(let t of n.blockIndex){if(!Zx(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!Zx(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&&!$x(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!==os(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(!Zx(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))||!Zx(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=>Zx(e)&&e.blockId===t.blockId);if(!Zx(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(!Zx(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))||!Zx(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=>Zx(e)&&e.blockId===t.blockId);if(!Zx(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}coe(n,n.blockIndex)}return e}function oS(e){return aS([e])[0]}function sS(e,t,n){return`${e}:${t}:${n}`}function cS(e){let t=[];for(let[n,r]of Object.entries(e.metrics)){if(typeof r!=`string`&&typeof r!=`number`)continue;let e=String(r).trim().match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);e?t.push({kind:`metric`,type:n,value:Number(e[1]),unit:e[2]}):t.push({kind:`metric`,type:n,value:r})}for(let[n,r]of Object.entries(e.summaries))t.push({kind:`metric`,type:`summaries.${n}`,value:r});for(let[n,r]of Object.entries(e.widgets??{}))t.push({kind:`metric`,type:`widgets.${n}`,value:r});for(let n of e.tags)t.push({kind:`tag`,slug:n});for(let n of e.functions)t.push({kind:`function`,name:n});return t}async function lS(e,t){let n=Cs(t.targetNotebookId);if(bs(n))throw Error(`Notebook '${n}' is read-only and cannot store overrides.`);if(n===`notebook/journal`||n===`notebook/playground`)throw Error(`Property overrides belong in 'notebook/custom' or a shared user Notebook, not '${n}'.`);let r=t.slug.trim().toLowerCase();if(!r)throw Error(`Property override requires a non-empty canonical slug.`);let i=Ss(n),a=`override/${i}/${t.kind}/${r}`,o=`${t.kind}-override-${i}-${r}`,s=Date.now(),c=t.rawContent,l=qb(c);(typeof l.id!=`string`||!l.id.trim())&&(c=tc(c,[`id`],o)),(typeof l.slug!=`string`||l.slug.trim()!==r)&&(c=tc(c,[`slug`],r));let u=t.title?.trim()||r,d;if(t.kind===`effort`){let e=Ld(c);if(e.errors.length>0)throw Error(e.errors.join(`
|
|
154
|
+
`),r=u(e);r.sessions.push(n.session),r.events.push(...n.events)}catch(e){c.push(e instanceof Error?e.message:String(e))}return{bundles:[...l.values()],errors:c}}var Fae=`0.63.2267`,fx=Ns,Iae=`1b671a64-40d5-491e-99b0-da01ff1f3341`,Lae={core:0,community:1,imported:2,user:3};function Rae(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 px(e,t){return Lae[Rae(e,t)]}var mx=`wodwiki.seed`,hx=`feed:index:`;function gx(e,t){return`${hx}${e}:${t}`}var _x=`efforts`,vx=`equipment`,yx=`canvas`;function bx(e){return`seed:${e}`}function zae(e){return e.startsWith(`seed:`)?e.slice(5):e}function xx(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Sx(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function Bae(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 Vae(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:${Bae(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Sx(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}var Cx=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-type`,keyPath:[`type`]},{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:`note_revisions`,keyPath:[`noteId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]}]},{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-session-date`,keyPath:[`sessionDate`]},{name:`by-schedule-item`,keyPath:[`scheduleItemId`]},{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:`notebook_links`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-target`,keyPath:[`targetKind`,`targetId`]},{name:`by-notebook-target`,keyPath:[`notebookId`,`targetKind`,`targetId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`property_overrides`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-kind-slug`,keyPath:[`kind`,`slug`]},{name:`by-owner-note`,keyPath:[`ownerNoteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`schedule_items`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-date-note`,keyPath:[`date`,`noteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],wx=`default`;function Tx(e=Date.now()){return{id:wx,displayName:`Anonymous`,createdAt:e}}var Ex=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`,`notebook_links`,`property_overrides`,`schedule_items`],Hae=Object.fromEntries(Ex.map(e=>[e,!0]));function Dx(e,t,n){if(!Hae[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 Ox(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(`only`in e||`lower`in e||`upper`in e||`lowerOpen`in e||`upperOpen`in e)}function kx(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 Ax(e,t){let n=e.keyPath.map(e=>kx(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}function Uae(e){return encodeURIComponent(JSON.stringify(e))}function jx(e){if(e===void 0)return;if(!Ox(e))return{only:e};if(e.only!==void 0)return e;let t={};return e.lower!==void 0&&e.lower!==null&&(t.lower=e.lower,t.lowerOpen=e.lowerOpen===!0),e.upper!==void 0&&e.upper!==null&&(t.upper=Array.isArray(e.upper)?e.upper.map(e=>Array.isArray(e)&&e.length===0?``:e):e.upper,t.upperOpen=e.upperOpen===!0),t.lower!==void 0||t.upper!==void 0?t:void 0}function Mx(e,t){if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t))return Array.isArray(e)?1:-1;for(let n=0;n<Math.min(e.length,t.length);n++){let r=Mx(e[n],t[n]);if(r!==0)return r}return e.length-t.length}return typeof e==`number`&&typeof t==`number`?e<t?-1:+(e>t):typeof e==`number`||typeof t==`number`?typeof e==`number`?-1:1:e<t?-1:+(e>t)}function Nx(e,t){if(t.only!==void 0)return Mx(e,t.only)===0;if(t.lower!==void 0){let n=Mx(e,t.lower);if(n<0||n===0&&t.lowerOpen===!0)return!1}if(t.upper!==void 0){let n=Mx(e,t.upper);if(n>0||n===0&&t.upperOpen===!0)return!1}return!0}function Px(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fx(e,t){return t.every(t=>e[t]===void 0||typeof e[t]==`string`)}function Ix(e,t){return t.every(t=>typeof e[t]==`number`&&Number.isFinite(e[t]))}function Lx(e){if(!Px(e)||typeof e.id!=`string`||typeof e.title!=`string`||typeof e.rawContent!=`string`||!Number.isSafeInteger(e.sourceRevision)||typeof e.sourceRevision!=`number`||e.sourceRevision<1||!Px(e.blocks)||!Ix(e,[`createdAt`])||e.date!==void 0&&!Ix(e,[`date`])||!Fx(e,[`type`,`sourceId`,`notebookId`,`sourcePath`,`seedOrigin`,`seedChunkId`,`feedOrigin`,`feedSourceId`])||e.tags!==void 0&&(!Array.isArray(e.tags)||!e.tags.every(e=>typeof e==`string`)))return!1;try{return Hs(e.rawContent,e.blocks,e.sourceRevision),!0}catch{return!1}}function Wae(e){return Px(e)&&typeof e.id==`string`&&typeof e.noteId==`string`&&typeof e.blockId==`string`&&Ix(e,[`blockVersion`,`sourceRevision`,`from`,`to`,`createdAt`])&&e.id===`${e.noteId}:${e.blockId}`&&typeof e.blockVersion==`number`&&Number.isSafeInteger(e.blockVersion)&&e.blockVersion>0&&typeof e.sourceRevision==`number`&&Number.isSafeInteger(e.sourceRevision)&&e.sourceRevision>0&&typeof e.from==`number`&&Number.isSafeInteger(e.from)&&e.from>=0&&typeof e.to==`number`&&Number.isSafeInteger(e.to)&&e.to>e.from&&[`wod`,`query`,`widget`,`embed`].includes(String(e.dataType))&&typeof e.rawContent==`string`&&typeof e.noteTitle==`string`&&Fx(e,[`blockContentId`,`sourceId`,`sourcePath`,`routeId`])&&(e.position===void 0||Ix(e,[`position`]))&&(e.isStatic===void 0||typeof e.isStatic==`boolean`)}function Gae(e){return Px(e)&&typeof e.id==`string`&&typeof e.label==`string`&&Ix(e,[`createdAt`])&&Fx(e,[`type`])}function Kae(e){return Px(e)&&typeof e.id==`string`&&Ix(e,[`createdAt`])&&Fx(e,[`date`,`slug`,`title`])}function qae(e){return Px(e)&&typeof e.id==`string`&&typeof e.noteId==`string`&&typeof e.pageId==`string`&&Ix(e,[`createdAt`])&&(e.position===void 0||Ix(e,[`position`]))}function Jae(e){return Px(e)&&Lx(e.note)&&Array.isArray(e.tags)&&e.tags.every(Gae)&&Array.isArray(e.links)&&e.links.every(qae)&&Array.isArray(e.pages)&&e.pages.every(Kae)}function Yae(e,t){if(!Px(e)||e.projectionVersion!==5||e.plan!==t||!Array.isArray(e.rows)||typeof e.selectedCount!=`number`||!Number.isSafeInteger(e.selectedCount)||e.selectedCount<0||typeof e.matchedCount!=`number`||!Number.isSafeInteger(e.matchedCount)||e.matchedCount<0||e.matchedCount>e.selectedCount||e.rows.length>e.matchedCount)throw Error(`ApiStorage: invalid or stale domain projection response`);let n={projectionVersion:5,selectedCount:e.selectedCount,matchedCount:e.matchedCount};switch(t){case`notes`:if(e.rows.every(Lx))return{...n,plan:t,rows:e.rows};break;case`blocks`:if(e.rows.every(Wae))return{...n,plan:t,rows:e.rows};break;case`detail`:if(e.rows.every(Jae))return{...n,plan:t,rows:e.rows}}throw Error(`ApiStorage: invalid domain query rows`)}var Rx=(e,t)=>`${e}\u0000${JSON.stringify(t)}`;function zx(e,t,n){if(n?.has(e))return!0;if(!t)return!1;let r=`${e}\u0000`;for(let e of t.keys())if(e.startsWith(r))return!0;return!1}function Xae(e,t,n){if(!n)return;let r=n.get(Rx(e,t));if(r)return r.kind===`put`?{hit:!0,value:r.value}:{hit:!1}}function Zae(e,t,n,r,i,a,o,s){if(!n||!zx(t,n,r))return a===void 0?i:i.slice(0,a);let c=new Map;if(!r?.has(t))for(let t of i)c.set(JSON.stringify(Ax(e,t)),t);let l=`${t}\u0000`;for(let[e,t]of n)e.startsWith(l)&&(t.kind===`put`?c.set(e.slice(l.length),t.value):c.delete(e.slice(l.length)));let u=s?e.indexes.find(e=>e.name===s):void 0;if(s&&!u)throw Error(`unknown index '${s}' for ${t}`);let d=t=>{if(!u)return Ax(e,t);let n=u.keyPath.map(e=>kx(t,e));if(n.some(e=>e===void 0))return;let r=n.filter(e=>e!==void 0);return r.length===1?r[0]:r},f=e=>{if(u?.multiEntry){let t=e;for(let e of u.keyPath[0].split(`.`)){if(typeof t!=`object`||!t||!(e in t))return!1;t=Reflect.get(t,e)}return Array.isArray(t)&&t.some(e=>(typeof e==`string`||typeof e==`number`)&&(!o||Nx(e,o)))}let t=d(e);return t!==void 0&&(!o||Nx(t,o))},p=[...c.values()].filter(f);return p.sort((t,n)=>{let r=Mx(Ax(e,t),Ax(e,n));if(u?.multiEntry)return r;let i=d(t),a=d(n);return i!==void 0&&a!==void 0&&Mx(i,a)||r}),a===void 0?p:p.slice(0,a)}function Qae(e,t,n){let r=new Set(e),i=[];for(let e of n)r.has(e)&&i.push({op:`clear`,store:e});for(let[e,n]of t){let t=e.indexOf(`\0`),a=e.slice(0,t);r.has(a)&&(n.kind===`put`?i.push({op:`put`,store:a,value:n.value}):i.push({op:`delete`,store:a,key:JSON.parse(e.slice(t+1))}))}return i}var Bx=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function Vx(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)=>Vx(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)&&Vx(Reflect.get(e,n),Reflect.get(t,n)))}function Hx(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new Bx(400,`storage row must be an object`);return e}function Ux(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`note_revisions`&&e!==`sessions`&&e!==`block_index`&&e!==`schedule_items`)return;let n=Hx(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.feedOrigin!==void 0&&n.feedOrigin!==`feed`&&n.feedOrigin!==`user`||n.feedOrigin===`feed`&&(n.seedOrigin===void 0||typeof n.feedSourceId!=`string`||n.feedSourceId.length===0)||n.feedOrigin===`user`&&n.seedOrigin===`seed`||n.feedSourceId!==void 0&&n.feedOrigin!==`feed`||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`))||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.provenance!==void 0&&(typeof n.provenance!=`object`||n.provenance===null||Array.isArray(n.provenance)||typeof n.provenance.sourceNoteId!=`string`)||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Bx(400,`invalid whole Note`,`invalid_note_blocks`);try{Hs(n.rawContent,Hx(n.blocks),n.sourceRevision)}catch(e){throw new Bx(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 Bx(400,`invalid block revision`,`invalid_note_blocks`);try{Hs(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 Bx(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`note_revisions`){if(!i(`noteId`)||!r(`version`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.type!==void 0&&typeof n.type!=`string`)throw new Bx(400,`invalid note revision`,`invalid_note_blocks`);try{Hs(n.rawContent,Hx(n.blocks),n.version)}catch(e){throw new Bx(400,e instanceof Error?e.message:`invalid note revision blocks`,`invalid_note_blocks`)}}else if(e===`schedule_items`){if(!i(`id`)||!i(`date`)||!i(`noteId`)||typeof n.position!=`number`||!Number.isFinite(n.position)||![`planned`,`completed`,`skipped`,`moved`].includes(String(n.status))||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||[`pageId`,`sourceNotebookId`,`fallbackTitle`,`blockId`,`slot`,`notes`,`movedFromDate`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Bx(400,`invalid schedule item`,`invalid_schedule_item`)}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||n.noteSourceRevision!==void 0&&!r(`noteSourceRevision`)||n.sessionDate!==void 0&&typeof n.sessionDate!=`string`||n.scheduleItemId!==void 0&&typeof n.scheduleItemId!=`string`||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new Bx(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 Bx(400,`invalid actionable block projection`,`invalid_note_blocks`)}function $ae(e,t){if(e===void 0||Vx(e,t))return;let n=Hx(e),r=Hx(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!Vx(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new Bx(409,`stale Note source revision`,`transaction_conflict`)}function eoe(e,t){if(e===void 0)return;let n=Hx(e),r=Hx(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new Bx(409,`Session pin is immutable`,`invalid_session_pin`)}async function Wx(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 Bx(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 Bx(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}async function Gx(e,t,n,r){let i=r?.params?.toString(),a=await e.fetchImpl(`${e.baseUrl}/v1${n}${i?`?${i}`:``}`,{method:t,headers:r?.body===void 0?void 0:{"content-type":`application/json`},body:r?.body===void 0?void 0:JSON.stringify(r.body)});if(!a.ok)throw Error(`ApiStorage: ${t} /v1${n} → ${a.status}`);return a}async function toe(e,t,n){let r=await e.fetchImpl(`${e.baseUrl}/v1/${t}/get?key=${Uae(n)}`);if(r.status!==404){if(!r.ok)throw Error(`ApiStorage: GET /v1/${t}/get → ${r.status}`);return await r.json()}}async function noe(e,t,n,r,i){let a=new URLSearchParams;return r&&a.set(`range`,JSON.stringify(r)),i!==void 0&&a.set(`count`,String(i)),await(await Gx(e,`GET`,`/${t}/${n}`,{params:a})).json()}async function Kx(e,t,n,r){let i=new URLSearchParams;return n&&i.set(`range`,JSON.stringify(n)),r!==void 0&&i.set(`index`,r),(await(await Gx(e,`GET`,`/${t}/count`,{params:i})).json()).count}async function qx(e,t,n){await Gx(e,`DELETE`,`/${t}`,{params:new URLSearchParams({key:JSON.stringify(n)})})}var roe=class{http;defs;getUserId;writeChain=Promise.resolve();constructor(e=`/api`,t=globalThis.fetch.bind(globalThis),n={}){this.http={baseUrl:e,fetchImpl:t},this.getUserId=n.getUserId,this.defs=Object.fromEntries(Cx.map(e=>[e.name,e]))}def(e){let t=this.defs[e];if(!t)throw Error(`ApiStorage: unknown store '${e}'`);return t}makeView(e,t,n,r,i=!1){return new ioe(this.http,this.def(e),e,t,n,this.getUserId,r,i)}readonly(e){return this.makeView(e)}readwrite(e){return this.makeView(e,void 0,void 0,void 0,!0)}async queryDomain(e){let t=await this.http.fetchImpl(`${this.http.baseUrl}/v1/query`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(t.status===409){let e=await t.json();if(typeof e==`object`&&e&&`code`in e&&e.code===`domain_projection_unavailable`)return}if(!t.ok)throw Error(`ApiStorage: POST /v1/query → ${t.status}`);return Yae(await t.json(),e.plan)}async transaction(e,t,n){let r=async()=>{let r=new Map,i=new Set,a=new Map,o=new Set(e),s=(e,n)=>{if(!o.has(e))throw Error(`store outside transaction scope`);if(n&&t!==`readwrite`)throw Error(`read-only transaction`);return this.makeView(e,r,i,a,n)},c=await n({readonly:e=>s(e,!1),readwrite:e=>s(e,!0)});return await this.flush(r,i,a),c};if(t!==`readwrite`)return r();let i=this.writeChain.then(r,r);return this.writeChain=i.then(()=>void 0,()=>void 0),i}async flush(e,t,n){let r=Qae(Cx.map(e=>e.name),e,t);r.length>0&&await Gx(this.http,`POST`,`/tx`,{body:{ops:[...n.values(),...r]}})}async wipe(){await Gx(this.http,`POST`,`/wipe`)}async close(){}},ioe=class{http;def;store;buffer;cleared;getUserId;checks;mutable;constructor(e,t,n,r,i,a,o,s=!1){this.http=e,this.def=t,this.store=n,this.buffer=r,this.cleared=i,this.getUserId=a,this.checks=o,this.mutable=s}dirty(){return zx(this.store,this.buffer,this.cleared)}async get(e){let t=Ox(e)?e:void 0,n;if(t){if(t.only===void 0)throw Error(`ApiStorage.get: needs a plain key or {only}; bounded ranges match no single row`);n=t.only}else n=e;let r=Xae(this.store,n,this.buffer);if(r)return r.hit?r.value:void 0;if(this.cleared?.has(this.store))return;let i=await toe(this.http,this.store,n),a=Rx(this.store,n);return this.checks?.has(a)||this.checks?.set(a,{op:`check`,store:this.store,key:n,value:structuredClone(i??null)}),i}async getMany(e){return Promise.all(e.map(e=>this.get(e)))}async getAllFromIndexMany(e,t){return Promise.all(t.map(t=>this.getAllFromIndex(e,t)))}async getAll(e,t){let n=jx(e);return this.overlay(await this.serverRows(`all`,n,this.dirty()?void 0:t),t,n)}async getAllFromIndex(e,t,n){let r=jx(t);return this.overlay(await this.serverRows(`index/${encodeURIComponent(e)}`,r,this.dirty()?void 0:n),n,r,e)}async count(e){let t=jx(e);return this.dirty()?this.overlay(await this.serverRows(`all`,t),void 0,t).length:Kx(this.http,this.store,t)}async countFromIndex(e,t){let n=jx(t);return this.dirty()?this.overlay(await this.serverRows(`index/${encodeURIComponent(e)}`,n),void 0,n,e).length:Kx(this.http,this.store,n,e)}async serverRows(e,t,n){if(this.cleared?.has(this.store))return[];let r=await noe(this.http,this.store,e,t,n);for(let e of r){let t=Ax(this.def,e),n=Rx(this.store,t);this.checks?.has(n)||this.checks?.set(n,{op:`check`,store:this.store,key:t,value:structuredClone(e)})}return r}overlay(e,t,n,r){return Zae(this.def,this.store,this.buffer,this.cleared,e,t,n,r)}async put(e,t){if(!this.mutable)throw Error(`read-only store`);let n=this.getUserId?.(),r=n?Dx(this.store,e,n):e,i=Ax(this.def,r);if(this.store===`block_revisions`||this.store===`note_revisions`){let e=this.buffer?.get(Rx(this.store,i));if(e?.kind===`put`&&!Vx(e.value,r))throw Error(this.store===`note_revisions`?`immutable note revision collision`:`immutable block revision collision`)}return this.buffer?(this.buffer.set(Rx(this.store,i),{kind:`put`,value:r}),i):(await Gx(this.http,`POST`,`/tx`,{body:{ops:[{op:`put`,store:this.store,value:r}]}}),i)}async putMany(e,t){if(!this.mutable)throw Error(`read-only store`);if(this.buffer){let t=[];for(let n of e)t.push(await this.put(n));return t}let n=e.map(e=>this.getUserId?Dx(this.store,e,this.getUserId()):e),r=n.map(e=>Ax(this.def,e));return await Gx(this.http,`POST`,`/tx`,{body:{ops:n.map(e=>({op:`put`,store:this.store,value:e}))}}),r}async delete(e){if(!this.mutable)throw Error(`read-only store`);if(this.store===`block_revisions`||this.store===`note_revisions`)throw Error(`block history requires explicit wipe`);let t=Ox(e)?e:void 0;if(t){if(this.buffer){let e=await this.getAll(t);for(let t of e){let e=Ax(this.def,t);this.buffer.set(Rx(this.store,e),{kind:`delete`,key:e})}return}await qx(this.http,this.store,t);return}let n=e;if(this.buffer){this.buffer.set(Rx(this.store,n),{kind:`delete`,key:n});return}await qx(this.http,this.store,n)}async clear(){if(!this.mutable)throw Error(`read-only store`);if(this.store===`block_revisions`||this.store===`note_revisions`)throw Error(`block history requires explicit wipe`);if(this.buffer){this.cleared?.add(this.store);let e=`${this.store}\u0000`;for(let t of[...this.buffer.keys()])t.startsWith(e)&&this.buffer.delete(t);return}await Gx(this.http,`POST`,`/tx`,{body:{ops:[{op:`clear`,store:this.store}]}})}},aoe=`user-deleted-seed:`;function Jx(e){return`${aoe}${e}`}function ooe(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function soe(e){return typeof e==`string`&&e.startsWith(`seed:`)}function Yx(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 Xx(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`property_overrides`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`meta`:return!soe(`key`in t?t.key:void 0);default:return!0}}function Zx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qx(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function $x(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function eS(e){return typeof e==`number`&&Number.isFinite(e)}function tS(e){return typeof e==`string`&&e.length>0&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)}function nS(e){if(typeof e!=`string`||!e.trim())return!1;if(/^https?:\/\//i.test(e))try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password}catch{return!1}return tS(e)}function rS(e){if(!Zx(e))throw Error(`Incompatible seed schema; rebuild seed artifacts`);let t=Array.isArray(e.notebooks);if(e.schema===void 0){if(!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`)}else if(!Qx(e.schema)||e.schema!==9&&!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`);let n=e.schema===void 0?9:e.schema,r=e.version===void 0&&t?1:e.version,i=e.builtAt===void 0&&t?new Date(0).toISOString():e.builtAt,a=e.chunks===void 0&&t?[]:e.chunks;if(!$x(r)||typeof i!=`string`||!Number.isFinite(Date.parse(i))||!Array.isArray(a))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`);for(let t of[`indexBytes`,`chunkBytes`])if(e[t]!==void 0&&!$x(e[t]))throw Error(`invalid seed manifest metadata`);let o=new Set,s=new Set;for(let e of a){if(!Zx(e)||typeof e.id!=`string`||!e.id||typeof e.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(e.path)||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256)||!$x(e.bytes)||!$x(e.count)||e.kind!==void 0&&e.kind!==`notes`||o.has(e.id)||s.has(e.path))throw Error(`seed manifest failed shape validation`);o.add(e.id),s.add(e.path)}let c;if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);c=[];for(let t of e.notebooks){if(!Zx(t)||typeof t.notebookId!=`string`||!t.notebookId||typeof t.label!=`string`||!$x(t.count)||!nS(t.indexPath))throw Error(`seed manifest failed shape validation`);if(`records`in t&&Array.isArray(t.records))throw Error(`seed manifest failed shape validation: manifest.notebooks must not contain inline records`);if(t.version!==void 0&&!$x(t.version)||t.commit!==void 0&&typeof t.commit!=`string`||t.builtAt!==void 0&&typeof t.builtAt!=`string`||t.sha256!==void 0&&typeof t.sha256!=`string`||t.bytes!==void 0&&!$x(t.bytes)||t.indexBytes!==void 0&&!$x(t.indexBytes)||t.chunkBytes!==void 0&&!$x(t.chunkBytes))throw Error(`seed manifest failed shape validation`);c.push({...t,version:t.version??r,commit:t.commit??``,builtAt:t.builtAt??i,sha256:t.sha256??``,bytes:t.bytes??t.indexBytes??0})}}return{...e,schema:n,version:r,builtAt:i,chunks:a,...c===void 0?{}:{notebooks:c}}}function iS(e){if(!Zx(e))throw Error(`notebook index failed shape validation`);if(typeof e.notebookId!=`string`||!e.notebookId||typeof e.label!=`string`||!e.label||!nS(e.indexPath)||!$x(e.count)||!Array.isArray(e.records)||e.version!==void 0&&!$x(e.version)||e.commit!==void 0&&typeof e.commit!=`string`||e.builtAt!==void 0&&typeof e.builtAt!=`string`||e.sha256!==void 0&&typeof e.sha256!=`string`||e.bytes!==void 0&&!$x(e.bytes))throw Error(`notebook index failed shape validation: missing required index summary or records`);let t=[];for(let n of e.records){if(!Zx(n)||typeof n.uuid!=`string`||!n.uuid||!tS(n.path))throw Error(`notebook index failed shape validation: invalid record ref`);let e=n.recordPath!==void 0,r=n.rawUrl!==void 0,i=/\.md$/i.test(n.path);if(e&&!tS(n.recordPath)||r&&!nS(n.rawUrl)||!e&&!r&&!i||n.commit!==void 0&&typeof n.commit!=`string`||n.version!==void 0&&!$x(n.version)||n.sha256!==void 0&&typeof n.sha256!=`string`||n.title!==void 0&&typeof n.title!=`string`||n.date!==void 0&&!eS(n.date))throw Error(`notebook index failed shape validation: invalid record ref`);t.push({...n,commit:n.commit??``,version:n.version??1,sha256:n.sha256??``})}return{...e,version:e.version??1,commit:e.commit??``,builtAt:e.builtAt??new Date(0).toISOString(),sha256:e.sha256??``,bytes:e.bytes??0,records:t}}function coe(e,t){if(e.telemetry===void 0)return;if(!Zx(e.telemetry)||!Array.isArray(e.telemetry.sessions)||!Array.isArray(e.telemetry.events))throw Error(`invalid seed telemetry`);let n=new Map;for(let r of e.telemetry.sessions){if(!Zx(r)||typeof r.id!=`string`||!r.id||n.has(r.id)||typeof r.noteId!=`string`||!r.noteId||typeof e.uuid==`string`&&r.noteId!==e.uuid||typeof r.blockId!=`string`||!Qx(r.blockVersion)||typeof r.blockContentId!=`string`||!eS(r.startTime)||!eS(r.endTime)||!eS(r.duration)||typeof r.completed!=`boolean`||!eS(r.createdAt))throw Error(`invalid seed session`);let i=t.find(e=>Zx(e)&&e.blockId===r.blockId);if(!Zx(i)||i.dataType!==`wod`||i.blockVersion!==r.blockVersion||i.blockContentId!==r.blockContentId)throw Error(`orphan or incompatible seed session pin`);n.set(r.id,r)}let r=new Set;for(let t of e.telemetry.events){if(!Zx(t)||typeof t.id!=`string`||!t.id||r.has(t.id)||typeof t.resultId!=`string`||typeof t.noteId!=`string`||!eS(t.timestamp)||t.grain!==`event`&&t.grain!==`summary`||typeof t.outputType!=`string`||!Array.isArray(t.metrics)||!t.metrics.every(e=>Zx(e)&&typeof e.type==`string`)||t.grain===`summary`&&t.metrics.length!==1)throw Error(`invalid seed event`);let e=n.get(t.resultId);if(!e||t.noteId!==e.noteId||t.blockId!==e.blockId||t.blockVersion!==e.blockVersion||t.blockContentId!==e.blockContentId)throw Error(`orphan or incompatible seed event identity`);r.add(t.id)}}function aS(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!Zx(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!Zx(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(!Zx(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!$x(t.from)||!Qx(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`);Hs(n.content,n.blocks,1,{registeredWidgets:fx});let e=new Set,r=zs(n.content,{registeredWidgets:fx});for(let t of n.blockIndex){if(!Zx(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!Zx(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&&!$x(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!==os(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(!Zx(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))||!Zx(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=>Zx(e)&&e.blockId===t.blockId);if(!Zx(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(!Zx(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))||!Zx(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=>Zx(e)&&e.blockId===t.blockId);if(!Zx(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}coe(n,n.blockIndex)}return e}function oS(e){return aS([e])[0]}function sS(e,t,n){return`${e}:${t}:${n}`}function cS(e){let t=[];for(let[n,r]of Object.entries(e.metrics)){if(typeof r!=`string`&&typeof r!=`number`)continue;let e=String(r).trim().match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);e?t.push({kind:`metric`,type:n,value:Number(e[1]),unit:e[2]}):t.push({kind:`metric`,type:n,value:r})}for(let[n,r]of Object.entries(e.summaries))t.push({kind:`metric`,type:`summaries.${n}`,value:r});for(let[n,r]of Object.entries(e.widgets??{}))t.push({kind:`metric`,type:`widgets.${n}`,value:r});for(let n of e.tags)t.push({kind:`tag`,slug:n});for(let n of e.functions)t.push({kind:`function`,name:n});return t}async function lS(e,t){let n=Cs(t.targetNotebookId);if(bs(n))throw Error(`Notebook '${n}' is read-only and cannot store overrides.`);if(n===`notebook/journal`||n===`notebook/playground`)throw Error(`Property overrides belong in 'notebook/custom' or a shared user Notebook, not '${n}'.`);let r=t.slug.trim().toLowerCase();if(!r)throw Error(`Property override requires a non-empty canonical slug.`);let i=Ss(n),a=`override/${i}/${t.kind}/${r}`,o=`${t.kind}-override-${i}-${r}`,s=Date.now(),c=t.rawContent,l=qb(c);(typeof l.id!=`string`||!l.id.trim())&&(c=tc(c,[`id`],o)),(typeof l.slug!=`string`||l.slug.trim()!==r)&&(c=tc(c,[`slug`],r));let u=t.title?.trim()||r,d;if(t.kind===`effort`){let e=Ld(c);if(e.errors.length>0)throw Error(e.errors.join(`
|
|
155
155
|
`));u=e.effort.label||u,d={...e.effort,id:typeof l.id==`string`&&l.id.trim()?l.id.trim():o,slug:r,label:u,registrySource:`user`,ownerNoteId:a,sourceId:n,updatedAt:new Date(s).toISOString()}}else if(t.kind===`equipment`){let e=Bd(c);if(e.errors.length>0)throw Error(e.errors.join(`
|
|
156
156
|
`));u=e.equipment.label||u,d={...e.equipment,id:typeof l.id==`string`&&l.id.trim()?l.id.trim():o,slug:r,label:u,registrySource:`user`,ownerNoteId:a,sourceId:n,updatedAt:new Date(s).toISOString()}}else if(t.kind===`tag`){let e=t.category??`tag`,n=Hd(c,e);if(n.errors.length>0)throw Error(n.errors.join(`
|
|
157
157
|
`));let i=n.tag.category||e;u=n.tag.label||u,d={id:n.tag.id||o,label:r,...i===`tag`?{}:{type:i},contributions:cS(n.tag),createdAt:s}}else{let e=cS(Hd(c,`tag`).tag);u=typeof l.label==`string`&&l.label.trim()||u,d={id:o,name:r,label:u,...typeof l.color==`string`&&l.color.trim()?{color:l.color.trim()}:{},...e.length>0?{contributions:e}:{},createdAt:s}}let f={id:sS(n,t.kind,r),notebookId:n,kind:t.kind,slug:r,label:u,ownerNoteId:a,rawContent:c,payload:d,seedOrigin:`user`,updatedAt:s};return await e.transaction([`notes`,`block_revisions`,`property_overrides`,`tags`,`tag_types`],`readwrite`,async e=>{let r=await e.readonly(`notes`).get(n);if(r&&(r.feedOrigin===`feed`||r.seedOrigin===`seed`))throw Error(`Notebook '${n}' is feed-delivered and read-only.`);let i=await e.readonly(`notes`).get(a),o=(i?.sourceRevision??0)+1,l=Vs(c,{sourceRevision:o,registeredWidgets:Ns}),p=Object.values(l).map(e=>({noteId:a,blockId:e.id,version:e.version,kind:e.kind,rawContent:c.slice(e.from,e.to),savedAt:s,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}}));await e.readwrite(`notes`).put({id:a,title:u,rawContent:c,sourceRevision:o,blocks:l,createdAt:i?.createdAt??s,notebookId:n,notebookIds:[n],seedOrigin:`user`}),p.length>0&&await e.readwrite(`block_revisions`).putMany(p),await e.readwrite(`property_overrides`).put(f),n===`notebook/custom`&&(t.kind===`tag`?await e.readwrite(`tags`).put(d):t.kind===`tag-type`&&await e.readwrite(`tag_types`).put(d))}),f}async function uS(e,t){let n;try{n=t?.notebookId?await e.readonly(`property_overrides`).getAllFromIndex(`by-notebook`,t.notebookId):t?.kind&&t?.slug?await e.readonly(`property_overrides`).getAllFromIndex(`by-kind-slug`,[t.kind,t.slug]):await e.readonly(`property_overrides`).getAll()}catch{return[]}return n.filter(e=>!(t?.notebookId&&e.notebookId!==t.notebookId||t?.kind&&e.kind!==t.kind||t?.slug&&e.slug!==t.slug))}function loe(e){let t=[],n=e=>{if(!e||!e.trim())return;if(e.startsWith(`feed:`)){t.includes(e)||t.push(e);return}let n=Cs(e);n!==`notebook/defaults`&&n!==`notebook/custom`&&n!==`notebook/journal`&&n!==`notebook/playground`&&(t.includes(n)||t.push(n))};if(e.note){let t=e.note.provenance?.feedSourceId??e.note.feedSourceId;t&&t!==`core`&&t!==`local`&&n(`feed:${t}`),e.note.provenance?.sourceNotebookId&&n(e.note.provenance.sourceNotebookId);for(let t of Hy(e.note))n(t);let r=Uy(e.note);r&&n(r)}return e.notebookId&&n(e.notebookId),t}async function dS(e,t={}){let n=[];try{n=await e.readonly(`property_overrides`).getAll()}catch{}let r=[],i=[],a=[],o=[];try{[r,i,a,o]=await Promise.all([e.readonly(`efforts`).getAll(),e.readonly(`equipment`).getAll(),e.readonly(`tags`).getAll(),e.readonly(`tag_types`).getAll()])}catch{}let s=new Map,c=new Map,l=new Map,u=new Map,d=new Map;for(let e of r)e.registrySource===`bundled`&&(!e.sourceId||e.sourceId===`core`||e.sourceId===`efforts`)&&(s.set(e.slug,e),d.set(`effort:${e.slug}`,`notebook/defaults`));for(let e of i)e.registrySource===`bundled`&&(!e.sourceId||e.sourceId===`core`||e.sourceId===`equipment`)&&(c.set(e.slug,e),d.set(`equipment:${e.slug}`,`notebook/defaults`));for(let e of a)l.set(e.label,e),d.set(`tag:${e.label}`,`notebook/defaults`);for(let e of o)u.set(e.name,e),d.set(`tag-type:${e.name}`,`notebook/defaults`);let f=t.notebookId?Cs(t.notebookId):void 0,p=t.mode??`source-first`,m=loe(t),h;if(h=f===`notebook/defaults`?[`notebook/defaults`]:p===`custom-runtime`||m.length===0?[`notebook/defaults`,...m,`notebook/custom`]:[`notebook/defaults`,`notebook/custom`,...m],h.includes(`notebook/custom`)){for(let e of r)e.registrySource===`user`&&!s.has(e.slug)&&(s.set(e.slug,e),d.set(`effort:${e.slug}`,`notebook/custom`));for(let e of i)e.registrySource===`user`&&!c.has(e.slug)&&(c.set(e.slug,e),d.set(`equipment:${e.slug}`,`notebook/custom`))}let g=new Map;for(let e of n){let t=g.get(e.notebookId)??[];t.push(e),g.set(e.notebookId,t)}for(let e of h){let t=g.get(e)??[];for(let n of t){let t=(e.startsWith(`feed:`),e);if(n.kind===`effort`){let e=n.payload??Ld(n.rawContent).effort;s.set(n.slug,{...e,slug:n.slug}),d.set(`effort:${n.slug}`,t)}else if(n.kind===`equipment`){let e=n.payload??Bd(n.rawContent).equipment;c.set(n.slug,{...e,slug:n.slug}),d.set(`equipment:${n.slug}`,t)}else if(n.kind===`tag`){let e=n.payload;e&&(l.set(n.slug,e),d.set(`tag:${n.slug}`,t))}else if(n.kind===`tag-type`){let e=n.payload;e&&(u.set(n.slug,e),d.set(`tag-type:${n.slug}`,t))}}}let _=[...s.values()],v=[...c.values()],y=[...l.values()],b=[...u.values()],x=[...b.filter(e=>e.contributions&&e.contributions.length>0).map(e=>({slug:`category:${e.name}`,contributions:e.contributions??[]})),...y.map(e=>({slug:e.label,contributions:e.contributions??[]}))];return{efforts:_,equipment:v,tags:y,tagTypes:b,referenceIndex:nf({efforts:_,equipment:v}),tagIndex:rs(x),originByKey:d}}async function uoe(e,t){let n=Cs(t.notebookId);if(xs(n))return[];let r,i;try{[r,i]=await Promise.all([e.readonly(`property_overrides`).getAllFromIndex(`by-notebook`,`notebook/custom`),e.readonly(`property_overrides`).getAllFromIndex(`by-notebook`,n)])}catch{return[]}let a=new Map(i.map(e=>[`${e.kind}:${e.slug}`,e])),o=new Map(r.map(e=>[`${e.kind}:${e.slug}`,e])),s=new Set;for(let e of t.effortSlugs??[])s.add(`effort:${e}`);for(let e of t.equipmentSlugs??[])s.add(`equipment:${e}`);for(let e of t.tagSlugs??[])s.add(`tag:${e}`);let c=[],l=Date.now();for(let e of s){if(a.has(e))continue;let t=o.get(e);if(!t)continue;let r={...t,id:sS(n,t.kind,t.slug),notebookId:n,updatedAt:l};c.push(r),a.set(e,r)}return c.length>0&&await e.transaction([`property_overrides`],`readwrite`,async e=>{await e.readwrite(`property_overrides`).putMany(c)}),[...a.values()]}async function fS(e){let t=await crypto.subtle.digest(`SHA-1`,new TextEncoder().encode(`${Iae}:${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 pS(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&&pS(Reflect.get(e,n),Reflect.get(t,n)))}function mS(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function doe(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=Us(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 Vs(t,{sourceRevision:n,blocks:c,registeredWidgets:fx,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function hS(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=[],g=i;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:g,sourcePath:t.path})}let _=await e.getMany(h.map(e=>e.slug)),v=h.filter((e,t)=>{let n=_[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:px(n.sourceId)}return a>=r&&!pS(e,n)});v.length&&await e.putMany(v);let y=new Set(h.map(e=>e.slug)),b=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&&!y.has(r)&&b.set(r,e)}let x=[...b.keys()];if(x.length){let a=await e.getMany(x);for(let[s,c]of a.entries()){let a=x[s];if(!c||c.registrySource!==`bundled`)continue;let l=b.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 v.length}async function gS(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!pS(e,r[t]));i.length&&await e.putMany(i)}var foe=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`property_overrides`,`meta`,`sessions`,`events`];async function poe(e){rS(e.manifest),aS(e.rows);let t=await Promise.all(e.rows.map(e=>fS(e.path))),n=new Map,r=new Map,i=new Map;for(let[a,o]of e.rows.entries()){let e=qb(o.content).slug;typeof e==`string`&&e.trim()&&(n.set(e,await fS(`page:${e}`)),r.set(t[a],await fS(`pagenote:${e}:${o.path}`)));for(let{label:e}of Yb(o.content))i.has(e)||i.set(e,await fS(`tag:${e}`))}return{write:e,ids:t,pagesBySlug:n,linkIds:r,tagIds:i}}async function _S(e,t){let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!t.length)return n;let r=await Promise.all(t.map(poe)),i={...n};for(let t=0;t<r.length;t++){let n=r[t],a=await e.transaction(foe,`readwrite`,e=>hoe(e,n));i.totalNotes+=a.totalNotes,i.totalEfforts+=a.totalEfforts,i.totalEquipment+=a.totalEquipment,i.totalBlocks+=a.totalBlocks,i.skippedUserOwned+=a.skippedUserOwned,i.deleted+=a.deleted,i.preservedPinned=(i.preservedPinned??0)+(a.preservedPinned??0),i.addedNotes+=a.addedNotes,i.updatedNotes+=a.updatedNotes,t+1<r.length&&await new Promise(e=>setTimeout(e,0))}return i}async function moe(e,t){return _S(e,[t])}async function hoe(e,t){let{write:n,ids:r,pagesBySlug:i,linkIds:a,tagIds:o}=t,s={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0},c=e.readwrite(`meta`),l=new Set;for(let e of await c.getAll()){let t=ooe(e?.key);t!==void 0&&l.add(t)}if(!pS(await c.get(n.meta.key),n.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(n.meta.schema!==9||n.manifest.schema!==9&&!Array.isArray(n.manifest.notebooks))throw Error(`Incompatible seed schema; recreate artifacts`);let u=e.readwrite(`notes`),d=n.chunkId?n.expectedMeta?.chunks[n.chunkId]?.noteIds??[]:[],f=new Set((n.chunkId?n.meta.chunks[n.chunkId]?.noteIds:void 0)??r),p=d.filter(e=>!f.has(e)),m=[...new Set([...r,...p])],h=await u.getMany(m),g=new Map(m.map((e,t)=>[e,h[t]])),_=n.meta.key.startsWith(`seed:`)?n.meta.key.slice(5):n.meta.key,v=zae(n.meta.key),y=px(n.meta.key,n.meta.tier),b=[];for(let e of await c.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`)||t.key===n.meta.key)continue;let r=new Set;for(let e of Object.values(t.chunks??{}))for(let t of e.noteIds??[])r.add(t);b.push({key:t.key,sourceId:t.key.slice(5),rank:px(t.key,t.tier),meta:t,noteIds:r})}b.sort((e,t)=>t.rank-e.rank);let x=e=>{let t=-1;for(let n of b)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},S=m.filter(e=>{if(l.has(e))return!1;let t=g.get(e);if(!t)return f.has(e);if(t.seedOrigin!==`seed`)return!1;let r=x(e);return f.has(e)?y>=r:r<0&&t.seedChunkId===n.chunkId}),C=new Set(S),w=e.readwrite(`block_revisions`),T=r.filter((e,t)=>C.has(e)&&g.get(e)?.rawContent!==n.rows[t].content),E=await w.getAllFromIndexMany(`by-note`,T),D=new Map(T.map((e,t)=>[e,E[t]])),O=e.readwrite(`block_index`),k=e.readwrite(`block_efforts`),A=e.readwrite(`block_equipment`),j=e.readwrite(`note_tags`),M=e.readwrite(`page_notes`),N=await O.getAllFromIndexMany(`by-note`,S),P=await k.getAllFromIndexMany(`by-note`,S),F=await A.getAllFromIndexMany(`by-note`,S),I=await j.getAllFromIndexMany(`by-note`,S),ee=await M.getAllFromIndexMany(`by-note`,S),L=new Map(S.map((e,t)=>[e,t])),R=e.readwrite(`tags`),z=[...o.keys()],B=await R.getAllFromIndexMany(`by-label`,z),V=new Map(z.map((e,t)=>[e,B[t][0]])),H=[],U=[],te=[],W=[],ne=[],re=[],ie=[],ae=[],oe=[],se=e.readwrite(`sessions`),ce=e.readwrite(`events`),le=new Set;if(S.length>0){let e;try{e=await se.getAllFromIndexMany(`by-note`,S)}catch{let t=await se.getAll();e=S.map(e=>t.filter(t=>t.noteId===e))}for(let t=0;t<S.length;t++){let n=S[t];(g.get(n)?.retention===`session-pinned`||(e[t]?.length??0)>0)&&le.add(n)}}let ue=n.rows.flatMap(e=>e.telemetry?.sessions.map(e=>e.id)??[]),de=await se.getMany(ue),fe=new Map(ue.map((e,t)=>[e,de[t]])),pe=[],me=[];for(let[e,t]of n.rows.entries()){let c=r[e],l=g.get(c);if(!C.has(c)){l&&l.seedOrigin!==`seed`&&s.skippedUserOwned++;continue}l?l.rawContent!==t.content&&s.updatedNotes++:s.addedNotes++,Hs(t.content,t.blocks,1,{registeredWidgets:fx});let u=l?l.sourceRevision+(l.rawContent===t.content?0:1):1,d=0,f=D.get(c)??[],p=l?l.rawContent===t.content?structuredClone(l.blocks):doe(l,t.content,u):f.length?Vs(t.content,{sourceRevision:u,registeredWidgets:fx,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(t.blocks);for(let e of Object.values(p)){let r=(D.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],i=t.content.slice(e.from,e.to);if(l?.rawContent===t.content)continue;let a=r&&r.kind===e.kind&&r.rawContent===i&&r.dialect===e.dialect&&r.sport===e.sport;e.version=l?a?r.version:(r?.version??0)+1:1,(!l||!a)&&te.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:i,savedAt:n.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Hs(t.content,p,u,{registeredWidgets:fx});let m=qb(t.content),h=typeof m.title==`string`&&m.title.trim()?m.title.trim():mS(t.path),_=n.chunkId?Vae(t.path,t.content,n.chunkId):void 0;if(!_)throw Error(`Unknown seed source family ${n.chunkId}`);let y=typeof m.date==`string`?m.date.match(/^(\d{4})-(\d{2})-(\d{2})$/):null,b;if(y){let e=Date.parse(`${m.date}T12:00:00Z`);if(!(Number.isFinite(e)&&new Date(e).getUTCMonth()===Number(y[2])-1&&new Date(e).getUTCDate()===Number(y[3])))throw Error(`invalid frontmatter date '${m.date}' in '${t.path}' — expected a real calendar day (YYYY-MM-DD)`);b=e}let x=t.commit??n.manifest.commit,S=l,w=le.has(c)||S?.retention===`session-pinned`?`session-pinned`:S?.retention===`schedule-pinned`?`schedule-pinned`:void 0,T={...l,id:c,title:h,rawContent:t.content,sourceRevision:u,blocks:p,createdAt:n.manifest.version,...b===void 0?{}:{date:b},type:n.chunkId===`dashboards`?`dashboard`:`note`,sourceId:_,seedOrigin:`seed`,seedVersion:n.manifest.version,seedChunkId:n.chunkId??void 0,feedOrigin:`feed`,feedSourceId:v,sourcePath:t.path,...x?{seedCommit:x}:{},...w?{retention:w}:S?.retention?{retention:S.retention}:{},...w||S?.upstreamStatus?{upstreamStatus:`live`}:{}};b===void 0&&delete T.date,pS(T,l)||U.push(T);let E=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),O=new Map(t.blockIndex.map(e=>[e.blockId,e])),k=new Map;for(let e of t.blockIndex){let n=E.get(`${e.from}:${e.to}`);if(!n||n.kind!==e.dataType)throw Error(`Orphan seed projection`);k.set(e.blockId,n.id);let r={...e,id:`${c}:${n.id}`,noteId:c,blockId:n.id,blockVersion:n.version,sourceRevision:u,noteTitle:h,sourceId:_,sourcePath:t.path,rawContent:t.content.slice(n.from,n.to)},i=N[L.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&ie.push(r)}let A=new Map,M=new Set;for(let e of t.telemetry?.sessions??[]){if(O.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed session pin`);let t=fe.get(e.id);if(t&&t.noteId!==c)throw Error(`Seed session ${e.id} belongs to another note`);if(t&&(t.origin||!t.id.startsWith(`seed:`))){M.add(e.id);continue}let n=t?.blockId??k.get(e.blockId);if(!n)throw Error(`Orphan seed session pin`);let r=p[n];if(!t&&!r)throw Error(`Orphan seed session pin`);let i={...e,noteId:c,blockId:n,blockVersion:t?.blockVersion??r.version,blockContentId:t?.blockContentId??O.get(e.blockId)?.blockContentId};pe.push(i),A.set(i.id,i)}for(let e of t.telemetry?.events??[]){if(M.has(e.resultId))continue;let t=A.get(e.resultId);if(!t)throw Error(`Orphan seed event result`);me.push({...e,noteId:c,blockId:t.blockId,blockVersion:t.blockVersion,blockContentId:t.blockContentId})}for(let e of t.blockEfforts){let n=k.get(e.blockId);if(!n||O.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let r={...e,id:`${c}:${n}:${e.effortSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=P[L.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&ae.push(i?{...r,createdAt:i.createdAt}:r)}for(let e of t.blockEquipment){let n=k.get(e.blockId);if(!n||O.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let r={...e,id:`${c}:${n}:${e.equipmentSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=F[L.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&oe.push(i?{...r,createdAt:i.createdAt}:r)}let ee=L.get(c),R=new Set;for(let e of Yb(t.content)){let t=V.get(e.label);t?e.type&&!t.type&&(t={...t,type:e.type},H.push(t),V.set(e.label,t)):(t={id:o.get(e.label),label:e.label,type:e.type,createdAt:n.meta.importedAt},H.push(t),V.set(e.label,t)),!R.has(t.id)&&(R.add(t.id),I[ee].find(e=>e.tagId===t.id)||re.push({id:`${c}:${t.id}`,noteId:c,tagId:t.id}))}for(let e of I[ee])R.has(e.tagId)||await j.delete(e.id);let z=m.slug;if(typeof z==`string`&&i.has(z)){let e=i.get(z);W.push({id:e,slug:z,title:mS(t.path),createdAt:n.manifest.version}),ne.push({id:a.get(c),pageId:e,noteId:c,createdAt:n.manifest.version})}s.totalNotes++,s.totalBlocks+=Object.keys(p).length}let he=new Set(p.filter(e=>C.has(e)&&(le.has(e)||g.get(e)?.retention===`schedule-pinned`))),ge=new Set(ie.map(e=>e.id)),_e=new Set(ae.map(e=>e.id)),ve=new Set(oe.map(e=>e.id));for(let e of N)for(let t of e)t.isStatic===!0&&!ge.has(t.id)&&!he.has(t.noteId)&&await O.delete(t.id);for(let e of P)for(let t of e)t.isStatic===!0&&!_e.has(t.id)&&!he.has(t.noteId)&&await k.delete(t.id);for(let e of F)for(let t of e)t.isStatic===!0&&!ve.has(t.id)&&!he.has(t.noteId)&&await A.delete(t.id);for(let e of p){if(!C.has(e))continue;let t=g.get(e);if(!t||t.seedOrigin!==`seed`)continue;let n=le.has(e)||t.retention===`session-pinned`?`session-pinned`:t.retention===`schedule-pinned`?`schedule-pinned`:void 0;if(n){let e={...t,retention:n,upstreamStatus:`removed`};pS(e,t)||U.push(e),s.preservedPinned=(s.preservedPinned??0)+1;continue}let r=L.get(e);await u.delete(e);for(let e of I[r])await j.delete(e.id);for(let e of ee[r])await M.delete(e.id);s.deleted++}let ye=async(t,i)=>{let a;try{a=e.readwrite(`property_overrides`)}catch{return}let o=v===`core`?[`notebook/defaults`]:[`feed:${v}`,...n.manifest.chunks.filter(e=>e.id.startsWith(`notebook.`)).map(e=>`notebook/${Sx(e.id)}`)],s=await a.getAll(),c=new Map(s.map(e=>[e.id,e])),l=new Set,u=[];for(let[e,a]of n.rows.entries()){let s=i(a.content);if(s)for(let i of o){let o=sS(i,t,s.slug);l.add(o);let d=c.get(o);if(d&&d.seedOrigin!==`seed`)continue;let f={id:o,notebookId:i,kind:t,slug:s.slug,label:s.label,ownerNoteId:r[e],rawContent:a.content,payload:s,seedOrigin:`seed`,feedSourceId:v,updatedAt:n.meta.importedAt};(!d||!pS(d,f))&&u.push(f)}}u.length>0&&await a.putMany(u);for(let e of s)e.seedOrigin===`seed`&&e.feedSourceId===v&&e.kind===t&&!l.has(e.id)&&(!e.ownerNoteId||!f.has(e.ownerNoteId))&&await a.delete(e.id)};return n.chunkId===`efforts`&&(s.totalEfforts=await hS(e.readwrite(`efforts`),u,Pd,`efforts`,_,y,b,d,n.rows,r,C,g,m),await ye(`effort`,Pd)),n.chunkId===`equipment`&&(s.totalEquipment=await hS(e.readwrite(`equipment`),u,Fd,`equipment`,_,y,b,d,n.rows,r,C,g,m),await ye(`equipment`,Fd)),U.length&&await u.putMany(U),te.length&&await w.putMany(te),await gS(O,ie,ie.map(e=>e.id)),await gS(k,ae,ae.map(e=>e.id)),await gS(A,oe,oe.map(e=>e.id)),await gS(se,pe,pe.map(e=>e.id)),await gS(ce,me,me.map(e=>e.id)),H.length&&await R.putMany([...new Map(H.map(e=>[e.id,e])).values()]),re.length&&await j.putMany(re),await gS(e.readwrite(`page`),W,W.map(e=>e.id)),await gS(M,ne,ne.map(e=>e.id)),await c.put(n.meta),s}function goe(e,t){let n=t.seedChunkId?e.filter(e=>e.chunkId===t.seedChunkId):[];return[...n.length>0?n:e].sort((e,t)=>t.rank-e.rank||(e.key<t.key?-1:+(e.key>t.key)))[0]}async function _oe(e){return e.transaction([`meta`,`notes`,`block_index`],`readwrite`,async e=>{let t=e.readwrite(`meta`),n=new Map;for(let e of await t.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`))continue;let r=t.key.slice(5),i=px(t.key,t.tier);for(let[e,a]of Object.entries(t.chunks??{}))for(let o of a.noteIds??[]){let a=n.get(o)??[];a.push({sourceId:r,chunkId:e,rank:i,key:t.key}),n.set(o,a)}}if(n.size===0)return 0;let r=e.readwrite(`notes`),i=e.readwrite(`block_index`),a=[...n.keys()],o=await r.getMany(a),s=[];for(let e=0;e<a.length;e++){let t=a[e],i=o[e];if(!i||i.seedOrigin!==`seed`||i.feedSourceId)continue;let c=goe(n.get(t),i),l=i.sourceRevision+1,u=Object.fromEntries(Object.entries(i.blocks).map(([e,t])=>[e,{...t,sourceRevision:l}]));await r.put({...i,blocks:u,sourceRevision:l,feedOrigin:`feed`,feedSourceId:c.sourceId}),s.push({id:t,sourceRevision:l})}if(s.length>0){let e=new Map(s.map(e=>[e.id,e.sourceRevision])),t=(await i.getAllFromIndexMany(`by-note`,s.map(e=>e.id))).flatMap(t=>t.flatMap(t=>{let n=e.get(t.noteId);return n!==void 0&&t.sourceRevision!==n?[{...t,sourceRevision:n}]:[]}));t.length>0&&await i.putMany(t)}return s.length})}async function voe(e){return e.transaction([`meta`,`notes`,`block_index`,`block_efforts`,`block_equipment`],`readwrite`,async e=>{let t=0,n=e.readwrite(`meta`);for(let e of await n.getAll()){let r=e;if(!r||typeof r.key!=`string`||!r.key.startsWith(`seed:`))continue;let i=r.chunks??{},a=!1,o={};for(let[e,t]of Object.entries(i)){let n=Eb(e);n!==e&&(a=!0),o[n]=o[n]&&o[n]!==t?{...o[n],noteIds:[...new Set([...o[n].noteIds??[],...t.noteIds??[]])]}:t}a&&(await n.put({...r,chunks:o}),t++)}for(let n of[`notes`,`block_index`,`block_efforts`,`block_equipment`]){let r=e.readwrite(n);for(let e of await r.getAll()){let n=e;sae(n)&&(await r.put(oae(n)),t++)}}return t})}function vS(e,t={}){let n=(e,t)=>typeof IDBKeyRange<`u`?IDBKeyRange.bound(e,t):{lower:e,upper:t},r=e=>n([e,``],[`${e}\uffff`,``]),i={getEventsByTimeRange:async(t,r)=>e.readonly(`events`).getAllFromIndex(`by-timestamp`,n(t,r)),getEventsByMetricDates:async t=>{let n=e.readonly(`events`),r=new Map;for(let e of t)for(let t of await n.getAllFromIndex(`by-metric-date`,e))r.set(t.id,t);return Array.from(r.values())},getEventsByResult:async t=>e.readonly(`events`).getAllFromIndex(`by-result-grain`,r(t)),getEventsForNote:async t=>(await e.readonly(`events`).getAll()).filter(e=>e.noteId===t),getEventsByContent:async t=>e.readonly(`events`).getAllFromIndex(`by-content-grain`,r(t)),scanAll:()=>e.readonly(`events`).getAll(),appendEvents:async t=>{t.length>0&&await e.readwrite(`events`).putMany(t)},finalizeSummaries:async(t,n)=>{await e.transaction([`events`],`readwrite`,async e=>{let r=(await e.readonly(`events`).getAll()).filter(e=>e.resultId===t&&e.grain===`summary`&&e.origin!==`user`);for(let t of r)await e.readwrite(`events`).delete(t.id);n.length>0&&await e.readwrite(`events`).putMany(n)})},deleteEvents:async t=>{for(let n of t)await e.readwrite(`events`).delete(n)}},a={eventStore:t.coalesce===!1?i:Sae(i),noteStore:{getAllNotes:()=>e.readonly(`notes`).getAll(),getNotesByIds:async t=>(await e.readonly(`notes`).getMany([...t])).filter(e=>e!==void 0),getNoteIdsForTag:async t=>{let n=new Set;for(let r of await e.readonly(`tags`).getAllFromIndex(`by-label`,t))for(let t of await e.readonly(`note_tags`).getAllFromIndex(`by-tag`,r.id))n.add(t.noteId);return n},getNoteTagLabels:async t=>{let n=await e.readonly(`note_tags`).getAllFromIndex(`by-note`,t);return(await e.readonly(`tags`).getMany(n.map(e=>e.tagId))).flatMap(e=>e?[e.label]:[])},queryDomain:async t=>{if(!e.queryDomain)return;let n=await e.queryDomain({...t,plan:`notes`});return n&&n.plan===`notes`?n:void 0}},blockStore:{getAllBlocks:()=>e.readonly(`block_index`).getAll(),queryDomain:async t=>{if(!e.queryDomain)return;let n=await e.queryDomain({...t,plan:`blocks`});return n&&n.plan===`blocks`?n:void 0}},effortStore:t.effortStore??{getAllEfforts:async()=>{let t=await e.readonly(`efforts`).getAll(),n=new Map;for(let e of Xd)n.set(e.slug,e);for(let e of t)n.set(e.slug,e);return[...n.values()]}},blockEffortsStore:{getAllFromIndex:(t,n)=>e.readonly(`block_efforts`).getAllFromIndex(t,n)},blockEquipmentStore:{getAllFromIndex:(t,n)=>e.readonly(`block_equipment`).getAllFromIndex(t,n)},tagsStore:{getAllFromIndex:(t,n)=>e.readonly(`tags`).getAllFromIndex(t,n),getAll:()=>e.readonly(`tags`).getAll()},noteTagsStore:{getAllFromIndex:(t,n)=>e.readonly(`note_tags`).getAllFromIndex(t,n)},pageStore:{getNotePages:t=>e.readonly(`page_notes`).getAllFromIndex(`by-note`,t),getPage:t=>e.readonly(`page`).get(t),getAllPages:()=>e.readonly(`page`).getAll(),getAllLinks:()=>e.readonly(`page_notes`).getAll()},relationStore:{getBatches:async t=>{let n=new Map,r=[...new Set(t)];return r.length===0?n:e.transaction([`page_notes`,`note_tags`,`tags`,`page`],`readonly`,async e=>{let[t,i]=await Promise.all([e.readonly(`page_notes`).getAllFromIndexMany(`by-note`,r),e.readonly(`note_tags`).getAllFromIndexMany(`by-note`,r)]),a=new Set,o=new Set;for(let e of i)for(let t of e)a.add(t.tagId);for(let e of t)for(let t of e)o.add(t.pageId);let[s,c]=await Promise.all([e.readonly(`tags`).getMany([...a]),e.readonly(`page`).getMany([...o])]),l=new Map([...a].map((e,t)=>[e,s[t]])),u=new Map([...o].map((e,t)=>[e,c[t]]));for(let e=0;e<r.length;e++){let a=r[e],o=t[e]??[],s=i[e]??[];n.set(a,{tags:s.flatMap(e=>{let t=l.get(e.tagId);return t?[{label:t.label,...t.type?{type:t.type}:{}}]:[]}),links:o,pages:o.flatMap(e=>{let t=u.get(e.pageId);return t?[t]:[]})})}return n})}},feedCatalogStore:t.feedCatalogStore??{getAllFeeds:async()=>{let t=[];for(let n of await e.readonly(`meta`).getAll()){let e=n.key;if(typeof e!=`string`||!e.startsWith(`seed:`)||e===bx(`user`))continue;let r=e.slice(5);t.push({id:r,label:r,url:`https://${r}.example/feed/`,tier:`imported`,subscribed:!0,installed:!0,notebookCount:0,itemCount:0})}return t},getAllNotebooks:async()=>{let n=await e.readonly(`notebook_links`).getAll().catch(()=>[]),r=await e.readonly(`notes`).getAll(),i=new Map;for(let e of n)e.targetKind===`note`&&i.set(e.notebookId,(i.get(e.notebookId)??0)+1);let a=[];for(let[e,n]of i){let i=e.startsWith(`notebook/`)?e.slice(9):e,o=r.find(t=>t.id===e),s=o?.feedSourceId,c=`notebook.${i}`,l=s??`local`,u=s!==void 0;if(t.isNotebookSubscribed){let e=t.isNotebookSubscribed(l,c);u=typeof e==`boolean`?e:!!await e}a.push({id:e,feedId:l,feedLabel:s??`Yours (Local)`,chunkId:c,slug:i,label:o?.title??i,count:n,subscribed:u,installed:!0,origin:s?`feed`:`user`,...o?.public===void 0?{}:{public:o.public}})}return a}}};return Object.assign(a,{scheduleStore:{getAll:async()=>e.readonly(`schedule_items`).getAll().catch(()=>[]),getForNote:async t=>e.readonly(`schedule_items`).getAllFromIndex(`by-note`,t).catch(()=>[]),getByDateRange:async(t,n)=>{try{return(await e.readonly(`schedule_items`).getAll()).filter(e=>e.date>=t&&e.date<=n)}catch{return[]}}},sessionStore:{getAll:async()=>(await e.readonly(`sessions`).getAll()).map(e=>({id:e.id,noteId:e.noteId,startedAt:e.startTime,...e.completed?{completedAt:e.endTime}:{},...typeof e.duration==`number`?{duration:e.duration}:{},createdAt:e.createdAt,...e.notebookIds?{notebookIds:e.notebookIds}:{},...e.blockContentId?{blockContentId:e.blockContentId}:{},...e.completed===void 0?{}:{completed:e.completed},...e.sessionDate?{sessionDate:e.sessionDate}:{},...e.scheduleItemId?{scheduleItemId:e.scheduleItemId}:{}}))}}),t.datasetStore&&(a.datasetStore=t.datasetStore),t.isNotebookSubscribed&&(a.isNotebookSubscribed=(e,n)=>{let r=t.isNotebookSubscribed(e,n);return typeof r!=`boolean`||r}),a}async function yoe(e,t){let n=new Map,[r,i]=await Promise.all([t.notebookSlug?e.readonly(`notes`).getAll():Promise.resolve([]),t.noteId?e.readonly(`notes`).get(t.noteId):Promise.resolve(void 0)]);if(t.resultId){let r=(await e.readonly(`events`).getAll()).filter(e=>e.resultId===t.resultId);n.set(`@session`,{events:r,notes:i?[i]:[]})}if(t.blockContentId){let r=(await e.readonly(`events`).getAll()).filter(e=>e.blockContentId===t.blockContentId);n.set(`@block`,{events:r,notes:i?[i]:[]})}if(t.noteId){let r=(await e.readonly(`events`).getAll()).filter(e=>e.noteId===t.noteId);n.set(`@note`,{events:r,notes:i?[i]:[]})}if(t.notebookSlug){let i=t.notebookSlug.replace(/^notebook\//,``),a=`notebook/${i}`,o=r.filter(e=>e.notebookId===a||e.notebookIds?.some(e=>e===a||e===i)||e.tags?.some(e=>e===`notebook:${i}`||e===a)?!0:i===`journal`&&!e.feedOrigin&&!e.feedSourceId&&!e.sourcePath?.startsWith(`markdown/`)&&e.type!==`dashboard`&&e.type!==`playground`?!e.notebookId:i===`playground`&&(e.sourceId===`playground`||e.type===`playground`)?!0:e.sourceId?.startsWith(`notebook:${i}`)??!1),s=new Set(o.map(e=>e.id)),c=(await e.readonly(`events`).getAll()).filter(e=>s.has(e.noteId));n.set(`@notebook`,{events:c,notes:o})}return n}var yS=`https://wod.wiki`,boe=`wod-feed-qr`;function xoe(e=yS){return Soe.replace(`__APP_ORIGIN__`,e)}var Soe=`(function () {
|
|
@@ -787,8 +787,8 @@ ${t??`A WOD Wiki workout feed compiled from authored Markdown notes and optional
|
|
|
787
787
|
`)?e.slice(0,-1):e}function cP(e){return`${e.replace(/\n+$/,``)}\n`}function lP(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 uP(e,t){let{sections:n}=e.state.field(cM);return n.find(e=>e.type===`widget`&&e.id===t)??null}function dP(e,t,n){if(e.state.readOnly)return{ok:!1,config:{},message:`Cannot modify widget source in read-only mode.`};let r=lP(n);if(!r.ok)return r;let i=uP(e,t);if(!i||i.contentFrom==null||i.contentTo==null)return{ok:!1,config:{},message:`Unable to locate widget source in the editor.`};let a=()=>{if(e.state.readOnly)return;let r=uP(e,t);!r||r.contentFrom==null||r.contentTo==null||e.dispatch({changes:{from:r.contentFrom,to:r.contentTo,insert:cP(n)}})};try{a()}catch(e){if(e instanceof Error&&/update.*in progress/i.test(e.message))queueMicrotask(a);else throw e}return r}function ble(e){return(0,q.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,q.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,e]}),(0,q.jsx)(`span`,{className:`ml-2 opacity-70`,children:`is not registered`})]})}function xle(e,t){return(0,q.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-5 text-sm text-destructive shadow-sm`,children:[(0,q.jsx)(`p`,{className:`font-medium`,children:`Widget config error`}),(0,q.jsxs)(`p`,{className:`mt-1 font-mono text-xs leading-5 text-destructive/90`,children:[`widget:`,e]}),(0,q.jsx)(`p`,{className:`mt-2 font-mono text-xs leading-5 text-destructive/90`,children:t})]})}function fP({widgetName:e,rawContent:t,sectionId:n,registry:r,view:i}){let a=K.useRef(null),o=K.useRef(null),s=K.useRef(null),c=K.useMemo(()=>sP(t),[t]),[l,u]=K.useState(()=>({isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c,hasFocus:!1}));K.useEffect(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c}))},[c]),K.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=K.useMemo(()=>lP(l.originalMarkdown),[l.originalMarkdown]),p=K.useCallback(e=>{u(t=>t.hasFocus===e?t:{...t,hasFocus:e})},[]),m=K.useCallback(()=>{u(e=>({...e,isEditing:!0,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),h=K.useCallback(e=>{let t=dP(i,n,e);if(!t?.ok)return u(e=>({...e,error:t?.message??`Invalid JSON.`})),!1;let r=sP(cP(e));return u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1}),!0},[i,n]),g=K.useCallback(()=>{h(o.current?.value??l.currentMarkdown)},[h,l.currentMarkdown]),_=K.useCallback(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),v=K.useCallback(e=>{let t=e.target.value;u(e=>{let n=e.error?lP(t):null;return{...e,currentMarkdown:t,isDirty:t!==e.originalMarkdown,error:n?.ok===!1?n.message:n?.ok?null:e.error}})},[]),y=K.useCallback(()=>{p(!1);let e=o.current?.value;if(e===void 0)return;let t=dP(i,n,e);if(!t?.ok){u(n=>({...n,isDirty:e!==n.originalMarkdown,error:t?.message??`Unable to save widget source.`}));return}let r=sP(cP(e));u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1})},[n,i,p]),b=K.useCallback(e=>{let t=e.relatedTarget;t instanceof Node&&a.current?.contains(t)||p(!1)},[p]),x=K.useCallback(e=>{e.key===`Enter`&&!l.isEditing&&(e.preventDefault(),m())},[m,l.isEditing]);K.useEffect(()=>{let e=s.current;if(e)return e.addEventListener(`keydown`,x),()=>e.removeEventListener(`keydown`,x)},[x]);let S=K.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?K.createElement(d,{config:f.config,rawContent:l.originalMarkdown,sectionId:n}):xle(e,f.message):ble(e),(0,q.jsxs)(`div`,{ref:a,"data-widget-section-id":n,"data-widget-mode":C,className:Co(`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,q.jsx)(rP,{mode:C,enterEditMode:m,onSave:g,onUndo:_,className:Co(`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,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[l.error!==null&&(0,q.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,q.jsx)(iP,{ref:o,"data-testid":`widget-markdown-editor`,value:l.currentMarkdown,onChange:v,onBlur:y,onKeyDown:S,hasError:l.error!==null})]}):(0,q.jsx)(`div`,{ref:s,"data-testid":`widget-preview-surface`,tabIndex:0,onKeyDown:x,children:T})]})}var Sle=class extends Ia{sectionId;root=null;container=null;constructor(e){super(),this.sectionId=e}eq(e){return this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);t.className=`relative h-0 w-full`,this.container=t;let n=eP(t);return this.root=n,n.render((0,q.jsx)(`div`,{className:`absolute right-0 top-1 z-50`,children:(0,q.jsx)(rP,{mode:`editing`,enterEditMode:()=>{},onSave:()=>{e.dispatch({effects:aP.of({sectionId:this.sectionId,editing:!1})})},onUndo:()=>{e.dispatch({effects:aP.of({sectionId:this.sectionId,editing:!1})})}})})),t}destroy(e){let t=e??this.container,n=this.root;this.root=null,this.container=null,t&&n&&tP(t,n)}ignoreEvent(){return!1}},Cle=class extends Ia{widgetName;rawContent;sectionId;registry;root=null;container=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`);t.className=`cm-widget-block-preview`,t.style.cssText=`display:block; width:100%; min-height:1.5em; outline:none;`,this.container=t;let n=eP(t);return this.root=n,n.render(K.createElement(fP,{widgetName:this.widgetName,rawContent:this.rawContent,sectionId:this.sectionId,registry:this.registry,view:e})),t}updateDOM(e,t){let n=eP(e);return this.container=e,this.root=n,n.render(K.createElement(fP,{widgetName:this.widgetName,rawContent:this.rawContent,sectionId:this.sectionId,registry:this.registry,view:t})),!0}destroy(e){let t=e??this.container,n=this.root;this.root=null,this.container=null,t&&n&&tP(t,n)}ignoreEvent(){return!1}get estimatedHeight(){return 200}};function pP(e,t){let n;try{n=e.field(cM)}catch{return Ca.none}let{sections:r}=n,i=e.field(oP),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(Ca.widget({widget:new Sle(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(Ca.replace({widget:new Cle(n.widgetName,s,n.id,t),block:!0}).range(n.from,n.to))}return a.sort((e,t)=>e.from-t.from),Ca.set(a)}function mP(e,t){return e.find(e=>e.type===`widget`&&t.from>=e.from&&t.from<=e.to)??null}function hP(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 wle(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(cM),i=e.state.field(oP),a=mP(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=mP(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(hP(e,e.state.doc.line(s.startLine)),!0)}function Tle(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(cM),i=e.state.field(oP),a=mP(r,n);if(a&&!i.has(a.id))return!1;let o=n.number-1;if(o<1)return!1;let s=mP(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(hP(e,e.state.doc.line(s.endLine)),!0)}var Ele=po.high(no.of([{key:`ArrowDown`,run:wle},{key:`ArrowUp`,run:Tle}])),gP=Xa.define({combine:e=>e[e.length-1]??new Map}),Dle=Qa.define({create(e){return pP(e,e.facet(gP))},update(e,t){let n=t.effects.some(e=>e.is(aP)),r=!t.startState.selection.eq(t.newSelection),i=t.startState.facet(gP)!==t.state.facet(gP);return t.docChanged||n||r||i?pP(t.state,t.state.facet(gP)):e},provide:e=>mo.decorations.from(e)});function Ole(e){return[gP.of(e),Dle,oP,Ele]}function kle(e){let t=e?.split(`:`,1)[0]?.toLowerCase();return t===`time`||t===`log`||t===`wod`||t===`whiteboard`?od:t===`wql`||t===`query`?vv:null}async function _P(e,t,n){let r=await uS(e,{notebookId:`notebook/custom`,kind:t});if(r.length===0)return[...n];let i=new Map;for(let e of n)e.registrySource===`user`&&i.set(e.slug,e);for(let e of r)if(e.payload){let t=e.payload;i.set(e.slug,{...t,slug:e.slug,registrySource:`user`,ownerNoteId:e.ownerNoteId,sourceId:`notebook/custom`})}return[...n.filter(e=>e.registrySource!==`user`),...i.values()]}var Ale=new class{_db;constructor(e){this._db=e}get db(){return this._db??X}async load(){let e=await this.db.getAllEfforts();return _P(this.db.storage,`effort`,e)}async save(e){await this.db.saveEffort(e)}async delete(e){await this.db.deleteEffort(e)}};function jle(){return new Sne({storage:Ale})}async function vP(e){let t=await X.getAllEfforts();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),Mle()}var yP=new Set;function bP(e){return yP.add(e),()=>yP.delete(e)}function Mle(){for(let e of yP)e()}var xP=null;function SP(){return xP||=jle(),xP}function Nle(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 Ple(e){let{meta:t,body:n}=ac(e),r=lc(t,`description`),i=lc(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():Nle(n);return{...o?{description:o}:{},...a?{image:a}:{}}}function CP(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var Fle={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 wP(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&&Fle[t.toLowerCase()]){r.push(t.toLowerCase());continue}r.push(t.charAt(0).toUpperCase()+t.slice(1))}return r.join(` `)}function TP(e,t){if(e!==`notebooks`)return[];let n=new Map,r=e=>{let t=n.get(e);return t||(t={id:e,name:CP(e),categories:[],items:[]},n.set(e,t)),t};for(let[e,n]of Object.entries(t)){let t=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/README\.md$/i);if(t){let e=r(t[1]);e.readme=n,e.categories=dc(n),Object.assign(e,Ple(n));continue}let i=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/(\d{4}-\d{2}-\d{2})\/([^/]+\.md)$/);if(i){let[,t,a,o]=i;r(t).items.push({id:o.replace(/\.md$/,``),name:wP(o),content:n,path:e,...a?{date:a}:{}});continue}let a=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/([^/]+\.md)$/);if(!a)continue;let[,o,s]=a;s.toLowerCase()!==`readme.md`&&r(o).items.push({id:s.replace(/\.md$/,``),name:wP(s),content:n,path:e})}for(let e of n.values())e.items.sort((e,t)=>e.date&&t.date&&e.date!==t.date?t.date.localeCompare(e.date):e.date&&!t.date?-1:!e.date&&t.date?1:e.id.localeCompare(t.id));return Array.from(n.values()).filter(({items:e,readme:t})=>e.length>0||t!==void 0).sort((e,t)=>e.name.localeCompare(t.name))}function EP(e){return TP(`notebooks`,e)}var DP=null,OP=[];async function kP(){let e=await zP();return DP!==e&&(DP=e,OP=EP(e)),OP}function AP(e,t,n){return e?.items.find(e=>(e.date??``)===t&&e.id===n)}var jP=null,MP=null;function NP(){return jP||=X.getAllBlockIndex().then(e=>e.filter(e=>e.isStatic===!0)).catch(e=>{throw jP=null,e}),jP}function Ile(){jP=null,MP=null}function Lle(e){let t=new Map;for(let n of e)for(let e of zs(n.rawContent).filter(e=>e.type===`frontmatter`).flatMap(e=>fc(e.displayContent))){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}return t}function Rle(){return MP||=X.getAllNotes().then(async e=>{let t=Lle(e.filter(e=>e.seedOrigin===`seed`));try{let e=await kP();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}),MP}async function PP(){let e=SP();return e.isInitialized()||await e.loadBundled(),e.list()}nA(`discipline`,{load:async()=>{try{return Yk((await PP()).map(e=>e.baseAttributes?.discipline).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),Jk(yd))}catch{return Jk(yd)}},cache:{ttlMs:6e4},open:!1,emptyText:`No disciplines available`}),nA(`effort`,{load:async()=>{try{return Yk((await PP()).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`}),nA(`intensity`,{load:async()=>{try{return Yk((await PP()).map(e=>e.baseAttributes?.intensityTier).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),Jk(_d))}catch{return Jk(_d)}},cache:{ttlMs:6e4},open:!1,emptyText:`No intensity tiers indexed yet`}),nA(`type`,{load:async()=>{try{return Yk(Gk(await NP()).map(e=>({value:e,label:e})),Jk(qk))}catch{return Jk(qk)}},cache:{ttlMs:3e5},open:!1,emptyText:`No indexed block types yet`}),nA(`notebook`,{load:async()=>Wk(await NP()).map(e=>({value:e,label:e})),cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`}),nA(`tag`,{load:async()=>{let e=await Rle(),t=Array.from(e.keys()),n=[];try{n=(await X.getAllTags()).map(e=>e.label)}catch{}return Kk(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`])nA(e,{load:async()=>{try{return(await X.getTags(e)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${e}s indexed yet`});nA(`origin`,{load:async()=>{try{let e=await X.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 X.getAllTagTypes();for(let t of e)rA(t.name)||nA(t.name,{load:async()=>{try{return(await X.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 FP=null,IP=null,LP=0,RP=new Set;function zle(){for(let e of RP)e()}async function Ble(){let e=await X.getSeedContent(),t={};for(let{path:n,raw:r}of e)t[n]=r;return t}function zP(){if(!IP){let e=LP;IP=Ble().then(t=>e===LP?(Object.keys(t).length>0&&FE(`corpusReady`),FP=t,zle(),t):FP??t).catch(t=>{throw e===LP&&(IP=null),t})}return IP}function BP(){LP++,FP=null,IP=null,Ile(),zP().catch(()=>{})}function VP(e){return RP.add(e),()=>RP.delete(e)}var Vle=VP;function Hle(){return FP}function HP(){let e=(0,K.useSyncExternalStore)(Vle,Hle);return(0,K.useEffect)(()=>{zP()},[]),e}var UP=!1;function Ule(){if(UP||typeof BroadcastChannel>`u`)return;UP=!0;let e=new BroadcastChannel(mx);e.onmessage=()=>BP()}var WP=`wodwiki.dataSettings.v1`;function Wle(){let e=KP();return e.state!==`invalid`&&e.localDbName?e.localDbName:iT}function Gle(e){return typeof e==`string`&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(e)}var Kle={"libsql:":!0,"https:":!0,"wss:":!0};function qle(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(!Kle[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 GP(){try{return localStorage.getItem(WP)}catch{return null}}function KP(){let e=GP();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&&!Gle(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=qle(a,o);return s?{state:`invalid`,raw:e,error:s}:{state:`turso`,url:a,authToken:o,...i}}var Jle=GP();typeof window<`u`&&window.addEventListener(`storage`,e=>{(e.key===`wodwiki.dataSettings.v1`||e.key===null)&&e.newValue!==Jle&&window.location.reload()});var Yle=t({DATA_SETTINGS_KEY:()=>WP,IndexedDBStorage:()=>TT,StorageService:()=>tE,profileService:()=>qP,readAllLocalRows:()=>eue,readUnsentEdits:()=>$le,startBackgroundStorageSync:()=>eF,stopBackgroundStorageSync:()=>Qle,storage:()=>YP,storageBackend:()=>`api`,storageService:()=>X,subscribeActiveLocalDatabase:()=>nF,whenStorageReady:()=>ZP}),qP=uE(`api`);function Xle(){return new roe(`/api`,void 0,{getUserId:()=>qP.currentSync()?.id})}var JP=Xle(),YP={readonly(e){return JP.readonly(e)},readwrite(e){return JP.readwrite(e)},transaction(e,t,n){return JP.transaction(e,t,n)},async queryDomain(e){return JP.queryDomain?.(e)},wipe(){return JP.wipe()},close(){return JP.close()}},X=new tE(YP),XP;async function Zle(){try{await X.ensureDefaultTagTypes()}catch{}}function ZP(){return XP||(XP=(async()=>{await Zle()})(),XP)}var QP,$P;function eF(){return QP||(QP={stop:()=>{QP=void 0}},$P=()=>{QP?.stop(),$P=void 0}),$P}async function Qle(){return QP&&QP.stop(),!1}async function $le(){return JP instanceof TT?JP.readOutbox(0,2**53-1):[]}async function eue(){return JP instanceof TT?JP.snapshotAllRows():[]}var tF=new Set;function nF(e){return tF.add(e),()=>{tF.delete(e)}}function tue(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`notebook`}var rF=`wodwiki.seedSources`,iF=`wodwiki.seedSources.hidden`,aF=`wodwiki.seedSubscriptions`,oF=`wodwiki.seedAutoSync`,sF=`wodwiki.seedChecks`,cF=`wodwiki.feedSubscriptions.pending`,lF={"seed-crossfit":`sport-crossfit`,"seed-hyrox":`sport-hyrox`,"seed-kettlebell":`legends-of-kettlebell`,"seed-swimming":`sport-swimming`,"seed-track":`sport-track`,"seed-zombie-fit":`wayback-zombie-fit`,"seed-golos-method":`sport-golos-method`,"example-movement":`samples-movement`,"example-yoga":`sport-yoga`},uF=new Set,dF=null,fF=null,pF=null,mF=null,hF=Promise.resolve(),gF=0,_F=0,vF=null,yF=null,bF=null,xF=null,SF=null,CF=null,wF=null,TF=new Map,EF=new Set,DF=new Map,OF=new Map,kF=new Map,AF=new Set,jF=new Set,MF=new Set;function NF(){for(let e of uF)e()}function PF(e){return uF.add(e),()=>{uF.delete(e)}}function FF(){return fF!==null}function IF(e){try{if(typeof localStorage>`u`)return null;let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function LF(e,t){try{return typeof localStorage>`u`||localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function nue(e){try{if(typeof localStorage>`u`)return;localStorage.removeItem(e)}catch{}}function rue(){let e=IF(cF);if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n={};if(t.subOverrides&&typeof t.subOverrides==`object`&&!Array.isArray(t.subOverrides)){let e={};for(let[n,r]of Object.entries(t.subOverrides))typeof r==`boolean`&&(e[n]=r);Object.keys(e).length>0&&(n.subOverrides=e)}if(Array.isArray(t.subRemovals)){let e=t.subRemovals.filter(e=>typeof e==`string`);e.length>0&&(n.subRemovals=e)}if(t.autoSyncOverrides&&typeof t.autoSyncOverrides==`object`&&!Array.isArray(t.autoSyncOverrides)){let e={};for(let[n,r]of Object.entries(t.autoSyncOverrides))typeof r==`boolean`&&(e[n]=r);Object.keys(e).length>0&&(n.autoSyncOverrides=e)}if(t.policyOverrides&&typeof t.policyOverrides==`object`&&!Array.isArray(t.policyOverrides)){let e={};for(let[n,r]of Object.entries(t.policyOverrides))(r===`index-only`||r===`offline-full`)&&(e[n]=r);Object.keys(e).length>0&&(n.policyOverrides=e)}return Object.keys(n).length>0?n:null}function RF(){let e=rue();if(e){if(e.subRemovals)for(let t of e.subRemovals)TF.has(t)||EF.add(t);if(e.subOverrides)for(let[t,n]of Object.entries(e.subOverrides))!TF.has(t)&&!EF.has(t)&&TF.set(t,n);if(e.autoSyncOverrides)for(let[t,n]of Object.entries(e.autoSyncOverrides))DF.has(t)||DF.set(t,n);if(e.policyOverrides)for(let[t,n]of Object.entries(e.policyOverrides))OF.has(t)||OF.set(t,n)}}function zF(){RF();let e={};TF.size>0&&(e.subOverrides=Object.fromEntries(TF)),EF.size>0&&(e.subRemovals=[...EF]),DF.size>0&&(e.autoSyncOverrides=Object.fromEntries(DF)),OF.size>0&&(e.policyOverrides=Object.fromEntries(OF)),Object.keys(e).length>0&&LF(cF,e)}function BF(){TF.clear(),EF.clear(),DF.clear(),OF.clear(),nue(cF)}function VF(e){let t=IF(e),n={};if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,r]of Object.entries(t))typeof r==`boolean`&&(n[e]=r);return n}function HF(e){let t=IF(e),n={};if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,r]of Object.entries(t))typeof r==`number`&&Number.isFinite(r)&&(n[e]=r);return n}function UF(){let e=IF(rF);if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||typeof n.id!=`string`||typeof n.label!=`string`||typeof n.url!=`string`)continue;let e=n;t.push({id:e.id,label:e.label,url:e.url,...typeof e.repositoryUrl==`string`?{repositoryUrl:e.repositoryUrl}:{}})}return t}function WF(){let e=IF(iF);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function GF(e){let t={};for(let[n,r]of Object.entries(e)){let e=r.notebookOverrides;if(r.notebookIds&&r.notebookIds.length>0){t[n]=!1;for(let e of r.notebookIds)t[`${n}#${e}`]=!0}else r.subscribed?t[n]=!0:e||(t[n]=!1);if(e)for(let[r,i]of Object.entries(e))t[`${n}#${r}`]=i}return t}function iue(e,t,n,r,i){let a={};for(let[e,n]of Object.entries(t))a[e]={...n};let o=new Map,s=new Map;for(let[t,n]of Object.entries(e)){let e=t.indexOf(`#`);if(e>0){let r=t.slice(0,e),i=lF[r]??r,a=t.slice(e+1),o=a.replace(/^collection\./,`notebook.`).replace(/^feed\./,`notebook.`),c=s.get(i)??{};(!(o in c)||a.startsWith(`notebook.`))&&(c[o]=n),s.set(i,c)}else{let e=lF[t]??t;(!o.has(e)||t===e)&&o.set(e,n)}}let c=new Set([...Object.keys(a),...o.keys(),...s.keys(),...Object.keys(n)]);for(let e of c){let t=a[e];if(t){t.autoSync===void 0&&e in n&&(t.autoSync=n[e]),t.checkedAt===void 0&&e in r&&(t.checkedAt=r[e]);continue}let c=s.get(e),l=o.get(e),u=c?Object.entries(c).filter(([,e])=>e===!0).map(([e])=>e):[],d=u.length>0,f=l===!0||d,p=l===!0?null:d?u:void 0;if(l!==void 0||c!==void 0){let t={subscribed:f,...p===void 0?{}:{notebookIds:p},...e in n?{autoSync:n[e]}:{},...e in r?{checkedAt:r[e]}:{},updatedAt:i};c&&Object.values(c).some(e=>e===!1)&&(t.notebookOverrides={...c}),a[e]=t}else e in n&&(a[e]={subscribed:!1,autoSync:n[e],...e in r?{checkedAt:r[e]}:{},updatedAt:i})}return a}function KF(e,t,n,r,i,a=Date.now()){let o={},s=new Set([...Object.keys(e),...Object.keys(n),...Object.keys(r)]);for(let e of Object.keys(t)){let t=e.indexOf(`#`);s.add(t>0?e.slice(0,t):e)}for(let c of s){let s=e[c],l=t[c],u=`${c}#`,d={},f=[];for(let[e,n]of Object.entries(t))if(e.startsWith(u)){let t=e.slice(u.length);d[t]=n,n&&f.push(t)}let p=f.length>0,m=l===!0||p,h=l===!0?null:p?f:l===!1?[]:s?.notebookIds,g=r[c]??s?.offlinePolicy??(c===`core`?`offline-full`:void 0),_=c in n?n[c]:s?.autoSync,v=c in i?i[c]:s?.checkedAt,y={...s??{},subscribed:m,...h===void 0?{}:{notebookIds:h},...g===void 0?{}:{offlinePolicy:g},..._===void 0?{}:{autoSync:_},...v===void 0?{}:{checkedAt:v},updatedAt:s?.updatedAt??a};Object.keys(d).length>0?y.notebookOverrides=d:delete y.notebookOverrides,o[c]=y}return o}function aue(e=Date.now()){return KF(bF??{},xF??VF(`wodwiki.seedSubscriptions`),SF??VF(`wodwiki.seedAutoSync`),CF??{},wF??HF(`wodwiki.seedChecks`),e)}function qF(e){hF=hF.then(e,e).catch(()=>{})}async function JF(){pF&&await pF.catch(()=>void 0),await hF}function YF(){let e=dF;if(!e)return;let t=gF,n=aue();bF=n;let r={...wF??{}};qF(async()=>{await e.transaction([`meta`],`readwrite`,async e=>{let t=e.readwrite(`meta`),i={...(await t.get(`feed:subscriptions`))?.checks??{},...r};await t.put({key:oC,entries:n,checks:i,migratedFromLocalStorage:!0})}),gF===t&&BF()})}function XF(){let e=dF;if(!e)return;let t=_F,n=[...vF??[]],r=[...yF??[]],i=Date.now();qF(async()=>{await e.transaction([`meta`],`readwrite`,async e=>{await e.readwrite(`meta`).put({key:sC,customFeeds:n,hiddenFeedIds:r,updatedAt:i,migratedFromLocalStorage:!0})}),_F===t&&(kF.clear(),AF.clear(),jF.clear(),MF.clear())})}var oue=8;async function ZF(e){if(pF&&mF===e){await pF;return}let t=(async()=>{await hF;let t=0;for(;;){t++;let n=Date.now(),[r,i]=await Promise.all([e.readonly(`meta`).get(sC),e.readonly(`meta`).get(oC)]);RF();let a=Array.isArray(r?.customFeeds)?[...r.customFeeds]:[],o=Array.isArray(r?.hiddenFeedIds)?[...r.hiddenFeedIds]:[],s=!!r?.migratedFromLocalStorage,c={...i?.entries??{}},l={...i?.checks??{}},u=!!i?.migratedFromLocalStorage,d=!1,f=!1;if(!s){let e=UF(),t=WF();for(let t of e)a.some(e=>e.id===t.id||e.url===t.url)||a.push(t);for(let e of t){let t=lF[e]??e;o.includes(t)||o.push(t)}d=!0}if(!u){let e=VF(aF),t=VF(oF),r=HF(sF);for(let[e,t]of Object.entries(r))e in l||(l[e]=t);c=iue(e,c,t,l,n),f=!0}let p=_F,m=gF;if(kF.size>0||AF.size>0){a=a.filter(e=>!AF.has(e.id));for(let e of kF.values())a.some(t=>t.id===e.id||t.url===e.url)||a.push(e);d=!0}if(jF.size>0||MF.size>0){let e=new Set(o);for(let t of jF)e.add(t);for(let t of MF)e.delete(t);o=[...e],d=!0}if(TF.size>0||EF.size>0||DF.size>0||OF.size>0){let e=GF(c);for(let t of EF)delete e[t];for(let[t,n]of TF)e[t]=n;let t={},r={};for(let[e,n]of Object.entries(c))typeof n.autoSync==`boolean`&&(t[e]=n.autoSync),n.offlinePolicy&&(r[e]=n.offlinePolicy);for(let[e,n]of DF)t[e]=n;for(let[e,t]of OF)r[e]=t;c=KF(c,e,t,r,l,n),f=!0}if((d||f)&&await e.transaction([`meta`],`readwrite`,async e=>{let t=e.readwrite(`meta`);d&&await t.put({key:sC,customFeeds:a,hiddenFeedIds:o,updatedAt:n,migratedFromLocalStorage:!0}),f&&await t.put({key:oC,entries:c,checks:l,migratedFromLocalStorage:!0})}),(gF!==m||_F!==p)&&t<oue){await hF;continue}gF===m&&BF(),_F===p&&(kF.clear(),AF.clear(),jF.clear(),MF.clear()),vF=a,yF=o,bF=c,xF=GF(c);let h={},g={},_={...l};for(let[e,t]of Object.entries(c))typeof t.autoSync==`boolean`&&(h[e]=t.autoSync),t.offlinePolicy&&(g[e]=t.offlinePolicy),typeof t.checkedAt==`number`&&(_[e]=t.checkedAt),t.hidden&&!o.includes(e)&&!a.some(t=>t.id===e)&&o.push(e);SF=h,CF=g,wF=_,LF(aF,xF),LF(oF,h),LF(sF,_),dF=e,fF=e,NF();break}})();pF=t,mF=e;try{await t}finally{pF===t&&(pF=null,mF=null)}}function sue(){return vF}function cue(e){if(e){let t=vF??[],n=!1;for(let r of e)t.some(e=>e.id===r.id&&e.url===r.url&&e.label===r.label)||(kF.set(r.id,r),AF.delete(r.id),n=!0);for(let r of t)e.some(e=>e.id===r.id)||(kF.delete(r.id),AF.add(r.id),n=!0);n&&_F++}vF=e,NF()}function lue(){return yF}function uue(e){if(e){let t=new Set(yF??[]),n=new Set(e),r=!1;for(let e of n)t.has(e)||(jF.add(e),MF.delete(e),r=!0);for(let e of t)n.has(e)||(jF.delete(e),MF.add(e),r=!0);r&&_F++}yF=e,NF()}function QF(){return bF}function $F(){return xF}function eI(e,t=!1,n){if(!t&&e){let t=xF??{},r=!1;for(let[n,i]of Object.entries(e))t[n]!==i&&(TF.set(n,i),EF.delete(n),r=!0);if(n)for(let t of n)t in e&&(TF.set(t,e[t]),EF.delete(t),r=!0);for(let n of Object.keys(t))n in e||(TF.delete(n),EF.add(n),r=!0);r&&(gF++,zF())}xF=e,t||NF()}function tI(){return SF}function nI(e,t=!1){if(!t&&e){let t=SF??{},n=!1;for(let[r,i]of Object.entries(e))t[r]!==i&&(DF.set(r,i),n=!0);n&&(gF++,zF())}SF=e,t||NF()}function rI(){return CF}function due(e){if(e){let t=CF??{},n=!1;for(let[r,i]of Object.entries(e))t[r]!==i&&(OF.set(r,i),n=!0);n&&(gF++,zF())}CF=e,NF()}function fue(e,t){let n={...wF??HF(`wodwiki.seedChecks`),[e]:t};wF=n,bF?.[e]&&(bF[e]={...bF[e],checkedAt:t}),LF(sF,n),YF()}function pue(e){return wF&&e in wF?wF[e]??null:bF?.[e]?.checkedAt===void 0?HF(`wodwiki.seedChecks`)[e]??null:bF[e].checkedAt??null}function mue(){xF=null,SF=null,NF()}function hue(e){return PF(e)}var gue=rF,_ue=iF;function iI(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 aI(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 oI=`/seed/core/`;function sI(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 cI(e){return e.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`?aI(t):null,r={id:e.id,label:e.label,url:e.url};return[n?{...r,repositoryUrl:n}:r]})}function lI(){return FF()?cI(sue()??[]):cI(UF())}function uI(e){FF()&&(cue(e),XF()),LF(gue,e)}function dI(){return lI()}function fI(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`source`}function vue(e,t,n){let r=iI(t);if(!r)throw Error(`Enter an absolute http(s) URL of a feed directory.`);let i=lI();if(i.some(e=>iI(e.url)===r)||wue().includes(r))throw Error(`This source is already registered.`);let a=n?.repositoryUrl?.trim(),o;if(a&&(o=aI(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={...Due};for(let e of i)c[e.id]=!0;let l=fI(s);for(let e=2;c[l];e++)l=`${fI(s)}-${e}`;let u={id:l,label:s,url:r,...o?{repositoryUrl:o}:{}};return uI([...i,u]),u}function yue(e){uI(lI().filter(t=>t.id!==e))}function bue(){return gI.map(e=>e.id)}function pI(){return FF()?[...lue()??[]]:WF()}function xue(e){let t=EI(e),n=pI();if(bue().includes(t)&&!n.includes(t)){let e=[...n,t];FF()&&(uue(e),XF()),LF(_ue,e)}}function Sue(){return[...new Set(pI().map(EI))]}var mI={id:`core`,label:`Core`,url:oI,description:`The app's own corpus — guides, the page template, and the reference chunks.`,tier:`core`},Cue=`https://bitcobblers.github.io`;function hI(e,t,n,r,i=!1){return{id:e,label:t,url:`${Cue}/${n}/`,repositoryUrl:`https://github.com/bitcobblers/${n}`,description:r,tier:`community`,...i?{autoImport:!0}:{}}}var gI=[hI(`sport-crossfit`,`CrossFit`,`wod-wiki-sport-crossfit`,`CrossFit benchmark collections (Games, Girls, Heroes) and weekly programming.`),hI(`sport-hyrox`,`HYROX`,`wod-wiki-sport-hyrox`,`HYROX race preparation and simulation workouts.`),hI(`legends-of-kettlebell`,`Kettlebell Coaches`,`wod-wiki-legends-of-kettlebell`,`Kettlebell coach collections and the Dan John 40-Day Program feed.`),hI(`sport-swimming`,`Swimming`,`wod-wiki-sport-swimming`,`Swimming programs from pre-highschool through college, masters, Olympic, and triathlete.`),hI(`sport-track`,`Track & Field`,`wod-wiki-sport-track`,`High-school track programs — 400m (Raffensperger) and sprints (Arrowhead).`),hI(`wayback-zombie-fit`,`ZombieFit`,`wod-wiki-wayback-zombie-fit`,`The ZombieFit parkour archive — daily WODs since 2009.`),hI(`sport-golos-method`,`Golos Method`,`wod-wiki-feed-golos-method`,`Daily minimalist strength and conditioning.`),hI(`yt-dan-john`,`Dan John`,`wod-wiki-youtube-dan-john`,`Dan John kettlebell workouts.`),hI(`yt-mark-wildman`,`Mark Wildman`,`wod-wiki-youtube-mark-wildman`,`Mark Wildman athletic kettlebell and club training.`),hI(`yt-strongfirst`,`StrongFirst`,`wod-wiki-youtube-strongfirst`,`StrongFirst hardstyle kettlebell workouts.`),hI(`yt-the-stone-circle`,`The Stone Circle`,`wod-wiki-youtube-the-stone-circle`,`Sandbag power-endurance and density training.`),hI(`samples-movement`,`Movement Examples`,`wod-wiki-samples-movement`,`Unconventional and parkour-style training examples.`),hI(`samples-results`,`Results Samples`,`wod-wiki-samples-results`,`Recorded sessions from the public sports datasets — HYROX races, athletics, CrossFit leaderboards, and swimming.`),hI(`sport-yoga`,`Yoga Examples`,`wod-wiki-sport-yoga`,`Yoga session examples.`),hI(`r-workoutroutines`,`r/WorkoutRoutines`,`wod-wiki-r-workoutroutines`,`Community feed from the r/WorkoutRoutines subreddit.`)];function wue(){return[oI,...gI.map(e=>e.url)]}function _I(e){return bI().find(t=>t.id===e)}function Tue(e){let t=_I(e);if(!t)throw Error(`unknown feed source: ${e}`);return t}function vI(e,t,n,r,i,a){return Tue(e),{id:`community-${t}`,feedId:e,chunkId:n,label:r,category:i,description:a}}var yI=[vI(`sport-crossfit`,`crossfit-games`,`notebook.crossfit-games`,`CrossFit Games`,`workouts`,`CrossFit Games workouts — Open, Regionals, and Games programming, formatted for Wod Wiki.`),vI(`sport-crossfit`,`crossfit-girls`,`notebook.crossfit-girls`,`CrossFit Girls`,`workouts`,`Classic benchmark workouts — Fran, Helen, Grace, Diane, and more, formatted for Wod Wiki.`),vI(`sport-crossfit`,`crossfit-heroes`,`notebook.crossfit-heroes`,`CrossFit Heroes`,`workouts`,`Hero benchmark workouts honoring service members — Murph, DT, Badger, and more.`),vI(`sport-crossfit`,`crossfit-programming`,`notebook.crossfit-programming`,`CrossFit Programming`,`programs`,`Weekly CrossFit programming — daily strength, conditioning, and skill sessions on a rotation with a weekly benchmark.`),vI(`sport-hyrox`,`hyrox`,`notebook.hyrox`,`HYROX`,`workouts`,`HYROX race preparation — running, sled work, ergs, and functional stations in race format.`),vI(`legends-of-kettlebell`,`geoff-neupert`,`notebook.geoff-neupert`,`Geoff Neupert`,`workouts`,`Geoff Neupert kettlebell workouts — strength and conditioning from a Master SFG coach.`),vI(`legends-of-kettlebell`,`girevoy-sport`,`notebook.girevoy-sport`,`Girevoy Sport`,`workouts`,`Competitive kettlebell sport — jerk, snatch, and long-cycle programming.`),vI(`legends-of-kettlebell`,`joe-daniels`,`notebook.joe-daniels`,`Joe Daniels (Swing This)`,`workouts`,`Joe Daniels kettlebell workouts — kettlebell sport and hardstyle fusion.`),vI(`legends-of-kettlebell`,`keith-weber`,`notebook.keith-weber`,`Keith Weber`,`workouts`,`Keith Weber kettlebell workouts — high-intensity kettlebell cardio.`),vI(`legends-of-kettlebell`,`steve-cotter`,`notebook.steve-cotter`,`Steve Cotter`,`workouts`,`Steve Cotter kettlebell workouts — comprehensive kettlebell education.`),vI(`legends-of-kettlebell`,`dan-john-40-day`,`notebook.dan-john-40-day`,`Dan John 40-Day Program`,`programs`,`Dan John's 40-day barbell program — five lifts, five sets of five, five days a week for 40 sessions.`),vI(`yt-dan-john`,`dan-john`,`notebook.dan-john`,`Dan John Kettlebell`,`workouts`,`Dan John kettlebell workouts — simple, effective programming with clear objectives.`),vI(`yt-mark-wildman`,`mark-wildman`,`notebook.mark-wildman`,`Mark Wildman`,`workouts`,`Mark Wildman workouts — athletic kettlebell and club training.`),vI(`yt-strongfirst`,`strongfirst`,`notebook.strongfirst`,`StrongFirst`,`workouts`,`StrongFirst workouts — hardstyle kettlebell strength and skill.`),vI(`yt-the-stone-circle`,`the-stone-circle`,`notebook.the-stone-circle`,`The Stone Circle`,`workouts`,`Sandbag power endurance and density training — progressive EMOM protocols.`),vI(`sport-swimming`,`swimming-college`,`notebook.swimming-college`,`Swimming: College`,`workouts`,`College swimming training sessions.`),vI(`sport-swimming`,`swimming-highschool`,`notebook.swimming-highschool`,`Swimming: High School`,`workouts`,`High-school swimming training sessions.`),vI(`sport-swimming`,`swimming-masters`,`notebook.swimming-masters`,`Swimming: Masters`,`workouts`,`Masters swimming training sessions.`),vI(`sport-swimming`,`swimming-olympic`,`notebook.swimming-olympic`,`Swimming: Olympic`,`workouts`,`Olympic-caliber swimming training sessions.`),vI(`sport-swimming`,`swimming-post-college`,`notebook.swimming-post-college`,`Swimming: Post-College`,`workouts`,`Post-college swimming training sessions.`),vI(`sport-swimming`,`swimming-pre-highschool`,`notebook.swimming-pre-highschool`,`Swimming: Pre-Highschool`,`workouts`,`Pre-highschool swimming training sessions.`),vI(`sport-swimming`,`swimming-triathlete`,`notebook.swimming-triathlete`,`Swimming: Triathlete`,`workouts`,`Triathlete swim training sessions.`),vI(`sport-track`,`hs-track-400m`,`notebook.hs-track-400m`,`HS Track 400m`,`workouts`,`High-school 400m program after Raffensperger — speed, tempo, and strength phases.`),vI(`sport-track`,`hs-track-sprints`,`notebook.hs-track-sprints`,`HS Track Sprints`,`workouts`,`High-school sprints program after Arrowhead — acceleration, maximum velocity, and speed endurance.`),vI(`wayback-zombie-fit`,`zombiefit`,`notebook.zombiefit`,`ZombieFit`,`workouts`,`The ZombieFit archive — parkour-inspired fitness WODs, 2009–2013.`),vI(`sport-golos-method`,`the-golos-method`,`notebook.the-golos-method`,`The Golos Method`,`workouts`,`Daily minimalist strength and conditioning — dense, repeatable sessions.`),vI(`samples-movement`,`unconventional`,`notebook.unconventional`,`Unconventional`,`workouts`,`Unconventional training — maces, clubs, sandbags, and parkour movement.`),vI(`samples-results`,`hyrox-races`,`notebook.hyrox-races`,`HYROX Race Results`,`results`,`Real HYROX race runs, station by station, from the public Pyrox results.`),vI(`samples-results`,`athletics-results`,`notebook.athletics-results`,`Athletics Results`,`results`,`Track-and-field performances with 100 m splits, from the AthTech Challenge results.`),vI(`samples-results`,`crossfit-leaderboards`,`notebook.crossfit-leaderboards`,`CrossFit Leaderboards`,`results`,`CrossFit Games and Open event-by-event scores from the official leaderboards.`),vI(`samples-results`,`swimming-results`,`notebook.swimming-results`,`Swimming Race Results`,`results`,`Swimming race times from the World Aquatics rankings.`),vI(`samples-results`,`swimming-training`,`notebook.swimming-training`,`Swimming Training Load`,`results`,`Twelve weeks of pool training load, one note per week.`),vI(`sport-yoga`,`yoga`,`notebook.yoga`,`Yoga`,`workouts`,`Yoga sessions for mobility and recovery.`),vI(`r-workoutroutines`,`workoutroutines-reddit`,`notebook.workoutroutines-reddit`,`r/WorkoutRoutines`,`programs`,`Community workouts from the r/WorkoutRoutines subreddit.`)];function bI(){return[mI,...gI,...dI().map(e=>({id:e.id,label:e.label,url:e.url,description:`Custom feed synced from ${e.url}`,tier:`imported`,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{}}))]}function xI(){return bI().filter(e=>e.id!==mI.id)}function SI(){return[...yI,...dI().map(e=>({id:e.id,feedId:e.id,chunkId:e.id,label:e.label,category:`custom`,description:`Custom feed synced from ${e.url}`}))]}function CI(e){return SI().filter(t=>t.feedId===e)}function Eue(e){return SI().find(t=>t.id===e)}function wI(e){let t=e.trim(),n=Eue(t);return n&&n.chunkId.startsWith(`notebook.`)?n.chunkId.replace(/^notebook\./,``):t.startsWith(`notebook/`)||t.startsWith(`notebook:`)||t.startsWith(`notebook.`)?t.slice(9):t}var TI={"seed-crossfit":`sport-crossfit`,"seed-hyrox":`sport-hyrox`,"seed-kettlebell":`legends-of-kettlebell`,"seed-swimming":`sport-swimming`,"seed-track":`sport-track`,"seed-zombie-fit":`wayback-zombie-fit`,"seed-golos-method":`sport-golos-method`,"example-movement":`samples-movement`,"example-yoga":`sport-yoga`};function EI(e){return TI[e]||(yI.find(t=>t.id===e)?.feedId??e)}var Due=Object.fromEntries([[`core`,!0],[`community`,!0],[`common`,!0],[`seed-core`,!0],[`seed-crossfit`,!0],[`seed-hyrox`,!0],[`seed-kettlebell`,!0],[`seed-swimming`,!0],[`seed-track`,!0],[`seed-zombie-fit`,!0],[`seed-golos-method`,!0],[`example-movement`,!0],[`example-yoga`,!0],...gI.map(e=>[e.id,!0]),...yI.map(e=>[e.id,!0])]),DI=`notebook/custom`,OI=new Set(ks.map(e=>e.slug)),Oue=class{store;constructor(e=X){this.store=e}tail=Promise.resolve();listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(let e of[...this.listeners])try{e()}catch{}}enqueue(e,t=!1){let n=this.tail.then(e,e);return this.tail=n.then(()=>void 0,()=>void 0),t?n.then(e=>(this.notify(),e)):n}getFeedNotebooks(){let e=[];for(let t of SI()){if(t.category===`dashboards`)continue;let n=t.chunkId.replace(/^notebook\./,``);e.push({id:Cs(n),slug:n,notebookId:Cs(n),name:t.label,description:t.description,icon:t.category===`feeds`?`📡`:`📚`,origin:`feed`,feedEntryId:t.feedId,seedChunkId:t.chunkId,createdAt:0})}return e}getDefaultNotebooks(){return ks.map(e=>({id:e.notebookId,slug:e.slug,notebookId:e.notebookId,name:e.name,description:e.description,icon:e.icon,origin:`default`,...e.feedEntryId?{feedEntryId:e.feedEntryId}:{},...e.seedChunkId?{seedChunkId:e.seedChunkId}:{},createdAt:0}))}async getAllNotebooks(){let e=new Map;for(let t of[...this.getDefaultNotebooks(),...this.getFeedNotebooks(),...await this.getAll()])e.set(t.notebookId,t);return[...e.values()]}async getAll(){let e=await this.store.getAllNotes(),t=e.filter(As),n=new Set(t.map(e=>e.id.slice(9))),r=t.map(AI),i=new Set(this.getFeedNotebooks().map(e=>e.slug));for(let t of e)if(t.feedOrigin!==`feed`&&t.seedOrigin!==`seed`&&t.retention!==`cached`&&t.retention!==`session-pinned`&&t.retention!==`indexed`&&t.notebookId?.startsWith(`notebook/`)){let e=t.notebookId.slice(9);e&&!OI.has(e)&&!i.has(e)&&!n.has(e)&&(n.add(e),r.push({id:t.notebookId,slug:e,notebookId:Cs(e),name:e,description:``,icon:`📓`,origin:`user`,createdAt:t.createdAt}))}return r.sort((e,t)=>e.createdAt-t.createdAt)}async getById(e){let t=Cs(e),n=await this.store.getNote(t);return n&&As(n)?AI(n):null}create(e,t=``,n=`📓`){return this.enqueue(()=>this.createNow(e,t,n),!0)}async createNow(e,t,n){let r=await this.getAll(),i=tue(e),a=new Set([...OI,...this.getFeedNotebooks().map(e=>e.slug),...r.map(e=>e.slug)]),o=i;for(let e=2;a.has(o);e++)o=`${i}-${e}`;let s=Cs(o);return AI(await this.saveLanding(s,e,t,n))}async saveLanding(e,t,n,r,i,a){let o=async a=>{let o=Aue(t,n,r),s={...await a.saveNoteSource({noteId:e,rawContent:o,blocks:Vs(o,{sourceRevision:i||1}),expectedSourceRevision:i??0,metadata:{title:t}}),notebookId:e,type:`note`,seedOrigin:`user`};return i===void 0&&(s.createdAt=Date.now()),await a.saveNote(s),s};return a?o(a):this.store.withTransaction([`notes`,`block_revisions`,`note_revisions`,`sessions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`],o)}update(e,t){return this.enqueue(async()=>{let n=Cs(e);kue(n);let r=await this.store.getNote(n);if(!r||!As(r))throw Error(`Notebook not found: ${e}`);let i=kI(r);return AI(await this.saveLanding(r.id,t.name??r.title,t.description??i.description,t.icon??i.icon,r.sourceRevision))},!0)}delete(e){return this.enqueue(async()=>{await yC(this.store.storage,e)},!0)}async listNotes(e,t=this.store){let n=Cs(e),r=await t.getAllNotes(),i=new Set;try{let e=await t.storage.readonly(`notebook_links`).getAllFromIndex(`by-notebook`,n);i=new Set(e.filter(e=>e.targetKind===`note`).map(e=>e.noteId))}catch{}return r.filter(e=>!As(e)&&(i.has(e.id)||e.notebookId===n||Hy(e).includes(n)))}promoteNote(e,t,n={}){return this.enqueue(async()=>{for(let e of t){let t=Cs(e);if(bs(t)||this.getFeedNotebooks().some(e=>e.notebookId===t))throw Error(`Notebook ${t} is read-only.`)}return HS(this.store.storage,{noteId:e,notebookIds:t,sessionIds:n.sessionIds,shareSessionsPublicly:n.shareSessionsPublicly})},!0)}setNoteNotebooks(e,t){return this.enqueue(async()=>{for(let e of t){let t=Cs(e);if(t!==`notebook/journal`&&t!==`notebook/playground`&&(bs(t)||this.getFeedNotebooks().some(e=>e.notebookId===t)))throw Error(`Notebook ${t} is read-only.`)}return US(this.store.storage,{noteId:e,notebookIds:t})},!0)}removeNoteFromNotebook(e,t){return this.enqueue(()=>WS(this.store.storage,e,t),!0)}getNoteNotebooks(e){return GS(this.store.storage,e)}moveNote(e,t){return this.enqueue(async()=>{if(!await this.store.getNote(e))throw Error(`Note not found: ${e}`);if(t===null){await US(this.store.storage,{noteId:e,notebookIds:[]});return}let n=Cs(t);if(bs(n)||this.getFeedNotebooks().some(e=>e.notebookId===n))throw Error(`Notebook ${n} is feed-delivered or system read-only.`);await US(this.store.storage,{noteId:e,notebookIds:[n]})},!0)}cloneNote(e,t,n){return this.enqueue(async()=>{let r=Cs(t);if(bs(r)||this.getFeedNotebooks().some(e=>e.notebookId===r))throw Error(`Notebook ${r} is read-only.`);let i=await this.store.getNote(e);if(!i)throw Error(`Note not found: ${e}`);let a=i.rawContent,o=Date.now(),s=Hy(i)[0],c=await this.store.saveNoteSource({noteId:Br(),rawContent:a,blocks:Vs(a,{sourceRevision:1}),expectedSourceRevision:0,createdAt:o,metadata:{title:n??i.title,type:`note`,sourceId:i.id,...i.tags?.length?{tags:[...i.tags]}:{}}}),l=r===`notebook/journal`?[`notebook/journal`]:[r],u={...c,notebookId:r,notebookIds:l,seedOrigin:`user`,provenance:RC(i,s,o)};return await this.store.saveNote(u),await HS(this.store.storage,{noteId:u.id,notebookIds:l}),await this.store.getNote(u.id)??u},!0)}ensureNotebooks(){return this.enqueue(async()=>{let e=await fS(`onboarding/my-workout`);await this.store.withTransaction([`notes`,`block_revisions`,`note_revisions`,`sessions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`notebook_links`,`meta`],async t=>{let n=await t.getAllNotes();n.some(e=>As(e)&&e.id===`notebook/custom`)||await this.saveLanding(DI,`Custom`,`User overrides and custom Tags, Efforts, Equipment, and starter workouts.`,`C`,void 0,t);for(let e of n)e.type===`template`&&await t.saveNote({...e,type:`note`,notebookId:e.notebookId??`notebook/custom`,seedOrigin:e.seedOrigin??`user`});if((await t.storage.readonly(`meta`).get(`onboarding:starterSeeded`))?.value)return;let r=await this.listNotes(DI,t);if(!n.some(t=>t.id===e)&&r.length===0){let n=Date.now(),r="# My Workout\n\n```time\n10 Push-ups\n```\n",i=await t.saveNoteSource({noteId:e,rawContent:r,blocks:Vs(r,{sourceRevision:1}),expectedSourceRevision:0,createdAt:n,metadata:{title:`My Workout`,type:`note`}}),a=[`notebook/journal`,DI];await t.saveNote({...i,notebookId:DI,notebookIds:a,seedOrigin:`user`});try{await t.storage.readwrite(`notebook_links`).putMany(a.map(t=>({id:IS(t,`note`,e),notebookId:t,targetKind:`note`,targetId:e,noteId:e,createdAt:n})))}catch{}}await t.storage.readwrite(`meta`).put({key:`onboarding:starterSeeded`,value:!0})})})}};function kue(e){if(OI.has(Ss(e)))throw Error(`Notebook ${e} is always present and cannot be changed.`)}function Aue(e,t,n){return`---\ndescription: ${t?JSON.stringify(t.replace(/\n/g,` `)):``}\nicon: ${n?JSON.stringify(n.replace(/\n/g,` `)):``}\n---\n\n# ${e}\n`}function kI(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e.rawContent),n=``,r=`📓`,i=e=>{if(e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`))try{return JSON.parse(e)}catch{return e}return e};if(t)for(let e of t[1].split(/\r?\n/)){let t=e.match(/^(description|icon):\s*(.*)$/);t&&(t[1]===`description`?n=i(t[2].trim()):r=i(t[2].trim())||r)}return{description:n,icon:r}}function AI(e){let{description:t,icon:n}=kI(e);return{id:e.id,slug:e.id.slice(9),notebookId:Cs(e.id),name:e.title,description:t,icon:n,origin:`user`,createdAt:e.createdAt}}var jI=new Oue;function MI(e){return jI.subscribe(e)}var jue=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async putMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).put(e)})}async deleteMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).delete(e)})}async getAllMeta(){return await this.storageInstance.readonly(`meta`).getAll()}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 moe(this.storageInstance,e)}applyChunks(e){return _S(this.storageInstance,e)}backfillFeedProvenance(){return _oe(this.storageInstance)}migrateNotebookVocabulary(){return voe(this.storageInstance)}async removeSourceContent(e){return cC(this.storageInstance,e)}async removeSourceContentById(e){return dC(this.storageInstance,e)}async removeNotebookContent(e,t){return Hoe(this.storageInstance,e,t)}async reconcileRemovedRecords(e,t,n){return Uoe(this.storageInstance,e,t,n)}};function NI(){return new jue(YP)}var PI=aF,FI=oF;function II(){let e=$F();if(e)return e;let t=VF(PI);return eI(t,!0),t}function LI(){return FF()?{...$F()??{}}:{...II(),...VF(PI)}}function RI(e,t){eI(e,!1,t);let n=LF(PI,e);return FF()?(YF(),!0):n}function zI(e){let t=EI(e);if(t===`core`)return`full`;let n=II();if(n[t]===!0||n[e]===!0)return`full`;let r=`${t}#`,i=`${e}#`;return Object.entries(n).some(([e,t])=>t===!0&&(e.startsWith(r)||e.startsWith(i)))?`partial`:`unsubscribed`}function BI(e){return e===`core`||zI(e)!==`unsubscribed`}function VI(e,t){if(e===`core`)return!0;let n={},r=`${e}#`;for(let[t,i]of Object.entries(LI()))t.startsWith(r)||yI.some(n=>n.feedId===e&&n.id===t)||(n[t]=i);return n[e]=t,RI(n,[e])}function HI(e,t){let n=EI(e);if(n===`core`)return!0;let r=II(),i=`${n}#${t}`;if(i in r)return r[i]===!0;let a=`${e}#${t}`;return a in r?r[a]===!0:r[n]===!0||r[e]===!0}function UI(e,t,n,r){if(e===`core`)return!0;let i={...LI()},a=`${e}#${t}`,o=`${e}#`,s=r??yI.filter(t=>t.feedId===e).map(e=>e.chunkId);if(i[e]===!0&&!n){i[e]=!1;for(let n of s)n!==t&&(i[`${e}#${n}`]=!0);return i[a]=!1,RI(i,[e,a,...s.filter(e=>e!==t).map(t=>`${e}#${t}`)])}if(i[a]=n,n&&s.length>0&&s.every(n=>n===t||i[`${e}#${n}`]===!0)){i[e]=!0;for(let e of Object.keys(i))e.startsWith(o)&&delete i[e];return RI(i,[e])}return!n&&s.length>0&&s.every(t=>i[`${e}#${t}`]===!1)?(i[e]=!1,RI(i,[e,a])):RI(i,[a])}function WI(e){let t=EI(e),n=zI(t);if(n===`full`)return null;if(n===`unsubscribed`)return[];let r=II(),i=`${t}#`,a=`${e}#`;return Object.entries(r).filter(([e,t])=>t===!0&&(e.startsWith(i)||e.startsWith(a))).map(([e])=>e.startsWith(i)?e.slice(i.length):e.slice(a.length))}function GI(e){return PF(e)}function KI(){let e=tI();if(e)return e;let t=VF(FI);return nI(t,!0),t}function qI(e){let t=KI();return e in t?t[e]===!0:e===`core`}function JI(e,t){let n={...KI(),[e]:t};nI(n);let r=LF(FI,n);return FF()?(YF(),!0):r}function YI(e){let t=EI(e);if(t===`core`)return`offline-full`;let n=rI();if(n){if(n[t])return n[t];if(n[e])return n[e]}let r=QF();if(r){let n=r[t]??r[e];if(n?.offlinePolicy)return n.offlinePolicy}return`index-only`}function XI(e,t){let n=EI(e)===`core`?`offline-full`:t;return due({...rI()??{},[e]:n}),FF()&&YF(),!0}async function Mue(e,t=NI()){t.storageInstance&&!FF()&&await ZF(t.storageInstance);let n={...LI()},r=[],i=!1;for(let[e,t]of Object.entries(TI))e in n&&(t in n||(n[t]=n[e],n[e]&&r.push(t)),delete n[e],i=!0);for(let e of yI){let t=e.chunkId.replace(/^notebook\./,``),r=`${e.feedId}#${e.chunkId}`,a=[e.feedId];for(let[t,n]of Object.entries(TI))n===e.feedId&&a.push(t);for(let o of a)for(let a of[`collection.${t}`,`feed.${t}`,e.chunkId]){let e=`${o}#${a}`;e===r||!(e in n)||(r in n||(n[r]=n[e]),delete n[e],i=!0)}}for(let e of yI)e.id in n&&(e.feedId in n||(n[e.feedId]=n[e.id],n[e.id]&&r.push(e.feedId)),delete n[e.id],i=!0);i&&RI(n);let a=[];for(let{id:r}of e)if(!(r===`core`||r in n))try{let e=await t.getSeedMeta(bx(r));e&&e.seedVersion>0&&a.push(r)}catch{}let o=!1;if(a.length>0){let e={...LI()};for(let t of a)t in e||(e[t]=!0,r.push(t),o=!0);o&&RI(e)}return(o||i)&&await JF(),r}typeof window<`u`&&window.addEventListener(`storage`,e=>{(e.key===null||e.key===PI||e.key===FI)&&(FF()||mue())});var ZI=e(Iee(),1),Nue=class extends Error{constructor(e=`That file is not a valid .zip bundle archive.`){super(e),this.name=`InvalidBundleError`}},Pue=class extends Error{constructor(e=`This .zip archive contains no portable notes (.md) or telemetry bundles (.jsonl/.csv).`){super(e),this.name=`EmptyBundleError`}},Fue=class extends Error{stage;constructor(e,t){super(t),this.name=`FeedExportError`,this.stage=e}},QI=class e{zip;constructor(e){this.zip=e??new ZI.default}static async fromBlob(t){let n=await ZI.default.loadAsync(t);return new e(n)}async read(e){let t=TS(e),n=this.zip.file(t);if(!n)throw new xS(`not-found`,`Zip entry not found: ${t}`);return n.async(`uint8array`)}async stat(e){let t=TS(e),n=this.zip.file(t);if(!n)return;let r=await n.async(`uint8array`);return{bytes:r.byteLength,sha256:await ES(r)}}async write(e,t){let n=TS(e);this.zip.file(n,t)}async writeText(e,t){await this.write(e,CS(t))}async delete(e){let t=TS(e);this.zip.remove(t)}async list(e=``){let t=e?TS(e)+`/`:``;return Object.keys(this.zip.files).filter(e=>!this.zip.files[e]?.dir&&(!t||e.startsWith(t))).sort()}toBlob(){return this.zip.generateAsync({type:`blob`})}toUint8Array(){return this.zip.generateAsync({type:`uint8array`})}};function $I(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}function eL(e,t,n=`text/plain;charset=utf-8`){$I(new Blob([e],{type:n}),t)}function Iue(e=`.md,.jsonl,.csv,.zip`){let{promise:t,resolve:n}=Promise.withResolvers(),r=document.createElement(`input`);return r.type=`file`,r.accept=e,r.onchange=()=>n(r.files?.[0]??null),r.oncancel=()=>n(null),r.click(),t}function tL(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`)||`note`}function nL(e){return{id:e.id,title:e.title,rawContent:e.rawContent,sourceRevision:e.sourceRevision??1,blocks:e.blocks??{},date:e.targetDate,createdAt:e.createdAt,...e.tags.length>0?{tags:e.tags}:{},...e.sourceId?{sourceId:e.sourceId}:{},...e.notebookId?{notebookId:e.notebookId}:{}}}function rL(e,t=of){let n=Kb(e,{defaultDate:t.nowMs()});return{...n.id?{id:n.id}:{},title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:n.date??t.nowMs(),sections:[],blocks:n.blocks,sourceRevision:1,...n.notebookId?{notebookId:n.notebookId}:{}}}async function iL(e,t){await t?.persistenceReady;let n=t?.persistenceStorage,r=n?await n.getSessionsForNote(e.id):e.extendedResults??[],i=[];if(n)for(let e of r)i.push(...await n.getEventsByResult(e.id));return{sessions:r,events:i,revisions:n?await n.getNoteBlockHistory(e.id):[]}}function aL(e){return e.sessions.length>0||e.events.length>0||e.revisions!==void 0&&e.revisions.length>0}async function oL(e,t={}){let n=await e.getRecords();if(n.length===0)throw Error(`No notes to export`);let r=t.telemetryFormat??`jsonl`,i=of,a=new QI;for(let t of n){let n=tL(t.id),i=Gb(nL(t));await a.writeText(`${n}.md`,i);let o=await iL(t,e);aL(o)&&((r===`jsonl`||r===`both`)&&await a.writeText(`${n}.jsonl`,yc(o)+`
|
|
788
788
|
`),(r===`csv`||r===`both`)&&await a.writeText(`${n}.csv`,ux(o)))}$I(await a.toBlob(),`wod-wiki-export-${i.nowMs()}.zip`)}async function sL(e,t,n={}){let r=of,i=tL(e.title||e.id),a=Gb(nL(e));if(n.format===`md`){eL(a,`${i}.md`,`text/markdown;charset=utf-8`);return}let o=await iL(e,t);if(n.format===`jsonl`){eL(yc(o)+`
|
|
789
789
|
`,`${i}.jsonl`,`application/x-ndjson;charset=utf-8`);return}if(n.format===`csv`){eL(ux(o),`${i}.csv`,`text/csv;charset=utf-8`);return}let s=new QI,c=tL(e.id);await s.writeText(`${c}.md`,a),aL(o)&&(await s.writeText(`${c}.jsonl`,yc(o)+`
|
|
790
|
-
`),await s.writeText(`${c}.csv`,ux(o))),$I(await s.toBlob(),`${i}-${r.nowMs()}.zip`)}async function cL(e,t,n){let r=[],i=new Set,a=0,o=0;for(let s of e){let e=s.note?.id??s.revisions?.[0]?.noteId??s.sessions[0]?.noteId??s.events[0]?.noteId;if(!(e&&n.skipBundles?.has(e))){if(!n.revisionsRestored&&s.revisions&&s.revisions.length>0)try{let e=t.persistenceStorage;if(!e)throw Error(`Revision import requires provider.persistenceStorage`);await t.persistenceReady,await e.saveBlockRevisions(s.revisions)}catch(t){r.push(`Failed to restore revisions for ${e??`unknown note`}: ${t instanceof Error?t.message:String(t)}`);continue}if(s.note&&!n.skipNotes.has(s.note.id))try{let e=await t.getRecord(s.note.id),n={...s.note,tags:s.note.tags??[],sourceRevision:e?.sourceRevision??s.note.sourceRevision,blocks:e?.rawContent===s.note.rawContent?e.blocks:s.note.blocks};await t.saveRecord(n),i.add(s.note.id)}catch(e){r.push(`Failed to import note ${s.note.id}: ${e instanceof Error?e.message:String(e)}`);continue}if(s.sessions.length>0||s.events.length>0){let e=t.persistenceStorage;if(!e){r.push(`Telemetry import requires provider.persistenceStorage`);continue}await t.persistenceReady;for(let n of s.sessions)try{if(!await t.getRecord(n.noteId))throw Error(`Parent note ${n.noteId} does not exist`);let r=await e.getBlockRevision(n.noteId,n.blockId,n.blockVersion);if(!r||r.kind!==`wod`)throw Error(`Pinned wod BlockRevision [${n.noteId}, ${n.blockId}, ${n.blockVersion}] does not exist`);let i=s.events.filter(e=>e.resultId===n.id);for(let e of i)if(e.noteId!==n.noteId||e.blockId!==n.blockId||e.blockVersion!==n.blockVersion||e.blockContentId!==n.blockContentId)throw Error(`Event ${e.id} does not match session ${n.id} identity`);let c=i.filter(e=>e.grain===`event`),l=i.filter(e=>e.grain===`summary`),u=l.length>0?l:My(Fy(c),{noteId:n.noteId,resultId:n.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,origin:n.origin,pageId:n.pageId,workoutTimestamp:n.startTime});await e.withTransaction([`notes`,`block_revisions`,`sessions`,`events`],async e=>{await e.saveSession(n),i.length>0&&(await e.appendEvents(c),await e.finalizeSummaries(n.id,u))}),a++,o+=c.length+u.length}catch(e){r.push(`Failed to import session ${n.id}: ${e instanceof Error?e.message:String(e)}`)}}}}return{noteIds:i,sessions:a,events:o,errors:r}}async function Lue(e,t){try{let n=rL(e,of),r=n.id?await t.getRecord(n.id):null;return await t.saveRecord({...n,sourceRevision:r?.sourceRevision??n.sourceRevision,blocks:r?.rawContent===n.rawContent?r.blocks:n.blocks}),{imported:1,sessionsImported:0,eventsImported:0,errors:[]}}catch(e){return{imported:0,sessionsImported:0,eventsImported:0,errors:[e instanceof Error?e.message:String(e)]}}}async function Rue(e,t){let n=bc(e),r=await cL(n.bundles,t,{skipNotes:new Set});return{imported:r.noteIds.size,sessionsImported:r.sessions,eventsImported:r.events,errors:[...n.errors,...r.errors]}}async function zue(e,t){let n=dx(e),r=await cL(n.bundles,t,{skipNotes:new Set});return{imported:r.noteIds.size,sessionsImported:r.sessions,eventsImported:r.events,errors:[...n.errors,...r.errors]}}async function lL(e,t){let n=e.name.toLowerCase();if(n.endsWith(`.md`)||n.endsWith(`.markdown`))return Lue(await e.text(),t);if(n.endsWith(`.jsonl`))return Rue(await e.text(),t);if(n.endsWith(`.csv`))return zue(await e.text(),t);let r=of,i;try{i=await ZI.default.loadAsync(await e.arrayBuffer())}catch{throw new Nue}let a=[],o=new Set,s=new Set,c=0,l=0,u=Object.keys(i.files).filter(e=>!i.files[e]?.dir),d=u.filter(e=>!e.startsWith(`dist/`)),f=d.some(e=>e.endsWith(`.jsonl`)||e.endsWith(`.csv`)||e.endsWith(`.md`)&&!/(?:^|\/)README\.md$/i.test(e))?d:u,p=f.filter(e=>e.endsWith(`.jsonl`)),m=f.filter(e=>e.endsWith(`.csv`)),h=f.filter(e=>e.endsWith(`.md`)&&!/(?:^|\/)README\.md$/i.test(e));if(p.length===0&&m.length===0&&h.length===0)throw new Pue;let g=[];for(let e of p){let t=await i.files[e].async(`text`);g.push({source:e,parsed:bc(t)})}let _=new Set(p.map(e=>e.replace(/\.jsonl$/i,``)));for(let e of m){if(_.has(e.replace(/\.csv$/i,``)))continue;let t=await i.files[e].async(`text`);g.push({source:e,parsed:dx(t)})}for(let{source:e,parsed:n}of g)for(let r of n.bundles){if(!r.revisions||r.revisions.length===0)continue;let n=r.note?.id??r.revisions[0]?.noteId;try{let e=t.persistenceStorage;if(!e)throw Error(`Revision import requires provider.persistenceStorage`);await t.persistenceReady,await e.saveBlockRevisions(r.revisions)}catch(t){n&&s.add(n),a.push(`${e}: Failed to restore revisions for ${n??`unknown`}: ${t instanceof Error?t.message:String(t)}`)}}for(let e of h)try{let n=rL(await i.files[e].async(`text`),r);if(n.id&&s.has(n.id)){a.push(`Failed to import ${e}: revision restoration failed for ${n.id}`);continue}let c=n.id?await t.getRecord(n.id):null,l=await t.saveRecord({...n,seedOrigin:c?.seedOrigin??`user`,sourceRevision:c?.sourceRevision??n.sourceRevision,blocks:c?.rawContent===n.rawContent?c.blocks:n.blocks});o.add(l.id)}catch(t){a.push(`Failed to import ${e}: ${t instanceof Error?t.message:String(t)}`)}for(let{source:e,parsed:n}of g){a.push(...n.errors.map(t=>`${e}: ${t}`));let r=await cL(n.bundles,t,{skipNotes:o,revisionsRestored:!0,skipBundles:s});for(let e of r.noteIds)o.add(e);c+=r.sessions,l+=r.events,a.push(...r.errors.map(t=>`${e}: ${t}`))}return{imported:o.size,sessionsImported:c,eventsImported:l,errors:a}}async function Bue(){{let e=await fetch(`/api/v1/feed/status`);if(e.ok)return{...await e.json(),mode:`self-hosted`}}return await ZP(),{...await FS(YP),mode:`browser-repo`}}async function uL(e={}){let t=await fetch(`/api/v1/feed/publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Publish failed (HTTP ${t.status})`)}let n=await t.json();return{report:n,feedUrl:n.feedUrl}}var Vue=3e4,Hue=5e3;async function dL(e,t,n){let r=new AbortController,i,a=new Promise((t,a)=>{i=setTimeout(()=>{r.abort(),a(new Fue(e,`Feed repository export timed out during ${e} (${Math.max(1,Math.round(n/1e3))}s).`))},n)});try{return await Promise.race([t(r.signal),a])}finally{i!==void 0&&clearTimeout(i)}}async function fL(e={}){let{stageTimeoutMs:t=Vue,...n}=e;await dL(`storage initialization`,()=>ZP(),t);let r=new QI,i=await dL(`feed compilation`,e=>PS(YP,r,{...n,layout:`repository`,recordCheckpoint:!1,signal:e}),t);return $I(await dL(`zip archive generation`,()=>r.toBlob(),t),`${(n.name??`wod-wiki-feed-repository`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`wod-wiki-feed-repository`}.zip`),await dL(`checkpoint persistence`,()=>NS(YP,i),Math.min(t,Hue)).catch(()=>void 0),i}function Uue(){return typeof window<`u`&&`showDirectoryPicker`in window}async function pL(e={}){let t=window;if(!t.showDirectoryPicker)throw Error(`Directory picker is not supported in this browser; use ZIP export instead.`);let n;try{n=await t.showDirectoryPicker({mode:`readwrite`})}catch{return null}return await ZP(),PS(YP,new koe(n),{...e,layout:`repository`,recordCheckpoint:!0})}var mL=`catalog:`;function hL(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`catalog:`)&&`manifest`in e}function gL(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`feed:index:`)&&`index`in e}function Wue(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`seed:`)}async function _L(e){return e||(await ZP().catch(()=>void 0),YP)}async function vL(e){let t=e??YP;FF()||await ZF(t).catch(()=>void 0)}async function yL(e,t,n){let r={key:`${mL}${e}`,feedId:e,manifest:t,updatedAt:Date.now()};try{let e=await _L(n);if(!e)return;await e.transaction([`meta`],`readwrite`,async e=>{await e.readwrite(`meta`).put(r)})}catch{}}async function bL(e,t){try{let n=await _L(t);if(!n)return;let r=await n.readonly(`meta`).get(`${mL}${e}`);return hL(r)?r.manifest:void 0}catch{return}}async function xL(e,t,n,r){let i={key:gx(e,t),feedId:e,notebookId:t,index:n,updatedAt:Date.now()};try{let e=await _L(r);if(!e)return;await e.transaction([`meta`],`readwrite`,async e=>{await e.readwrite(`meta`).put(i)})}catch{}}async function Gue(e,t,n){try{let r=await _L(n);if(!r)return;let i=await r.readonly(`meta`).get(gx(e,t));return gL(i)?i.index:void 0}catch{return}}function Kue(e){return e.notebooks&&e.notebooks.length>0?e.notebooks:e.chunks.filter(e=>e.id.startsWith(`notebook.`)).map(t=>{let n=Sx(t.id)??t.id.slice(9);return{notebookId:t.id,label:n.replace(/-/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),indexPath:`indexes/notebooks/${t.id}.json`,version:e.version,commit:e.commit??``,builtAt:e.builtAt,sha256:t.sha256,bytes:t.bytes,chunkBytes:t.bytes,count:t.count}})}async function SL(e,t){let n=iI(e)??(e.startsWith(`/`)?sI(e):null);if(!n&&!t?.source)throw Error(`Enter an absolute http(s) URL of a feed directory.`);let r;r=t?.source?await t.source.fetchManifest():await new OS(n).readJson(`manifest.json`);let i=rS(r),a=n??e,o=t?.feedId??xI().find(e=>iI(e.url)===n)?.id;o&&await yL(o,i,t?.storage);let s=Kue(i),c=s.length>0?s.reduce((e,t)=>e+t.count,0):i.chunks.reduce((e,t)=>e+t.count,0),l=i.indexBytes??s.reduce((e,t)=>e+(t.indexBytes??0),0),u=i.chunkBytes??(i.chunks.length>0?i.chunks.reduce((e,t)=>e+(t.bytes??0),0):s.reduce((e,t)=>e+(t.chunkBytes??0),0)),d=aI(i.repositoryUrl??``)??void 0,f;try{f=new URL(a).hostname||`Feed`}catch{f=`Feed`}return{url:a,manifest:i,name:i.name?.trim()||f,...i.description?.trim()?{description:i.description.trim()}:{},...d?{repositoryUrl:d}:{},version:i.version,schema:i.schema,builtAt:i.builtAt,notebooks:s,notebookCount:s.length,itemCount:c,indexBytes:l,chunkBytes:u,hasOfflineChunks:i.chunks.length>0||u>0}}var CL=new Map,wL=new Map,TL=new Map;function EL(e){let t=`remote:${e.feedId}:${e.record.uuid}`;wL.set(t,e),wL.set(e.record.uuid,e),TL.set(e.record.uuid,e)}function DL(e){return wL.get(e)??TL.get(e)}function que(e){let t=/^remote:([^:]+):(.+)$/.exec(e);return t?{feedId:t[1],uuid:t[2]}:{uuid:e}}function OL(e,t){if(t){let n=new TextEncoder;return{async read(e){if(/\.md$/i.test(e)&&t.fetchText)return n.encode(await t.fetchText(e));let r=await t.fetchChunk(e);return n.encode(JSON.stringify(r))},async readText(n){if(t.fetchText)return t.fetchText(n);if(/\.json$/i.test(n))return JSON.stringify(await t.fetchChunk(n));throw Error(`Feed source for ${e.feedId} cannot read text '${n}'`)},async stat(){}}}return new OS(e.feedUrl)}function kL(e,t){if(e)return wI(e);let n=/^markdown\/notebooks\/([^/]+)\//.exec(t??``);return n?.[1]?wI(n[1]):`workouts`}function AL(e){return e.title?.trim()?e.title.trim():(e.path.split(`/`).at(-1)??e.path).replace(/\.md$/i,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}async function jL(e,t){let n=typeof e==`string`?{noteId:e}:e,r=n.noteId??n.uuid;if(r){let e=DL(r);if(e)return{entry:e,canonicalUuid:e.record.uuid,requestedFeedId:e.feedId}}let i=n.noteId?que(n.noteId):{feedId:n.feedId,uuid:n.uuid},a=n.uuid??i.uuid,o=n.feedId??i.feedId,s=n.feedUrl??(o?_I(o)?.url:void 0);if(n.record||(n.recordPath||n.rawUrl||n.path)&&(s||t?.source)){let e=n.record??{uuid:a??``,path:n.path??n.recordPath??n.rawUrl??``,...n.recordPath?{recordPath:n.recordPath}:{},...n.rawUrl?{rawUrl:n.rawUrl}:{},commit:``,version:n.version??1,sha256:``,...n.title?{title:n.title}:{},...n.date===void 0?{}:{date:n.date}};if(o||s||t?.source){let t=o??`remote`,r={feedId:t,feedUrl:s??``,notebookSlug:n.notebookSlug??kL(n.notebookId,e.path),record:e};return e.uuid&&EL(r),{entry:r,canonicalUuid:e.uuid||a,requestedFeedId:t}}}let c=await _L(t?.storage);if(c&&a)try{let e=await c.readonly(`meta`).getAll();for(let t of e){if(!gL(t)||o&&t.feedId!==o)continue;let e=t.index.records.find(e=>e.uuid===a);if(!e)continue;let n=s??_I(t.feedId)?.url??``,r={feedId:t.feedId,feedUrl:n,notebookSlug:kL(t.notebookId,e.path),record:e};return EL(r),{entry:r,canonicalUuid:e.uuid,requestedFeedId:t.feedId}}}catch{}if(o&&(s||t?.source)&&a)try{let e=OL({feedId:o,feedUrl:s??``,notebookSlug:`workouts`,record:{uuid:a,path:``,commit:``,version:1,sha256:``}},t?.source),n=c?await bL(o,c):void 0;!n&&t?.source?n=rS(await t.source.fetchManifest()):!n&&s&&(n=rS(await new OS(s).readJson(`manifest.json`)));for(let t of n?.notebooks??[]){let n=await tC(e,t.indexPath);c&&await xL(o,t.notebookId,n,c);for(let e of n.records)EL({feedId:o,feedUrl:s??``,notebookSlug:kL(t.notebookId,e.path),record:e});let r=DL(a);if(r)return{entry:r,canonicalUuid:r.record.uuid,requestedFeedId:o}}}catch{}return{entry:void 0,canonicalUuid:a,requestedFeedId:o}}function Jue(e){return{path:e.sourcePath??`${e.id}.md`,content:e.rawContent,blocks:e.blocks,blockIndex:[],blockEfforts:[],blockEquipment:[],commit:e.seedCommit,uuid:e.id,version:e.seedVersion}}async function ML(e,t={}){let{entry:n,canonicalUuid:r,requestedFeedId:i}=await jL(e,t),a=await _L(t.storage);if(a&&r&&!t.forceRefresh)try{let e=await a.readonly(`notes`).get(r);if(e){let t=e.seedOrigin!==`seed`&&e.feedOrigin!==`feed`&&!e.retention,r=n?.record.version??0,a=e.seedVersion??0,o=e.retention===`cached`&&e.rawContent.length>0&&(r===0||a>=r);if(t||e.retention===`session-pinned`||e.retention===`schedule-pinned`||o){let t=Jue(e),r=e.feedSourceId??i;return{note:e,seedRow:t,row:t,feedId:r,...n?{notebookSlug:n.notebookSlug,record:n.record}:{},...r?{remoteNoteId:`remote:${r}:${e.id}`}:{},canonicalNoteId:e.id,fromCache:!0}}}}catch{}if(!n)return;let o=await nC(OL(n,t.source),n.record,{fetchImpl:t.fetchImpl});if(a&&t.cache!==!1){let e=await iC(a,{feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,seedRow:o,retention:`cached`,upstreamStatus:`live`});return{note:e,seedRow:o,row:o,feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,remoteNoteId:`remote:${n.feedId}:${e.id}`,canonicalNoteId:e.id,fromCache:!1}}let s=n.record.uuid||o.uuid||r||o.path;return{note:{id:s,title:n.record.title||o.blockIndex[0]?.noteTitle||AL(n.record),rawContent:o.content,sourceRevision:1,blocks:o.blocks,...n.record.date===void 0?{}:{date:n.record.date},createdAt:n.record.date??0,notebookId:`notebook/${n.notebookSlug}`,feedOrigin:`feed`,feedSourceId:n.feedId,seedOrigin:`seed`,seedChunkId:`notebook.${n.notebookSlug}`,seedVersion:n.record.version??o.version??1,sourcePath:o.path,retention:`cached`,upstreamStatus:`live`},seedRow:o,row:o,feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,remoteNoteId:`remote:${n.feedId}:${s}`,canonicalNoteId:s,fromCache:!1}}async function NL(e,t={}){let{entry:n}=await jL(e,t);if(!n)return;let r=await nC(OL(n,t.source),n.record,{fetchImpl:t.fetchImpl});if(t.cache!==!1)try{let e=await _L(t.storage);e&&await iC(e,{feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,seedRow:r,retention:`cached`,upstreamStatus:`live`})}catch{}return r}async function Yue(e,t,n={}){let{entry:r}=await jL(e,n);if(!r)throw Error(`Remote record metadata not found for ${e}`);let i=await _L(n.storage);if(!i)throw Error(`Storage is not ready for cloning remote record`);return Ioe(i,OL(r,n.source),{feedId:r.feedId,record:r.record,targetNotebookId:t,sourceNotebookId:`notebook/${r.notebookSlug}`})}async function PL(e,t,n){try{return(await SL(t,{feedId:e,storage:n})).manifest}catch{return}}function FL(e,t){let n=e.label.trim();if(!n)return t?.name?.trim()||e.id;if(e.tier===`imported`&&t?.name?.trim()){let r;try{r=new URL(e.url).hostname}catch{r=``}if(n===`Source`||n===e.url||r&&n===r)return t.name.trim()}return n}var IL=`a Wod.Wiki community seed source`;function LL(e,t){let n=e.description?.trim()||void 0;if(n&&!n.includes(IL))return n;let r=t?.description?.trim()||void 0;return r&&!r.includes(IL)?r:n??r}async function RL(){let e=new Map,t=new Map,n=new Map;try{await ZP().catch(()=>void 0),await vL();let r=await YP.readonly(`meta`).getAll();for(let i of r)if(hL(i))e.set(i.feedId,i.manifest);else if(Wue(i))t.set(i.key,i);else if(gL(i)){n.set(i.key,i.index);let e=_I(i.feedId)?.url??``,t=Sx(i.notebookId)??wI(i.notebookId);for(let n of i.index.records)EL({feedId:i.feedId,feedUrl:e,notebookSlug:t,record:n})}}catch{}return{catalogs:e,checkpoints:t,indexes:n}}async function zL(){await ZP().catch(()=>void 0),await vL();let[e,t,n,{catalogs:r,checkpoints:i,indexes:a}]=await Promise.all([jI.getAllNotebooks().catch(()=>[]),YP.readonly(`notes`).getAll().catch(()=>[]),YP.readonly(`notebook_links`).getAll().catch(()=>[]),RL()]),o=new Map(t.map(e=>[e.id,e])),s=Ms(t,n,Hy),c=[],l=new Set;for(let t of e){if(t.origin!==`user`&&t.origin!=="default")continue;let e=o.get(`notebook/${t.slug}`),n=`${t.origin==="default"?`core`:`local`}#${t.slug}`;l.add(n),c.push({id:t.id,feedId:t.origin==="default"?`core`:`local`,feedLabel:t.origin==="default"?`Core`:`Yours (Local)`,chunkId:`notebook.${t.slug}`,slug:t.slug,label:t.name,description:t.description,category:t.origin,count:s.get(Cs(t.slug))??0,subscribed:!0,installed:!0,origin:t.origin,public:e?.public===!0,icon:t.icon})}for(let e of xI()){let t=r.get(e.id),n=i.get(bx(e.id)),o=FL(e,t);if(t?.notebooks&&t.notebooks.length>0)for(let r of t.notebooks){let i=Sx(r.notebookId)??wI(r.notebookId),s=`${e.id}#${i}`;if(l.has(s))continue;l.add(s);let u=n?.chunks?.[r.notebookId],d=a.get(gx(e.id,r.notebookId));c.push({id:`${e.id}:${r.notebookId}`,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.notebookId,slug:i,label:r.label,description:t.description??e.description,category:r.category,count:r.count,version:r.version,commit:r.commit,sha256:r.sha256,updatedAt:r.updatedAt,builtAt:r.builtAt,indexPath:r.indexPath,subscribed:HI(e.id,r.notebookId),installed:!!(u||d),origin:`feed`})}else if(t)for(let r of t.chunks){if(!r.id.startsWith(`notebook.`))continue;let i=Sx(r.id)??r.id.slice(9),s=`${e.id}#${i}`;if(l.has(s))continue;l.add(s);let u=n?.chunks?.[r.id],d=a.get(gx(e.id,r.id));c.push({id:`${e.id}:${r.id}`,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.id,slug:i,label:i.replace(/-/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),description:t.description??e.description,count:r.count,version:t.version,sha256:r.sha256,builtAt:t.builtAt,indexPath:`indexes/notebooks/${r.id}.json`,subscribed:HI(e.id,r.id),installed:!!(u||d),origin:`feed`})}else{let t=CI(e.id);for(let r of t){let t=wI(r.chunkId||r.id),i=`${e.id}#${t}`;if(l.has(i))continue;l.add(i);let s=n?.chunks?.[r.chunkId],u=a.get(gx(e.id,r.chunkId));c.push({id:r.id,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.chunkId,slug:t,label:r.label,description:r.description,category:r.category,count:u?.count??s?.noteIds?.length??0,indexPath:`indexes/notebooks/${r.chunkId}.json`,subscribed:HI(e.id,r.chunkId),installed:!!(s||u),origin:`feed`})}}}return c}var BL={async getAllFeeds(){let[{catalogs:e,checkpoints:t},n]=await Promise.all([RL(),Bue().catch(()=>({hasPublicContent:!1,publishedVersion:null,builtAt:null,dirty:!1,publicNotebooks:0,publicNotes:0,publicSessions:0,changes:[],mode:`self-hosted`}))]),r=[],i=n.feedUrl??(typeof window<`u`?`${window.location.origin}/feed/`:`wod-wiki-feed-repository (.zip / folder)`);r.push({id:`local`,label:`My Published Feed`,url:i,description:n.publicNotebooks>0?`Publishes ${n.publicNotebooks} public notebook(s), ${n.publicNotes} note(s), and ${n.publicSessions} opted-in session(s).`:`Mark any user-owned notebook as Public to publish via self-hosted server or export a wod-wiki-feed-repository.`,tier:`local`,subscribed:!0,installed:!0,notebookCount:n.publicNotebooks,itemCount:n.publicNotes,localVersion:n.publishedVersion??void 0,remoteVersion:n.publishedVersion??void 0,unpublishedChanges:n.dirty,builtAt:n.builtAt??void 0});let a=[mI,...xI()];for(let n of a){let i=e.get(n.id),a=t.get(bx(n.id)),o=n.id===`core`||BI(n.id),s=(a?.seedVersion??0)>0,c=CI(n.id),l=i?.notebooks?i.notebooks.length:i?i.chunks.filter(e=>e.id.startsWith(`notebook.`)).length:c.length,u=a?Object.values(a.chunks??{}).reduce((e,t)=>e+(Array.isArray(t?.noteIds)?t.noteIds.length:0),0):0,d=i?.notebooks?i.notebooks.reduce((e,t)=>e+t.count,0):i?i.chunks.reduce((e,t)=>e+t.count,0):0,f=a?.seedVersion||void 0,p=i?.version,m=!!(o&&f&&p&&p>f);r.push({id:n.id,label:FL(n,i),url:n.id===`core`?sI(oI):n.url,repositoryUrl:i?.repositoryUrl??n.repositoryUrl,description:LL(n,i),tier:n.id===`core`?`core`:n.tier??`imported`,subscribed:o,installed:s,notebookCount:l,itemCount:d||u,localVersion:f,remoteVersion:p,updateAvailable:m,builtAt:i?.builtAt??a?.builtAt})}return r},getAllNotebooks:zL,async getRemoteNotebookNotes(e,t){let n=wI(e),r=`notebook.${n}`,i=await zL(),a=t??(typeof window<`u`?new URLSearchParams(window.location.search).get(`feed`)??void 0:void 0),o=i.find(e=>e.origin===`feed`&&e.slug===n&&(!a||e.feedId===a));if(!o&&a){let e=_I(a);e?.url&&(await PL(a,e.url),o=(await zL()).find(e=>e.origin===`feed`&&e.slug===n&&e.feedId===a))}if(!o){let e=dI();for(let t of e)await PL(t.id,t.url);e.length>0&&(o=(await zL()).find(e=>e.origin===`feed`&&e.slug===n))}let s=o?.feedUrl??(a?_I(a)?.url:void 0),c=o?.feedId??a;if(!s||!c)return[];let l=o?.indexPath??`indexes/notebooks/${r}.json`,u=`${s}#${l}@${o?.sha256??`latest`}`,d=CL.get(u);if(!d){let e=await Gue(c,r);e&&(!o?.sha256||e.sha256===o.sha256)&&(d=e,CL.set(u,d))}if(!d)try{d=await tC(new OS(s),l),CL.set(u,d),await xL(c,r,d)}catch{return[]}return d.records.map(e=>{EL({feedId:c,feedUrl:s,notebookSlug:n,record:e});let t=`remote:${c}:${e.uuid}`,i=e.path.replace(/^markdown\/notebooks\/[^/]+\//,``).replace(/\.md$/i,``);return{id:t,title:AL(e),rawContent:``,sourceRevision:1,blocks:{},...e.date===void 0?{}:{date:e.date},createdAt:e.date??0,notebookId:`notebook/${n}`,sourceId:`notebook:${n}/${i}`,sourcePath:e.path,feedOrigin:`feed`,feedSourceId:c,seedOrigin:`seed`,seedChunkId:r,seedVersion:e.version,tags:[`preview:remote`]}})}};function Xue(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 Zue(e){let t=Date.now();if(!Xue(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}}}var VL=new Set;function Que(e){VL.add(e)}function HL(e){VL.delete(e)}function UL(e){return VL.has(e)}function WL(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:Fy(t)}}var GL={registeredWidgets:Ns},KL=new Map,qL=[`notes`,`block_revisions`,`note_revisions`,`schedule_items`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`notebook_links`];function JL(e){return[...e].sort((e,t)=>t.createdAt-e.createdAt)}function YL(e,t){return t==null?e:e.slice(0,t)}function XL(e){return new Date(`${e}T12:00:00`).getTime()}function ZL(e){let t=ls(e.links,e.pages),n=us(t),r=t.find(e=>e.date!==void 0)?.date,i=r===void 0?NaN:XL(r);return{id:e.note.id,title:e.note.title,slug:n.pageSlug,pageId:n.pageId,journalDate:n.journalDate??(e.note.type===`journal`&&e.note.date!==void 0?Fw(new Date(e.note.date)):void 0),placements:t,createdAt:e.note.createdAt,updatedAt:e.note.createdAt,targetDate:e.note.date??(Number.isFinite(i)?i: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,notebookId:e.note.notebookId,notebookIds:e.note.notebookIds,provenance:e.note.provenance,seedOrigin:e.note.seedOrigin,schemaVersion:1}}function QL(e){return{id:e.id,title:e.title,journalDate:e.type===`journal`&&e.date!==void 0?Fw(new Date(e.date)):void 0,createdAt:e.createdAt,updatedAt:e.createdAt,targetDate:e.date??e.createdAt,rawContent:e.rawContent,blocks:e.blocks,sourceRevision:e.sourceRevision,tags:e.tags??[],type:e.type??`note`,sourceId:e.sourceId,notebookId:e.notebookId,notebookIds:e.notebookIds,provenance:e.provenance,seedOrigin:e.seedOrigin,schemaVersion:1}}function $ue(e){if(e?.dateRange)return e.dateRange;if(e?.daysBack!=null){let t=Date.now();return{start:t-e.daysBack*864e5,end:t}}}var $L=class e{storage;contentProviderOverride;mode=`history`;capabilities={canWrite:!0,canDelete:!0,canFilter:!0,canMultiSelect:!0,supportsHistory:!0};constructor(e=X,t){this.storage=e,this.contentProviderOverride=t}get persistenceStorage(){return this.storage}get provider(){return this.contentProviderOverride??this}async createNote(e){if(await this.provider.persistenceReady,HL(e.id),await this.storage.getNote(e.id))throw Error(`Note already exists: ${e.id}`);return this.provider.saveRecord({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,...e.notebookIds===void 0?{}:{notebookIds:e.notebookIds}})}async getNote(e,t={}){await this.provider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new AT(`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.provider.getRecord(n.id);if(!o)throw new AT(`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.provider.getRecords(e);if(e.journalDate&&(t=t.filter(t=>t.placements&&t.placements.length>0?t.placements.some(t=>t.date===e.journalDate):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.offset||e.limit)&&(t=t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))),e.projection===`history-detail`&&(t=await Promise.all(t.map(e=>this.getNote(e.id,{projection:`history-detail`,resultSelection:{mode:`all-for-note`}})))),t}async mutateNote(t,n){await this.provider.persistenceReady;let r=await this.resolveNote(t);if(!r)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(t)}`);if(n.expectedSourceRevision!==void 0&&n.expectedSourceRevision!==r.sourceRevision)throw new AT(`STALE_SOURCE`,`Note ${r.id} changed since it was loaded`);let i=n.attachments?.add?await Promise.all(n.attachments.add.map(e=>Zue(e))):[];return await this.storage.withTransaction([...qL,`attachments`],async t=>{let a=new e(t);if(await a.updateRecord(r.id,{...n.metadata,rawContent:n.rawContent,blocks:n.blocks,expectedSourceRevision:n.expectedSourceRevision,results:n.workoutResult?.data,blockId:n.workoutResult?.blockId,blockVersion:n.workoutResult?.blockVersion,blockContentId:n.workoutResult?.blockContentId,origin:n.workoutResult?.origin,resultId:n.workoutResult?.id}),n.rawContent!==void 0&&n.rawContent!==r.rawContent){let e=await a.getRecord(r.id);await Zw(r.id,n.rawContent,t,{targetDate:e?.targetDate})}for(let e of i)await t.saveAttachment({...e,id:e.id??Br(),noteId:r.id,resultId:n.workoutResult?.id,createdAt:Date.now()});for(let e of n.attachments?.remove??[])await t.deleteAttachment(e)}),this.getNote(r.id,{includeAttachments:!!n.attachments})}async saveNote(e){if(await this.provider.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 AT(`STALE_SOURCE`,`Note ${e.noteId} no longer exists`);return this.provider.saveRecord({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,r){if(await this.provider.persistenceReady,n.noteId!==t.noteId)throw new AT(`RESULT_NOTE_MISMATCH`,`Session belongs to another Note`);let i=SC(t.noteId),a=i.isRemote?i.uuid:t.noteId,o=await this.storage.getNote(a)??(a===t.noteId?void 0:await this.storage.getNote(t.noteId));if(i.isRemote||o&&(!Os(o,Wy(o),Uy(o))||Ds(o,Wy(o),Uy(o)).kind!==`user`)){let e;if(!o&&i.isRemote){let n=await NL(t.noteId).catch(()=>void 0),r=DL(t.noteId);n?e={row:n,canonicalNoteId:r?.record.uuid??i.uuid,remoteNoteId:t.noteId,feedId:r?.feedId??i.feedId,notebookSlug:r?.notebookSlug,record:r?.record}:t.rawContent?.trim()&&(e={id:i.uuid,title:t.metadata?.title,rawContent:t.rawContent,blocks:t.blocks,feedSourceId:r?.feedId??i.feedId,sourceNotebookId:r?.notebookSlug?`notebook/${r.notebookSlug}`:void 0})}let r=n.sessionDate??Fw(new Date(n.createdAt||n.startTime||Date.now())),a=await FC(this.storage.storage,{noteId:o?o.id:t.noteId,blockId:n.blockId,...n.blockContentId?{blockContentId:n.blockContentId}:{},sessionId:n.id,journalDate:r,startedAt:n.startTime,...n.scheduleItemId?{scheduleItemId:n.scheduleItemId}:{},origin:n.origin,...e?{remotePayload:e}:{}});return KL.set(a.session.id,a.session),{note:a.note,revision:a.revision,session:a.session}}return this.storage.withTransaction([`notes`,`block_revisions`,`note_revisions`,`schedule_items`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`sessions`,`events`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`notebook_links`],async i=>{await new e(i).saveNote(t);let a=await i.getNote(t.noteId),o=a?.blocks[n.blockId];if(!a||!o||o.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Selected workout is not in the saved Note`);let s=await i.getBlockRevision(a.id,o.id,o.version);if(!s)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Selected workout revision is missing`);if(await i.getSessionById(n.id)||KL.has(n.id))throw Error(`Session already exists: ${n.id}`);let c=zs(s.rawContent,GL).find(e=>e.scriptBlock),l=n.sessionDate??Fw(new Date(n.createdAt||n.startTime||Date.now())),u=n.notebookIds?.length?n.notebookIds:a.notebookIds&&a.notebookIds.length>0?a.notebookIds:void 0,d={...n,blockId:o.id,blockVersion:s.version,blockContentId:c?.scriptBlock?.contentId,noteSourceRevision:n.noteSourceRevision??a.sourceRevision,sessionDate:l,status:`in-progress`,...u?{notebookIds:u}:{}};return r?.deferPersist?KL.set(d.id,d):await i.saveSession(d),{note:a,revision:s,session:d}})}async finishSession(e,t,n,r){await this.provider.persistenceReady;let i=await this.storage.withTransaction([`sessions`,`notes`,`block_revisions`,`events`,`notebook_links`,`schedule_items`],async i=>{let a=await i.getSessionById(e)??KL.get(e);if(!a&&r?.noteId&&r?.blockId){let o=SC(r.noteId),s=o.isRemote?o.uuid:r.noteId,c=await i.getNote(s)??(s===r.noteId?void 0:await i.getNote(r.noteId)),l=c?.id??s,u=c?.blocks[r.blockId],d=u?.id??r.blockId,f=r.blockVersion??u?.version,p=f===void 0?void 0:await i.getBlockRevision(l,d,f);if(p||=(await i.getBlockHistory(l,d)).reduce((e,t)=>!e||t.version>e.version?t:e,void 0),!p&&c){let e=Object.values(c.blocks).filter(e=>e.kind===`wod`);if(e.length===1){let t=e[0];p=await i.getBlockRevision(c.id,t.id,t.version)}}if(p){let i=zs(p.rawContent,GL).find(e=>e.scriptBlock),o=r.sessionDate??Fw(new Date(t.endTime||t.startTime||n||Date.now())),s=c?.notebookIds&&c.notebookIds.length>0?c.notebookIds:void 0;a={id:e,noteId:p.noteId,blockId:p.blockId,blockVersion:p.version,blockContentId:r.blockContentId??i?.scriptBlock?.contentId,noteSourceRevision:c?.sourceRevision,origin:r.origin??`journal`,...r.scheduleItemId?{scheduleItemId:r.scheduleItemId}:{},sessionDate:o,startTime:t.startTime,endTime:t.endTime,duration:t.duration??0,completed:t.completed,status:`in-progress`,createdAt:n??t.endTime??Date.now(),...s?{notebookIds:s}:{}}}}if(!a)throw new AT(`RESULT_NOT_FOUND`,`Session not found: ${e}`);if(!await i.getBlockRevision(a.noteId,a.blockId,a.blockVersion))throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision is missing`);let o=a.sessionDate??Fw(new Date(t.endTime||t.startTime||a.createdAt||Date.now())),s={...a,sessionDate:o,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??a.createdAt};if(await i.saveSession(s),s.scheduleItemId)try{let e=i.storage.readwrite(`schedule_items`),t=await e.get(s.scheduleItemId);t&&t.status!==`completed`&&await e.put({...t,status:`completed`,updatedAt:s.endTime||Date.now()})}catch{}let c=s.notebookIds??[];if(c.length>0){let e=c.map(e=>({id:`${e}:session:${s.id}`,notebookId:e,targetKind:`session`,targetId:s.id,noteId:s.noteId,createdAt:s.createdAt}));await i.storage.readwrite(`notebook_links`).putMany(e)}if(t.logs?.length){let e={noteId:s.noteId,resultId:s.id,blockId:s.blockId,blockVersion:s.blockVersion,blockContentId:s.blockContentId,origin:s.origin,pageId:s.pageId,workoutTimestamp:s.endTime};await i.appendEvents(jy(t.logs,e)),await i.finalizeSummaries(s.id,My(t.logs,e))}return s});return KL.delete(e),i}async getBlockRevision(e,t,n){return await this.provider.persistenceReady,this.storage.getBlockRevision(e,t,n)}async getBlockHistory(e,t){return await this.provider.persistenceReady,this.storage.getBlockHistory(e,t)}async getNoteBlockHistory(e){return await this.provider.persistenceReady,this.storage.getNoteBlockHistory(e)}async deleteNote(e){await this.provider.persistenceReady;let t=await this.resolveNote(e);if(!t)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);await this.provider.deleteRecord(t.id)}async getSessionById(e){return await this.provider.persistenceReady,this.storage.getSessionById(e)}async rederiveResultAnalytics(e){await this.provider.persistenceReady;let t=await this.storage.getSessionById(e);if(!t)throw new AT(`RESULT_NOT_FOUND`,`Result not found: ${e}`);let n=await this.storage.getBlockRevision(t.noteId,t.blockId,t.blockVersion),r=n&&zs(n.rawContent).find(e=>e.scriptBlock)?.scriptBlock;if(!r||n?.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Cannot re-derive result ${e}: pinned workout revision is missing`);let i={...r,results:void 0,id:t.blockId,version:t.blockVersion,dialect:n.dialect,sport:n.sport,widgetIds:{},statements:nu().read(r.content,n.sport).statements},a=this.storage.getEventsByResult?await this.storage.getEventsByResult(e):[],o=nT(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(jy(o,e)),await n.finalizeSummaries(t.id,My(o,e))})}return t}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`)),YL(JL(n),t.limit)}async selectLocalCandidateIds(e,t){let n=null,r=null,i=e=>{if(n===null){n=new Set(e);return}let t=new Set;for(let r of e)n.has(r)&&t.add(r);n=t};if(e?.journalDate&&(i(await this.storage.getNoteIdsForJournalDate(e.journalDate)),n.size===0))return{candidateIds:[],loadedNotes:r};if(e?.tags&&e.tags.length>0){for(let t of e.tags)if(i(await this.storage.getNoteIdsForTag(t)),n.size===0)return{candidateIds:[],loadedNotes:r}}if(e?.kind&&e.kind!==`note`&&n===null){let t=await this.storage.getNotesByType(e.kind);if(r=new Map(t.map(e=>[e.id,e])),i(t.map(e=>e.id)),n.size===0)return{candidateIds:[],loadedNotes:r}}if(t){let e=new Set,a=(await this.storage.getAllPages()).filter(e=>{if(!e.date)return!1;let n=XL(e.date);return Number.isFinite(n)&&n>=t.start&&n<=t.end});if(a.length>0){let t=await Promise.all(a.map(e=>this.storage.getPageNotes(e.id)));for(let n of t)for(let t of n)e.add(t.noteId)}if(n===null){let a=await this.storage.getNotesByDateRange(t.start,t.end),o=new Set(a.map(e=>e.id));for(let t of e)o.add(t);if(e.size===0&&(r=new Map(a.map(e=>[e.id,e]))),i([...o]),n.size===0)return{candidateIds:[],loadedNotes:r}}else{let a=[...n];if(!r){let e=await this.storage.getNotesByIds(a);r=new Map(e.map(e=>[e.id,e]))}let o=[];for(let n of a){let i=r.get(n);if(!i)continue;let a=i.date??i.createdAt;(a>=t.start&&a<=t.end||e.has(n))&&o.push(n)}if(i(o),n.size===0)return{candidateIds:[],loadedNotes:r}}}if(n===null){let e=await this.storage.getAllNotes();if(r=new Map(e.map(e=>[e.id,e])),i(e.map(e=>e.id)),n.size===0)return{candidateIds:[],loadedNotes:r}}let a=[...n],o=e?.search?.toLowerCase();if((e?.kind||o)&&!r){let e=await this.storage.getNotesByIds(a);r=new Map(e.map(e=>[e.id,e]))}if(r&&(e?.kind||o)){let t=[];for(let n of a){let i=r.get(n);i&&(e?.kind&&(i.type??`note`)!==e.kind||o&&!i.title.toLowerCase().includes(o)&&!i.rawContent.toLowerCase().includes(o)||t.push(n))}return{candidateIds:t,loadedNotes:r}}return{candidateIds:a,loadedNotes:r}}async getRecords(e){let t=$ue(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]});e?.kind&&e.kind!==`note`&&n.push({field:`type`,values:[e.kind]}),e?.search?.trim()&&n.push({field:`text`,value:e.search.trim()});let r=e?.projection===`history-detail`||e?.projection===`workbench`,i=!!e?.journalDate||!!e?.tags?.length||!!t,a=!r&&!i,o=e?.limit!==void 0&&!e?.journalDate&&e?.kind!==`note`&&!t&&!e?.tags?.length?(e?.offset??0)+e.limit:void 0,s={plan:a?`notes`:`detail`,...n.length?{selection:n}:{},order:[{field:`date`,direction:`desc`},{field:`createdAt`,direction:`desc`}],...o===void 0?{}:{offset:0,limit:o}},c=await this.storage.queryDomain(s),l;if(c?.plan===`detail`)l=c.rows.map(ZL);else if(c?.plan===`notes`)l=c.rows.map(QL);else{let n=await this.selectLocalCandidateIds(e,t),r=n.candidateIds,i=n.loadedNotes;if(r.length===0)return[];if(o!==void 0&&r.length>o){if(!i){let e=await this.storage.getNotesByIds(r);i=new Map(e.map(e=>[e.id,e]))}let e=i;r=[...r].sort((t,n)=>{let r=e.get(t),i=e.get(n);return(i?.date??i?.createdAt??0)-(r?.date??r?.createdAt??0)}).slice(0,o)}l=a?(i?r.map(e=>i.get(e)).filter(e=>e!==void 0):await this.storage.getNotesByIds(r)).map(QL):[...(await this.storage.getDetailBatches(r)).values()].map(ZL)}return l=l.filter(n=>(!t||n.targetDate>=t.start&&n.targetDate<=t.end)&&(e?.tags??[]).every(e=>n.tags.includes(e))),l.sort((e,t)=>t.targetDate-e.targetDate)}async getRecord(e){let t=await this.resolveStoredNote(e);if(!t)return null;let n=(await this.storage.getDetailBatches([t.id])).get(t.id);if(!n)return null;let r=ZL(n),i=(await this.storage.getSessionsForNote(t.id)).sort((e,t)=>t.createdAt-e.createdAt)[0],a=zs(t.rawContent,GL).map(e=>{let n=Object.values(t.blocks).find(t=>t.from===e.from&&t.to===e.to);return n?{...e,id:n.id,version:n.version,scriptBlock:e.scriptBlock?{...e.scriptBlock,id:n.id,version:n.version}:void 0}:e});return{...r,sections:a,results:i?WL(i,await this.storage.getEventsByResult(i.id)):void 0}}async cloneRecord(e,t){let n=await this.getRecord(e);if(!n)throw Error(`Source entry not found: ${e}`);let r=t??Date.now();return this.saveRecord({title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:r,journalDate:Fw(new Date(r)),type:`journal`,sourceId:n.id})}async saveRecord(t){let n=Date.now(),r=t.id??(t.type===`playground`?Vw(n):Br());if(!t.id&&t.type===`playground`){let e=r;for(let t=1;await this.storage.getNote(r);t++){if(t>100)throw Error(`Unable to allocate unique playground timestamp ID`);r=`${e}-${t}`}}await this.storage.withTransaction([...qL],async n=>{let i=await n.getNote(r),a=i?t.sourceRevision:0;if(a===void 0)throw new AT(`STALE_SOURCE`,`An expected source revision is required for ${r}`);let o=new e(n),s=await o.changedManualTags(r,t.tags),c=t.blocks??(i?.rawContent===t.rawContent?i.blocks:Vs(t.rawContent,{...GL,sourceRevision:a||1}));await n.saveNoteSource({noteId:r,rawContent:t.rawContent,blocks:c,expectedSourceRevision:a,createdAt:t.createdAt,metadata:{title:t.title,type:t.type,tags:s,targetDate:t.targetDate,sourceId:t.sourceId}}),await o.updateRelationships(r,{journalDate:t.journalDate,slug:t.slug}),await o.updateTags(r,t.rawContent,s);let l=await n.getNote(r);if(l){let e=t.seedOrigin??i?.seedOrigin??`user`,a=l.id.startsWith(`notebook/`)||l.id.startsWith(`effort/`)||l.id.startsWith(`equipment/`)||l.id.startsWith(`t/`);if(e===`seed`||l.feedOrigin===`feed`||a)l.seedOrigin!==e&&await n.saveNote({...l,seedOrigin:e});else{let a=t.notebookIds!==void 0||t.notebookId!==void 0,o=[...t.notebookIds??[],...t.notebookId?[t.notebookId]:[]].map(e=>e.trim()).filter(Boolean).map(e=>Cs(e)).filter(e=>!bs(e)),s=a&&t.notebookIds!==void 0?[]:(i?.notebookIds??[]).filter(Boolean).map(e=>Cs(e)).filter(e=>!bs(e)),c=Array.from(new Set([...l.type===`playground`||l.sourceId===`playground`?[`notebook/playground`]:[],...s,...o])),u=c.find(e=>e!==`notebook/playground`)??c[0],d={...l,seedOrigin:e,notebookIds:c,...u?{notebookId:u}:{notebookId:void 0}};Vx(l,d)||await n.saveNote(d);try{let e=n.storage.readwrite(`notebook_links`),i=await e.getAllFromIndex(`by-note`,r),a=new Set(c),o=new Set(i.filter(e=>e.targetKind===`note`&&e.targetId===r).map(e=>Cs(e.notebookId)));if(t.notebookIds!==void 0)for(let t of i)t.targetKind===`note`&&t.targetId===r&&!a.has(Cs(t.notebookId))&&await e.delete(t.id);let s=Date.now(),l=c.filter(e=>!o.has(e)).map(e=>({id:IS(e,`note`,r),notebookId:e,targetKind:`note`,targetId:r,noteId:r,createdAt:s}));l.length>0&&await e.putMany(l)}catch{}}}});let i=await this.getRecord(r);if(!i)throw Error(`Saved note disappeared: ${r}`);return i}async updateRecord(t,n){let r=await this.resolveStoredNote(t);if(!r)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${t}`);await this.storage.withTransaction([...qL],async t=>{let i=await t.getNote(r.id);if(!i)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${r.id}`);let a=n.rawContent??i.rawContent,o=i.id.startsWith(`remote:`)||i.retention===`indexed`||i.retention===`session-pinned`||i.retention===`cached`||i.feedOrigin===`feed`||i.upstreamStatus===`unsubscribed`||i.upstreamStatus===`removed`;if(n.rawContent!==void 0&&n.rawContent!==i.rawContent&&o){let e=Ds(i,Wy(i),Uy(i));if(!e.editable)throw Error(`Note '${i.id}' is read-only (${e.kind}) and cannot be edited directly.`)}if(n.rawContent!==void 0&&n.expectedSourceRevision===void 0)throw new AT(`STALE_SOURCE`,`An expected source revision is required for ${i.id}`);let s=n.expectedSourceRevision??i.sourceRevision,c=new e(t),l=n.tags===void 0?void 0:await c.changedManualTags(i.id,n.tags),u=n.blocks??(a===i.rawContent?i.blocks:Vs(a,{...GL,sourceRevision:s}));if(await t.saveNoteSource({noteId:i.id,rawContent:a,blocks:u,expectedSourceRevision:s,metadata:{title:n.title,type:n.type,tags:l,targetDate:n.targetDate,sourceId:n.sourceId}}),await c.updateRelationships(i.id,n),(n.tags!==void 0||a!==i.rawContent)&&await c.updateTags(i.id,a,l),n.results){if(!n.blockId||!n.blockVersion)throw Error(`Recording a result requires its frozen block pin`);let e=await t.getBlockRevision(i.id,n.blockId,n.blockVersion);if(!e||e.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision not found`);let r=n.resultId?await t.getSessionById(n.resultId):void 0;if(r&&(r.noteId!==i.id||r.blockId!==n.blockId||r.blockVersion!==n.blockVersion))throw new AT(`RESULT_NOTE_MISMATCH`,`Cannot replace a Session pin`);let a=n.results,o={...r,id:n.resultId??Br(),noteId:i.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,noteSourceRevision:r?.noteSourceRevision??i.sourceRevision,sessionDate:n.sessionDate??r?.sessionDate??Fw(new Date(a.endTime??a.startTime??r?.createdAt??Date.now())),...n.scheduleItemId??r?.scheduleItemId?{scheduleItemId:n.scheduleItemId??r?.scheduleItemId}:{},origin:n.origin??r?.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:r?.createdAt??a.endTime??Date.now()};if(await t.saveSession(o),o.scheduleItemId)try{let e=t.storage.readwrite(`schedule_items`),n=await e.get(o.scheduleItemId);n&&n.status!==`completed`&&await e.put({...n,status:`completed`,updatedAt:o.endTime||Date.now()})}catch{}if(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(jy(a.logs,e)),await t.finalizeSummaries(o.id,My(a.logs,e))}}});let i=await this.getRecord(r.id);if(!i)throw Error(`Saved note disappeared: ${r.id}`);return i}async addRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e),r=await this.resolveTargetPage(n,t);await this.storage.addNoteToPage(n,r.id);let i=await this.getRecord(n);if(!i)throw Error(`Saved note disappeared: ${n}`);return i}async removeRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e);await this.storage.removeNoteFromPage(n,t);let r=await this.getRecord(n);if(!r)throw Error(`Saved note disappeared: ${n}`);return r}async moveRecordPlacement(e,t,n){let r=await this.resolvePlacementNoteId(e),i=await this.resolveTargetPage(r,n);await this.storage.moveNoteBetweenPages(r,t,i.id);let a=await this.getRecord(r);if(!a)throw Error(`Saved note disappeared: ${r}`);return a}async getPageRecords(e){let t=await this.storage.getPageBySlug(e);if(!t)return[];let n=await this.storage.getPagePlacements(t.id);if(n.length===0)return[];let r=await this.storage.getDetailBatches(n.map(e=>e.noteId));return n.map(e=>r.get(e.noteId)).filter(e=>e!==void 0).map(ZL)}async deleteRecord(e){await this.storage.deleteNote(e)}async getAttachments(e){return this.storage.getAttachmentsForNote(e)}async saveAttachment(e,t){let n={...t,id:t.id??Br(),noteId:e,createdAt:Date.now()};return await this.storage.saveAttachment(n),n}async deleteAttachment(e){await this.storage.deleteAttachment(e)}async updateRelationships(e,t){for(let n of[`journalDate`,`slug`]){let r=t[n];if(r===void 0)continue;if(!r){for(let t of await this.storage.getNotePages(e)){let r=await this.storage.getPage(t.pageId);(n===`journalDate`?r?.date:r?.slug&&!r.date)&&await this.storage.removeNoteFromPage(e,t.pageId)}continue}let i=await this.resolvePage(e,n,r);await this.storage.addNoteToPage(e,i.id)}}async resolvePage(e,t,n){if(t===`journalDate`)return this.storage.getOrCreatePageForDate(n);let r=await this.storage.getPageBySlug(n);if(r)return r;let i={id:Br(),slug:n,title:(await this.storage.getNote(e))?.title,createdAt:Date.now()};return await this.storage.savePage(i),i}async resolveTargetPage(e,t){if(t.date)return this.storage.getOrCreatePageForDate(t.date);if(t.slug)return this.resolvePage(e,`slug`,t.slug);throw Error(`A placement target needs a date or a slug`)}async resolvePlacementNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.storage.getNote(e)??(t===e?void 0:await this.storage.getNote(t));if(!n)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async resolveStoredNote(e){let t=e.startsWith(`playground/`)?e.slice(11):e;return await this.storage.getNote(e)??(t===e?void 0:await this.storage.getNote(t))??await this.storage.getNoteBySlug(e)??(t===e?void 0:await this.storage.getNoteBySlug(t))}async changedManualTags(e,t){let n=(await this.storage.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.storage.getAllTagTypes()).map(e=>e.name),i=zs(t,GL).filter(e=>e.type===`frontmatter`).flatMap(e=>pc(e.displayContent,r)),a=n??(await this.storage.getNote(e))?.tags??[];await this.storage.setNoteTags(e,[...a,...i.map(e=>e.type?e:e.label)])}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=>Lw(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=>Lw(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 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 AT(`RESULT_NOT_FOUND`,`Result not found: ${t.resultId}`);if(r.noteId!==e.id)throw new AT(`RESULT_NOTE_MISMATCH`,`Result ${t.resultId} does not belong to note ${e.id}`);return{results:WL(r,await n(r))}}if(t.mode===`latest-for-section`||t.mode===`all-for-section`){let n=JL(await this.storage.getSessionsForSection(e.id,t.blockId));if(t.mode===`all-for-section`){let e=YL(n,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(n[0])}}let r=JL(await this.storage.getSessionsForNote(e.id));if(t.mode===`all-for-note`){let e=YL(r,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(r[0])}}async payloadOf(e){return e?WL(e,this.storage.getEventsByResult?await this.storage.getEventsByResult(e.id):[]):void 0}},eR=new $L,tR=new Map,nR=`wodwiki:pending-note-saves:v1`;function rR(){try{let e=localStorage.getItem(nR),t=e?JSON.parse(e):{};if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=r;t&&typeof t.noteId==`string`&&typeof t.rawContent==`string`&&t.blocks&&typeof t.expectedSourceRevision==`number`&&(n[e]={...t,noteId:e,stagedAt:t.stagedAt??0})}return n}catch{return{}}}function iR(e){try{Object.keys(e).length===0?localStorage.removeItem(nR):localStorage.setItem(nR,JSON.stringify(e))}catch{}}function ede(e){if(UL(e.noteId))return;let t=rR();t[e.noteId]=e,iR(t)}function aR(e){let t=rR();e in t&&(delete t[e],iR(t))}var oR=new Map;function tde(e,t){let n=oR.get(e);return n||(n=new Set,oR.set(e,n)),n.add(t),()=>{let n=oR.get(e);n&&(n.delete(t),n.size===0&&oR.delete(e))}}var sR=null;async function nde(){let e=rR();for(let t of Object.values(e)){if(UL(t.noteId)){aR(t.noteId);continue}let e=tR.get(t.noteId);if(e&&await e.then(()=>void 0,()=>void 0),UL(t.noteId)){aR(t.noteId);continue}let n=rR()[t.noteId];if(!n)continue;let r=oR.get(n.noteId);if(r&&r.size>0){let e=!1;for(let t of[...r])try{await t()&&(e=!0)}catch{e=!0}if(e)continue}let i=eR.saveNote({noteId:n.noteId,rawContent:n.rawContent,blocks:n.blocks,expectedSourceRevision:n.expectedSourceRevision,...n.metadata?{metadata:n.metadata}:{},...n.noteType?{noteType:n.noteType}:{}});tR.set(n.noteId,i);try{await i}catch{}finally{tR.get(n.noteId)===i&&tR.delete(n.noteId)}aR(n.noteId)}}function cR(){return sR??=nde().finally(()=>{sR=null}),sR}async function lR(e){let t=[...tR].filter(([t])=>t===e).map(([,e])=>e.then(()=>void 0,()=>void 0));t.length>0&&await Promise.all(t),await cR()}async function uR(){if(tR.size>0){let e=[...tR.values()].map(e=>e.then(()=>void 0,()=>void 0));await Promise.all(e)}await cR()}function dR(e,...t){console.warn(`[${e}]`,...t)}function fR(e,...t){console.error(`[${e}]`,...t)}var pR=new Set;function mR(e){return pR.add(e),()=>{pR.delete(e)}}function hR(e){for(let t of pR)try{t(e)}catch(e){fR(`resultRecorder`,`error in listener:`,e)}}function gR(e){return{async record({resultId:t,noteId:n,blockId:r,runBlock:i,blockVersion:a,blockContentId:o,data:s,createdAt:c,origin:l,scheduleItemId:u,sessionDate:d}){let f=a??(i&&`version`in i&&typeof i.version==`number`?i.version:void 0),p=o??i?.contentId,m=n&&r?{noteId:n,blockId:r,...f===void 0?{}:{blockVersion:f},...p?{blockContentId:p}:{},...l?{origin:l}:{},...u?{scheduleItemId:u}:{},...d?{sessionDate:d}:{}}:void 0,h=await e.finishSession(t,s,c,m);return wR(t),bR(t,{status:`saved`}),hR(h),h}}}var _R=gR(eR),vR=new Map,yR=new Set;function rde(){for(let e of yR)try{e()}catch(e){fR(`resultRecorder`,`error in unload state listener:`,e)}}function bR(e,t){if(t===null){if(!vR.has(e))return;vR.delete(e)}else vR.set(e,t);rde()}function ide(e){return yR.add(e),()=>{yR.delete(e)}}function ade(e){let t=e in SR(),n=vR.get(e);return n?(n.status===`pending`||n.status===`failed`)&&!t?(vR.delete(e),{status:`idle`}):n:t?{status:`pending`}:{status:`idle`}}var xR=`wodwiki:pending-halted-sessions:v1`;function ode(e){let t=e=>e instanceof Date?e:typeof e==`string`||typeof e==`number`?new Date(e):new Date,n=e=>({...e,...e.timestamp===void 0?{}:{timestamp:t(e.timestamp)},...Array.isArray(e.metrics)?{metrics:e.metrics.map(e=>e&&typeof e==`object`&&e.timestamp!==void 0?{...e,timestamp:t(e.timestamp)}:e)}:{},...e.timeSpan&&typeof e.timeSpan==`object`?{timeSpan:{...e.timeSpan,...e.timeSpan.startTime===void 0?{}:{startTime:t(e.timeSpan.startTime)},...e.timeSpan.endTime===void 0?{}:{endTime:t(e.timeSpan.endTime)}}}:{}});return{...e,...Array.isArray(e.logs)?{logs:e.logs.map(e=>n(e))}:{}}}function SR(){try{let e=localStorage.getItem(xR),t=e?JSON.parse(e):{};if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=r;t&&typeof t.resultId==`string`&&t.data&&typeof t.createdAt==`number`&&(n[e]={...t,resultId:e,data:ode(t.data)})}return n}catch{return{}}}function CR(e){try{Object.keys(e).length===0?localStorage.removeItem(xR):localStorage.setItem(xR,JSON.stringify(e))}catch{}}function sde(e){let t=SR();t[e.resultId]=e,CR(t),bR(e.resultId,{status:`pending`})}function wR(e){let t=SR();e in t&&(delete t[e],CR(t));let n=vR.get(e);n&&n.status!==`saved`&&bR(e,null)}var TR=null;function ER(e=_R){return TR??=(async()=>{let t=SR();for(let n of Object.values(t)){bR(n.resultId,{status:`flushing`});try{await e.record({resultId:n.resultId,noteId:n.noteId??``,blockId:n.blockId??``,...n.blockVersion===void 0?{}:{blockVersion:n.blockVersion},...n.blockContentId?{blockContentId:n.blockContentId}:{},data:n.data,createdAt:n.createdAt,...n.origin?{origin:n.origin}:{},...n.scheduleItemId?{scheduleItemId:n.scheduleItemId}:{},...n.sessionDate?{sessionDate:n.sessionDate}:{}}),wR(n.resultId),bR(n.resultId,{status:`saved`})}catch(e){let t=e instanceof Error?e.message:String(e);fR(`resultRecorder`,`pending unload flush failed:`,e),bR(n.resultId,{status:`failed`,error:t})}}})().finally(()=>{TR=null}),TR}typeof window<`u`&&ER();var DR=class extends $L{async getRecord(e){return await Promise.all([uR(),ER()]),super.getRecord(e)}async getRecords(e){return await Promise.all([uR(),ER()]),super.getRecords(e)}},OR={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 kR(e){return OR[e]}var AR=Object.freeze(Object.keys(OR)),jR=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)}},MR=class extends Error{sound;constructor(e){super(`Unknown sound "${e}" — it has no entry in the sound table`),this.sound=e,this.name=`UnknownSoundError`}},NR=new class{enabled;sink;constructor(e,t){if(this.sink=e??new jR,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=kR(e);if(!n)throw new MR(e);`init`in this.sink&&typeof this.sink.init==`function`&&this.sink.init(),await this.sink.playNotes(n.notes,t)}},PR=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 PR;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 PR;var FR=!0,IR=[`wodwiki.routeWql.v1`,`wodwiki.routeWqlShortcuts.v1`,`wodwiki.soundProfiles.v1`],LR=[],RR=new Map,zR={getItem:e=>RR.get(e)??null,setItem:(e,t)=>RR.set(e,t),removeItem:e=>RR.delete(e)};async function BR(){let e=await Promise.all(IR.map(e=>YP.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`)))),t=await Promise.all(LR.map(e=>YP.readonly(`meta`).get(e)));for(let t of e)for(let e of t)RR.set(e.key,e.value);for(let e of t)e&&RR.set(e.key,e.value)}async function VR(e,t){t===null?(await YP.readwrite(`meta`).delete(e),RR.delete(e)):(await YP.readwrite(`meta`).put({key:e,value:t}),RR.set(e,t))}async function HR(e){if(e.length===1)return VR(e[0],null);await YP.transaction([`meta`],`readwrite`,async t=>{for(let n of e)await t.readwrite(`meta`).delete(n)});for(let t of e)RR.delete(t)}async function UR(e){return await YP.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`))}async function WR(e,t){await YP.readwrite(`meta`).put({key:e,value:t})}async function GR(e){await YP.readwrite(`meta`).delete(e)}var KR=`wodwiki-telemetry`,qR=1,JR=`events`,YR=`wodwiki.telemetry.consent`,XR=class{events=new PR;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(YR)!==`denied`}get consent(){return this._consent}setConsent(e){if(this._consent!==e){this._consent=e;try{this.storage?.setItem(YR,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(JR,`readonly`).objectStore(JR).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(JR,`readwrite`);return a.objectStore(JR).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(KR,qR);return r.onupgradeneeded=()=>{let e=r.result;if(!e.objectStoreNames.contains(JR)){let t=e.createObjectStore(JR,{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))}},ZR;function QR(){let e=Date.now(),t=ZR===void 0?0:e-ZR;return ZR=e,t}var $R=FR?new XR({sink:e=>WR(`telemetry:${crypto.randomUUID()}`,{name:e.name,payload:e.payload,at:e.at}),load:async()=>(await UR(`telemetry:`)).map(e=>e.value).sort((e,t)=>e.at-t.at)}):new XR,ez={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 tz(){let e=(0,K.useSyncExternalStore)(e=>$R.subscribeConsent(e),()=>$R.consent);return{track:(0,K.useCallback)((e,t)=>$R.record(e,t),[]),consent:e,setConsent:(0,K.useCallback)(e=>$R.setConsent(e),[])}}var nz=[25,50,75,90];function rz(e,t=nz){let n=(0,K.useRef)(new Set);(0,K.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),$R.record(`scroll`,{percent_scrolled:r,page_path:e}))};return window.addEventListener(`scroll`,r,{passive:!0}),r(),()=>{window.removeEventListener(`scroll`,r)}},[e,t])}var iz=new class{_db;constructor(e){this._db=e}get db(){return this._db??X}async load(){let e=await this.db.getAllEquipment();return _P(this.db.storage,`equipment`,e)}async save(e){await this.db.saveEquipment(e)}async delete(e){await this.db.deleteEquipment(e)}};async function az(e){let t=await X.getAllEquipment();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),cz()}var oz=new Set;function sz(e){return oz.add(e),()=>oz.delete(e)}function cz(){for(let e of oz)e()}var lz=null;function uz(){return lz||=new xne({storage:iz}),lz}var dz=`sound-`;function fz(e){if(!e.startsWith(`sound-`))return;let t=e.slice(6);return t.length>0?t:void 0}function pz(e){let t=fz(e);return t?[{kind:`metric`,type:`sound`,value:t}]:[]}function mz(e,t=[]){let n=[],r=new Set([...xz().map(e=>e.slug),...t.map(e=>e.name.trim())]);for(let t of e){let e=t.label.trim();e.length>0&&r.add(e)}for(let t of e){let e=t.label.trim();if(e.length===0)continue;let i=t.contributions?.length?[...t.contributions]:[...pz(e)],a=t.type?.trim();a&&a!==e&&a!==`category`&&r.has(a)&&!i.some(e=>e.kind===`tag`&&e.slug===a)&&i.push({kind:`tag`,slug:a}),n.push({slug:e,...a===`category`?{isCategory:!0}:{},contributions:i})}return n}function hz(e){let t=xz(),n=new Set(t.map(e=>e.slug)),r=e.filter(e=>!n.has(e.slug)||e.contributions.length>0),i=new Set(r.map(e=>e.slug));return rs([...t.filter(e=>!i.has(e.slug)),...r])}function gz(e){return e.filter(e=>e.name.trim().length>0).map(e=>({slug:e.name.trim(),isCategory:!0,contributions:e.contributions??[]}))}async function _z(){return vz.loadTags()}var vz=new class{async loadTags(){let[e,t,n]=await Promise.all([X.getAllTags(),X.getAllTagTypes().catch(()=>[]),uS(X.storage,{notebookId:`notebook/custom`}).catch(()=>[])]),r=new Map(e.map(e=>[e.label,e])),i=new Map(t.map(e=>[e.name,e]));for(let e of n)e.kind===`tag`&&e.payload?r.set(e.slug,e.payload):e.kind===`tag-type`&&e.payload&&i.set(e.slug,e.payload);let a=[...i.values()],o=[...r.values()];return[...gz(a),...mz(o,a)]}},yz=rs(xz()),bz=new Set;function xz(){return[{slug:`tonnage`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]},{slug:`metabolic`,contributions:[{kind:`metric`,type:`met`,value:8},{kind:`metric`,type:`metMinutes`,value:`met * convert(elapsed, min)`},{kind:`metric`,type:`summaries.totalMetMinutes`,value:`sum(metMinutes)`}]},{slug:`kettlebell-24kg`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]}]}function Sz(){return yz}var Cz=null;function wz(){return Cz||=_z().then(e=>{yz=hz(e);for(let e of bz)e();return yz}).finally(()=>{Cz=null}),Cz}async function Tz(){yz=hz(await _z());for(let e of bz)e();return yz}function Ez(e){return bz.add(e),()=>bz.delete(e)}var Dz=new Map,Oz=new Map;function kz(e){Oz.set(e.runtimeId,e)}function Az(e){let t=Oz.get(e);return t&&Oz.delete(e),t}function jz(e){return Oz.get(e)}function Mz(e){for(let t of Oz.values())if(t.journalDate===e)return t}function Nz(e){Oz.delete(e)}var Pz=`wodwiki:halted-run:v1`;function Fz(){try{if(typeof window<`u`&&window.sessionStorage)return window.sessionStorage}catch{}return null}function Iz(){let e=Fz();if(!e)return null;try{let t=e.getItem(Pz);if(!t)return null;let n=JSON.parse(t);return typeof n.sessionId!=`string`||!n.sessionId||typeof n.timestamp!=`number`||!Number.isFinite(n.timestamp)?null:{sessionId:n.sessionId,...typeof n.runtimeId==`string`?{runtimeId:n.runtimeId}:{},...typeof n.noteId==`string`?{noteId:n.noteId}:{},...typeof n.workoutTitle==`string`?{workoutTitle:n.workoutTitle}:{},timestamp:n.timestamp,...typeof n.elapsedMs==`number`&&Number.isFinite(n.elapsedMs)?{elapsedMs:n.elapsedMs}:{}}}catch{return null}}function Lz(e){let t=Fz();if(t)try{t.setItem(Pz,JSON.stringify(e))}catch{}}function Rz(){let e=Fz();if(e)try{e.removeItem(Pz)}catch{}}var zz={status:`idle`,elapsedTime:0,stepCount:0,startTime:null},Bz=bt(e=>({runtime:null,activeNoteId:null,activeSessionId:null,haltedRun:Iz(),subscriptionManager:null,execution:zz,userOutputOverrides:new Map,setRuntime:(t,n=null)=>e(e=>({runtime:t,activeNoteId:n??(t?e.activeNoteId:null),...t===null?{execution:zz}:{}})),setActiveSessionMeta:(t,n=null)=>e(()=>({activeSessionId:t,activeNoteId:n})),setHaltedRun:t=>e({haltedRun:t}),setSubscriptionManager:t=>e({subscriptionManager:t}),setExecution:t=>e(e=>({execution:{...e.execution,...t}})),resetExecution:()=>e({execution:zz}),setUserOverride:(t,n)=>e(e=>{let r=new Map(e.userOutputOverrides),i=n instanceof Qo?n:Qo.from(n,t);return r.set(t,i),{userOutputOverrides:r}}),clearUserOverride:t=>e(e=>{if(!e.userOutputOverrides.has(t))return e;let n=new Map(e.userOutputOverrides);return n.delete(t),{userOutputOverrides:n}})}));function Vz(e){Lz(e),Bz.getState().setHaltedRun(e)}function Hz(e){let t=Iz()??Bz.getState().haltedRun;return!t||e&&t.noteId&&t.noteId!==e?null:t}function Uz(e){let t=Iz()??Bz.getState().haltedRun;e&&t&&t.sessionId!==e||(Rz(),Bz.getState().setHaltedRun(null))}var Wz=new WeakMap;function Gz(e,t){t&&Wz.set(e,t)}function Kz(e){return Wz.get(e)}function qz(e){let t=new Zd;return t.seed(Xd),t.seed(e.efforts),nf({efforts:t.list(),equipment:e.equipment})}function Jz(e,t){if(e.kind!==`wod`||!e.dialect)throw Error(`The saved revision is not a workout.`);let n=zs(e.rawContent).find(t=>t.type===e.dialect);if(!n?.scriptBlock)throw Error(`The saved workout fence cannot be read.`);let r=n.scriptBlock.content,i=t?.efforts===void 0?t?.referenceIndex:qz({efforts:t.efforts,equipment:t.equipment??[]}),a=t&&(!(`tags`in t)||t.tags.length>0)?t.tagIndex:Sz();return{id:e.blockId,content:r,dialect:e.dialect,sport:e.sport,statements:nu({tags:a,...i?{references:i}:{}}).read(r,e.sport).statements,startLine:0,endLine:e.rawContent.split(`
|
|
791
|
-
`).length-1,version:e.version,state:`idle`,widgetIds:{},createdAt:e.savedAt}}async function Yz(e,t,n,r,i=eR,a){let o=Date.now();Bz.getState().setActiveSessionMeta(n,e.noteId);let s=await i.startSession(e,{id:n,noteId:e.noteId,blockId:t.id,blockContentId:t.contentId,origin:r??`journal`,...a?.scheduleItemId?{scheduleItemId:a.scheduleItemId}:{},...a?.sessionDate?{sessionDate:a.sessionDate}:{},startTime:o,endTime:o,duration:0,completed:!1,status:`in-progress`,createdAt:o},a);s.note.id!==e.noteId&&Bz.getState().setActiveSessionMeta(n,s.note.id);let c=i.persistenceStorage?.storage??X.storage,l=await GS(c,s.note.id).catch(()=>[]),u=await dS(c,{note:l.length>0?{...s.note,notebookIds:l}:s.note}).catch(()=>void 0),d=!!(u&&(u.efforts.length>0||u.equipment.length>0||u.tags.length>0||u.tagTypes.length>0)),f=Jz(s.revision,d?u:void 0);return d&&u&&Gz(f,u),{...s,block:f}}async function Xz(e,t,n,r,i){let a=SC(e),o=a.isRemote?a.uuid:e,s=await X.getNote(o)??(o===e?void 0:await X.getNote(e));if(!s&&a.isRemote){let t=i?.resolveRemoteWorkout?await i.resolveRemoteWorkout(e):await NL(e).catch(()=>void 0),n=DL(e),r=t?`content`in t&&`path`in t?{row:t,canonicalNoteId:n?.record.uuid??a.uuid,remoteNoteId:e,feedId:n?.feedId??a.feedId,notebookSlug:n?.notebookSlug,record:n?.record}:t:void 0;r&&(s=(await PC(X.storage,{noteId:e,remotePayload:r})).note)}if(!s)throw Error(`The note is unavailable. Save the note before starting a workout.`);return Yz({noteId:s.id,rawContent:s.rawContent,blocks:s.blocks,expectedSourceRevision:s.sourceRevision},t,n,r,eR,{...i?.deferPersist===void 0?{}:{deferPersist:i.deferPersist},...i?.scheduleItemId?{scheduleItemId:i.scheduleItemId}:{},...i?.sessionDate?{sessionDate:i.sessionDate}:{}})}var Zz=`sound`,Qz=`wodwiki.soundProfiles.v1`,$z=`profiles`,eB=new rE(Qz,FR?zR:void 0);function tB(e){return`${dz}${e}`}function nB(e){return[{kind:`metric`,type:`sound`,value:e}]}function rB(e=eB){let t=e.get($z);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 iB(e,t=eB){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(FR){try{await VR(t.qualify($z),r)}catch(e){return console.error(`[soundProfiles] server write failed:`,e),!1}return dB(),!0}return t.set($z,n),t.getRaw($z)===r&&(dB(),!0)}var aB=Promise.resolve();async function oB(e,t=eB){let n=aB.then(async()=>iB(e(rB(t)),t));return aB=n.catch(()=>!1),n}async function sB(e,t){let n=tB(e),r=(await t.getAllTags()).find(e=>e.label===n);if(r){let n=nB(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:Zz});return}await t.putTag({id:`sound-profile-${e}`,label:n,type:Zz,contributions:nB(e),createdAt:Date.now()})}async function cB(e,t){let n=tB(e),r=(await t.getAllTags()).find(e=>e.label===n);r&&await t.deleteTag(r.id)}var lB=new Set,uB=0;function dB(){uB+=1;for(let e of lB)e()}function fB(e){return lB.add(e),()=>{lB.delete(e)}}function pB(){return uB}async function mB(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===Y.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??X,o=t.persistence??new $L(a),s=await a.getSessionById(n);if(!s||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),hR(s),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(s),`captured-no-rederive`;throw e}}async function hB(e,t={}){let{resultId:n,occurrence:r,metricType:i}=e;if(!n||!i)throw TypeError(`clearMetricCorrection: resultId and metricType are required`);let a=t.storage??X,o=t.persistence??new $L(a),s=await a.getSessionById(n);if(!s||await a.withTransaction([`events`],async e=>{let t=(await e.getEventsByResult(n)).filter(e=>e.grain===`event`&&e.outputType===`segment`&&(!r?.blockKey||e.sourceBlockKey===r.blockKey)&&(r?.sourceStatementId===void 0||e.sourceStatementId===r.sourceStatementId)&&(r?.stackLevel===void 0||e.stackLevel===r.stackLevel)&&e.metrics.some(e=>e.origin===`user`&&String(e.type).toLowerCase()===i.toLowerCase()));if(t.length===0)return`not-found`;let a=[];for(let e of t){let t=e.metrics.filter(e=>e.origin!==`user`||String(e.type).toLowerCase()!==i.toLowerCase()),n=e.timeSpan?.started??e.timestamp;a.push({...e,metrics:t,...e.metricTemporal?{metricTemporal:t.map(()=>({temporalKind:`instant`,instant:n}))}:{}})}return await e.appendEvents(a),`captured`})===`not-found`)return`not-found`;try{return await o.rederiveResultAnalytics(n),hR(s),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(s),`captured-no-rederive`;throw e}}async function gB(e,t,n={}){let r=n.storage??X,i=n.persistence??new $L(r),a=await r.getSessionById(e);if(!a)return`not-found`;let o=(r.getEventsByResult?await r.getEventsByResult(e):[]).filter(e=>e.grain===`event`&&e.metrics.some(e=>e.type===Y.SessionRPE&&e.origin===`user`));o.length>0&&r.deleteEvents&&await r.deleteEvents(o.map(e=>e.id));let s=r.getEventsByResult?await r.getEventsByResult(e):[],c=`session`,l=0,u=s.filter(e=>e.outputType===`segment`);if(u.length>0){let e=u[u.length-1];c=e.sourceBlockKey??`session`,l=e.stackLevel??0}let d=a.endTime??a.startTime??Date.now(),f={id:`${e}:rpe:${Date.now()}`,resultId:e,noteId:a.noteId,blockId:a.blockId,blockVersion:a.blockVersion,blockContentId:a.blockContentId,pageId:a.pageId,origin:`user`,timestamp:d,grain:`event`,outputType:`segment`,metrics:[{type:Y.SessionRPE,value:t,origin:`user`,image:`rpe: ${t}`}],sourceBlockKey:c,stackLevel:l};r.appendEvents&&await r.appendEvents([f]);try{return await i.rederiveResultAnalytics(e),hR(a),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(a),`captured-no-rederive`;throw e}}var _B=null,vB=new Set;function yB(e){_B!==e&&(_B=e,vB.forEach(e=>e(_B)))}function bB(){return _B}function xB(e){return vB.add(e),()=>{vB.delete(e)}}var SB=(0,K.createContext)({transport:null});function CB(){let e=(0,K.useContext)(SB),[t,n]=K.useState(()=>bB());return K.useEffect(()=>xB(n),[]),e.transport??t}var wB=({children:e,transport:t})=>{let n=(0,K.useMemo)(()=>({transport:t}),[t]);return(0,q.jsx)(SB.Provider,{value:n,children:e})},TB=(0,K.createContext)(void 0);function EB({children:e,audioAdapter:t=NR}){let[n,r]=(0,K.useState)(t.isEnabled()),i=CB();(0,K.useEffect)(()=>{t.setEnabled(n)},[n,t]);let a=(0,K.useCallback)((e,r=1)=>{if(n){if(i?.connected){console.log(`[AudioContext] Routing sound '${e}' to cast receiver`);try{i.send({type:`rpc-audio`,name:e,volume:r})}catch(n){console.error(`[AudioContext] Failed to send rpc-audio`,n),t.playSound(e,r).catch(DB)}}else t.playSound(e,r).catch(DB)}},[n,i,t]),o=(0,K.useCallback)(()=>{let e=!n;r(e),e&&(t.setEnabled(!0),t.playSound(`beep`).catch(DB))},[n,t]),s=(0,K.useCallback)(()=>{a(`chime`)},[a]),c=(0,K.useCallback)(()=>{a(`click`,.5)},[a]),l=(0,K.useMemo)(()=>({isEnabled:n,toggleAudio:o,playTestSound:s,playSound:a,playClick:c}),[n,o,s,a,c]);return(0,q.jsx)(TB.Provider,{value:l,children:e})}function DB(e){console.error(`[AudioContext] Sound playback failed`,e)}function OB(){let e=(0,K.useContext)(TB);if(e===void 0)throw Error(`useAudio must be used within an AudioProvider`);return e}function kB(){return(0,K.useContext)(TB)}var AB=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},jB=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 AB(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return rS(await e.json())}resolveTargetUrl(e){if(/^https?:\/\//i.test(e)){let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password)throw new AB(`Disallowed feed resource URL`);return t.toString()}let t=e.replace(/^\/+/,``);return`${this.baseUrl}${t}`}async fetchChunk(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new AB(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}async fetchText(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new AB(`feed text fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.text()}},MB={core:1};function NB(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function PB(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}var FB=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=rS(e.manifest??await this.source.fetchManifest()),n=bx(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??xx(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=new Set(t.chunks.map(e=>e.id)),s=[...t.chunks,...(t.notebooks??[]).filter(e=>!o.has(e.notebookId)).map(e=>({id:e.notebookId,path:e.indexPath,sha256:e.sha256,bytes:e.bytes,count:e.count}))],c=s.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),l=!!(t.notebooks&&t.notebooks.length>0),u=c.filter(n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),i=a.chunks[n.id];if(e.forceAll||!i)return!0;if(r){if((r.version??0)>(i.version??0))return!0}else if(!l&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});u.sort((e,t)=>Number(t.id===yx)-Number(e.id===yx));let d=Object.keys(a.chunks).filter(e=>!s.some(t=>t.id===e)),f={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!u.length&&!d.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return f;f.status=`imported`;let p=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:f.appliedChunks,totalChunks:u.length,totalNotes:f.totalNotes,totalEfforts:f.totalEfforts,totalEquipment:f.totalEquipment,totalBlocks:f.totalBlocks,skippedUserOwned:f.skippedUserOwned,deleted:f.deleted,preservedPinned:f.preservedPinned,addedNotes:f.addedNotes,updatedNotes:f.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}}),m=e=>{f.totalNotes+=e.totalNotes,f.totalEfforts+=e.totalEfforts,f.totalEquipment+=e.totalEquipment,f.totalBlocks+=e.totalBlocks,f.skippedUserOwned+=e.skippedUserOwned,f.deleted+=e.deleted,f.preservedPinned=(f.preservedPinned??0)+(e.preservedPinned??0),f.addedNotes+=e.addedNotes,f.updatedNotes+=e.updatedNotes},h=(e,n,r)=>({...a,seedVersion:t.version,builtAt:t.builtAt,chunks:{...a.chunks,[e.id]:{sha256:e.sha256,version:n?.version,builtAt:n?.builtAt??t.builtAt,importedAt:this.now(),noteIds:r}},importedAt:this.now()}),g=0;if(u[0]?.id===`canvas`){let n=u[0],r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:s,noteIds:c}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id)),l=h(n,r,c);p(`applying`,n.id),m(await this.storage.applyChunk({chunkId:n.id,rows:s,manifest:t,expectedMeta:i,meta:l})),f.appliedChunks++,a=l,i=l,p(`committed`,n.id),e.onFirstPaintApplied?.(),g=1}let _=[];for(let n=g;n<u.length;n+=4){let r=u.slice(n,n+4),i=await Promise.all(r.map(async n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:i,noteIds:s}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id));return{chunk:n,notebook:r,rows:i,noteIds:s}}));_.push(...i)}let v=[];for(let e of _){let n=h(e.chunk,e.notebook,e.noteIds);v.push({chunkId:e.chunk.id,rows:e.rows,manifest:t,expectedMeta:i,meta:n}),a=n,i=n}for(let e of d){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()};v.push({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r}),a=r,i=r}let y={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};if(v.push({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:y}),v.length>0){if(_.length>0&&p(`applying`,_[0].chunk.id),this.storage.applyChunks){m(await this.storage.applyChunks(v)),f.appliedChunks+=_.length;for(let e of _)p(`committed`,e.chunk.id)}else for(let e of v)m(await this.storage.applyChunk(e)),e.chunkId&&_.some(t=>t.chunk.id===e.chunkId)&&(f.appliedChunks++,p(`committed`,e.chunkId))}return p(`finalizing`,null),f}async fetchSingleRecordRow(e){if(e.recordPath)try{let t=await this.source.fetchChunk(e.recordPath);return Array.isArray(t)?aS(t):[oS(t)]}catch(t){if(!e.rawUrl&&!/\.md$/i.test(e.path))throw t}let t=e.rawUrl??e.path,n=this.source.fetchText?await this.source.fetchText(t):String(await this.source.fetchChunk(t));return[await $S({path:e.path,markdown:n,uuid:e.uuid,commit:e.commit,version:e.version,title:e.title,date:e.date})]}async fetchChunkData(e,t,n,r,i,a){let o,s=e.records,c=!!(n.chunks[e.id]&&r.granularRecords&&(t?.indexPath||e.records));if(!a||c||r.granularRecords&&e.records&&e.records.length>0){if(t?.indexPath&&(s=iS(await this.source.fetchChunk(t.indexPath)).records),s&&s.length>0){let t=!r.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,n=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(a&&c&&n.length>s.length/2){if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else{let t=[];for(let r=0;r<n.length;r+=8){let a=n.slice(r,r+8);i(`fetching`,e.id,a[0]?.uuid,r,n.length);let o=await Promise.all(a.map(e=>this.fetchSingleRecordRow(e)));for(let e of o)t.push(...e)}o=t}}else if(a){if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else o=[]}else if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(o.map(e=>fS(e.path)));return{rows:o,noteIds:l}}},IB=45e3;function LB(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 RB(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function zB(e,t){if(e.offlinePolicy)return e.offlinePolicy;if(e.id===`core`)return`offline-full`;try{let n=(await t.getMeta?.(oC))?.entries?.[e.id]?.offlinePolicy;if(n===`index-only`||n===`offline-full`)return n}catch{}return`index-only`}async function BB(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=bx(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);s.hadCheckpoint=(c?.seedVersion??0)>0;let l=await zB(e,r);if(l===`offline-full`&&!t.force&&!t.probeManifests&&PB(c,e.embeddedVersion))return s.outcome=`current`,s;if(RB(c,i,a()))return s.outcome=`busy`,s;let u=rS(await e.source.fetchManifest());s.manifestChecked=!0,s.manifest=u,await r.putMeta?.({key:`catalog:${e.id}`,feedId:e.id,manifest:u,updatedAt:a()}).catch(()=>void 0);let d=Array.isArray(u.notebooks)&&u.notebooks.length>0;if(l===`index-only`&&d){let n=u.notebooks.filter(t=>e.notebookIds!==void 0&&e.notebookIds!==null?e.notebookIds.length!==0&&e.notebookIds.includes(t.notebookId):!0),i=await Promise.all(n.map(t=>r.getMeta?.(gx(e.id,t.notebookId)).catch(()=>void 0)));if(t.background&&!e.autoSyncOn)return s.outcome=n.some((e,t)=>{let n=i[t];return!n?.index||e.version>(n.index.version??0)||!!(e.sha256&&n.index.sha256!==e.sha256)})?`update-pending`:`current`,s;let o=!1,c=0;for(let[s,l]of n.entries()){let n=i[s];if(!(t.force===!0||!n?.index||l.version>(n.index.version??0)||l.sha256&&n.index.sha256!==l.sha256))continue;let u=iS(await e.source.fetchChunk(l.indexPath));await r.putMeta?.({key:gx(e.id,l.notebookId),feedId:e.id,notebookId:l.notebookId,index:u,updatedAt:a()});let d=new Set(u.records.map(e=>e.uuid)),f=await r.reconcileRemovedRecords?.(e.id,l.notebookId,d);c+=f?.preservedPinned??0,o=!0}return s.outcome=o?`imported`:`current`,o&&(s.applied=!0,s.importedVersion=u.version,s.added=0,s.updated=0),c>0&&(s.preservedPinned=c),s}let f=t.force?`import`:NB(c?.seedVersion,u.version);if(f===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);let p=u.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`)));if(t.background&&!e.autoSyncOn)return s.outcome=p.some(e=>{let t=u.notebooks?.find(t=>t.notebookId===e.id),n=c?.chunks[e.id];return!n||t&&(t.version??0)>(n.version??0)?!0:n.sha256!==e.sha256})?`update-pending`:`current`,s;let m=!!(c&&Object.keys(c.chunks).length>0),h=!m||p.every(e=>c?.chunks[e.id]?.sha256===e.sha256),g=m&&Object.keys(c.chunks).some(e=>!u.chunks.some(t=>t.id===e));if(!t.force&&f===`current`&&c?.schema===9&&c.builtAt===u.builtAt&&h&&!g)return s.outcome=`current`,s;let _={...c??xx(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(_,c??null);try{let i=await new FB(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:!t.force&&!!(e.granularRecords&&m),manifest:u,stored:_});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=u.version,s.added=i.addedNotes,s.updated=i.updatedNotes,i.preservedPinned&&(s.preservedPinned=i.preservedPinned))}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(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=LB(t),s}}function VB(){try{return typeof localStorage<`u`&&localStorage.getItem(`wodwiki.seedImport.enabled`)!==`0`}catch{return!1}}function HB(){let e=new Set(Sue()),t=sI(oI);return[{id:`core`,label:`Core`,source:new jB(t),url:t,embeddedVersion:MB.core??0},...gI.map(e=>({id:e.id,label:e.label,source:new jB(e.url),url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},embeddedVersion:0,autoImport:e.autoImport??!1,tier:e.tier,...e.description?{description:e.description}:{}})),...dI().map(e=>({id:e.id,label:e.label,source:new jB(e.url),url:e.url,repositoryUrl:e.repositoryUrl,embeddedVersion:MB[e.id]??0,autoImport:!1}))].filter(t=>!e.has(t.id))}function UB(e){try{if(typeof BroadcastChannel<`u`){let t=new BroadcastChannel(mx);t.postMessage(e),t.close()}}catch{}}async function WB(){BP(),await Tz().catch(()=>{});let e=SP();e.isInitialized()&&await vP(e);let t=uz();t.isInitialized()&&await az(t)}function GB(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`}async function KB(e,t,n,r){let i=n.now??Date.now,a=n.broadcast??UB,o=n.reportActivity!==!1;if(t.manifestChecked&&nV(e.id,i()),t.manifest&&await yL(e.id,t.manifest,n.storage?.storageInstance).catch(()=>void 0),t.outcome===`error`){let i=t.error??`feed sync failed`;n.mode===`background`&&r?.set(e.id,{sourceId:e.id,label:e.label,state:`error`}),o&&TE(i);return}t.outcome===`imported`&&t.applied&&(a({kind:`seed-imported`,source:e.id,version:t.importedVersion}),await WB().catch(()=>void 0),o&&CE({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 qB(){return typeof Worker<`u`&&!1}async function JB(e,t,n){return new Promise(r=>{let i;try{i=new Worker(new URL(`/assets/feedSync.worker-3JQ9JWGx.js`,``+import.meta.url),{type:`module`})}catch(e){console.warn(`[feedSync] seed worker unavailable; running on main thread`,e),r(null);return}let a=t.mode===`background`?new Map:void 0,o=[],s=[],c=e.length,l=!1,u=e=>{wE(null),i.terminate(),r(e)};i.onerror=e=>{console.warn(`[feedSync] feed worker failed`,e.message??`unknown error`),u(l?GB(o):null)},i.onmessage=n=>{l=!0;let r=n.data;if(r.type===`progress`){let n=e.find(e=>e.id===r.sourceId);wE({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}),r.progress.phase===`committed`&&(r.progress.chunkId===`efforts`||r.progress.chunkId===`equipment`)&&s.push(WB().catch(()=>void 0)),t.onProgress?.({...r.progress,sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,sourceIndex:e.indexOf(n)+1,totalSources:c});return}if(r.type===`first-paint`){s.push(WB().catch(()=>void 0)),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),s.push(KB(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:c});return}Promise.allSettled(s).then(()=>{a&&eV([...a.values()]),u(GB(r.outcomes.length?r.outcomes:o))})},i.postMessage({type:`run`,dbName:Wle(),userId:qP.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:sI(e.url),...e.tier?{tier:e.tier}:{},embeddedVersion:e.embeddedVersion,autoSyncOn:qI(e.id),notebookIds:t.notebookIds===void 0?zI(e.id)===`partial`?WI(e.id)??void 0:t.mode===`background`&&zI(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0,offlinePolicy:t.offlinePolicy??YI(e.id)}))})})}var YB=null,XB=0,ZB=new Set;function QB(){return YB}function $B(e){return ZB.add(e),()=>{ZB.delete(e)}}function eV(e){YB=e.length?{id:++XB,updates:e}:null;for(let e of ZB)e()}function tV(e){YB?.updates.some(t=>t.sourceId===e)&&eV(YB.updates.filter(t=>t.sourceId!==e))}function nV(e,t){fue(e,t)}function rV(e){return pue(e)}async function iV(e={}){let t=[],n=e.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=e.mode===`background`?new Map:void 0;if(!(e.isEnabled??VB)())return`disabled`;let i=e.owner??`seed-${(e.now??Date.now)()}-${Math.random().toString(36).slice(2,8)}`,a=e.sources??HB();if(!e.storage&&!e.now&&qB()){let t=await JB(a,e,i);if(t)return t}for(let[o,s]of a.entries()){let c=await oV(s,e,n,i,o+1,a.length,r);console.debug(`[feedSync] ${s.id} outcome: ${c}`),t.push(c)}return r&&eV([...r.values()]),GB(t)}async function aV(e={}){let t=e.sources??HB(),n=e.storage??NI();await yV({storage:n}).catch(e=>console.warn(`[feedSync] core registry migration failed`,e));let r;try{r=await n.getSeedMeta(bx(`core`))}catch(e){return console.warn(`[feedSync] boot provider probe failed`,e),`error`}if(!r||r.seedVersion<=0)return iV({...e,sources:t.filter(e=>e.autoImport!==!1)});let i=t.filter(e=>e.id===`core`||zI(e.id)!==`unsubscribed`);return iV({...e,sources:i,probeManifests:!0,mode:`background`,reportActivity:!1})}async function oV(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?SE(`download`,e.label):()=>{};try{let l=await BB({id:e.id,label:e.label,source:e.source,embeddedVersion:e.embeddedVersion,autoSyncOn:qI(e.id),...e.tier?{tier:e.tier}:{},notebookIds:t.notebookIds===void 0?zI(e.id)===`partial`?WI(e.id)??void 0:t.mode===`background`&&zI(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0,offlinePolicy:t.offlinePolicy??YI(e.id)},{storage:n,owner:r,now:s,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`},{onProgress:t=>{wE({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}),t.phase===`committed`&&(t.chunkId===`efforts`||t.chunkId===`equipment`)&&WB(),c?.({...t,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a})},onFirstPaint:()=>{BP(),t.onFirstPaint?.()}});return await KB(e,l,t,o),u(l.outcome,l.error),l.outcome}finally{wE(null),d()}}async function sV(e,t={}){let n=(t.sources??HB()).find(t=>t.id===e);if(!n)return console.warn(`[feedSync] unknown feed source: ${e}`),`error`;let r=await iV({...t,sources:[n]});return(r===`imported`||r===`current`)&&(t.subscribe===!1?BI(e)||VI(e,!1):!t.preserveSubscriptionState&&!t.notebookIds&&(VI(e,!0),t.offlinePolicy&&XI(e,t.offlinePolicy)),await JF(),tV(e)),r}async function cV(e,t={}){let n=t.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=t.offlinePolicy??(e===`core`?`offline-full`:`index-only`);return VI(e,!0),XI(e,r),t.autoSync!==void 0&&JI(e,t.autoSync),await JF(),sV(e,{...t,offlinePolicy:r,subscribe:!0,...t.notebookIds?{preserveSubscriptionState:!0}:{}})}async function lV(e,t,n={}){let r=n.storage??NI();return r.storageInstance&&!FF()&&await ZF(r.storageInstance).catch(()=>void 0),XI(e,`offline-full`),!t?.length&&!BI(e)&&VI(e,!0),await JF(),sV(e,{...n,offlinePolicy:`offline-full`,notebookIds:t,preserveSubscriptionState:!!t?.length})}async function uV(e,t,n,r={}){let i=r.storage??NI();if(i.storageInstance&&!FF()&&await ZF(i.storageInstance).catch(()=>void 0),n){UI(e,t,!0),await JF();let n=r.offlinePolicy??YI(e);return{outcome:await sV(e,{...r,offlinePolicy:n,notebookIds:[t],preserveSubscriptionState:!0,force:n===`offline-full`||r.force})}}{UI(e,t,!1),await JF(),await i.deleteMeta?.(gx(e,t)).catch(()=>void 0);let n=await i.getSeedMeta(bx(e));if(!n||!n.chunks[t]){let n=await i.removeNotebookContent?.(e,t)??{deleted:0,preservedPinned:0};if(n.deleted>0||n.preservedPinned>0){BP();let t=SP();t.isInitialized()&&await vP(t);let n=uz();n.isInitialized()&&await az(n),UB({kind:`seed-removed`,source:e})}return{deleted:n.deleted,preservedPinned:n.preservedPinned}}let r={...n.chunks};if(delete r[t],Object.keys(r).length===0){let t=await i.removeSourceContent(n);BP();let r=SP();r.isInitialized()&&await vP(r);let a=uz();return a.isInitialized()&&await az(a),UB({kind:`seed-removed`,source:e}),{deleted:t.deleted,preservedPinned:t.preservedPinned}}let a={...n,chunks:r,importedAt:Date.now()},o={schema:9,version:n.seedVersion,builtAt:n.builtAt,chunks:[]},s=await i.applyChunk({chunkId:t,rows:[],manifest:o,expectedMeta:n,meta:a}),c=await i.removeNotebookContent?.(e,t)??{deleted:0,preservedPinned:0};BP();let l=SP();l.isInitialized()&&await vP(l);let u=uz();return u.isInitialized()&&await az(u),UB({kind:`seed-removed`,source:e}),{deleted:s.deleted+c.deleted,preservedPinned:(s.preservedPinned??0)+c.preservedPinned}}}async function dV(e,t={}){if(e===`core`)return{deleted:0,preservedPinned:0};let n=t.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=await n.getSeedMeta(bx(e)),i=n.removeSourceContentById?await n.removeSourceContentById(e):r?await n.removeSourceContent(r):{deleted:0,preservedPinned:0};VI(e,!1),JI(e,!1),await JF(),tV(e),BP();let a=SP();a.isInitialized()&&await vP(a);let o=uz();return o.isInitialized()&&await az(o),UB({kind:`seed-removed`,source:e}),{deleted:i.deleted,preservedPinned:i.preservedPinned}}async function fV(e,t={}){if(e===`core`)return{deleted:0,preservedPinned:0};let n=t.storage??NI(),r=await dV(e,t);return await n.deleteMeta?.(`catalog:${e}`).catch(()=>void 0),dI().some(t=>t.id===e)?yue(e):xue(e),await JF(),r}async function pV(e={}){let t=e.storage??NI(),n=!1,r=!1;return await Promise.all((e.sources??HB()).map(async e=>{try{let i=await t.getSeedMeta(bx(e.id));if(!i||i.seedVersion<=0)return;e.autoImport===!1?r=!0:n=!0}catch{}})),{coreImported:n,libraryImported:r}}async function mV(e={}){let t=e.storage??NI();t.storageInstance&&!FF()&&await ZF(t.storageInstance).catch(()=>void 0);let n=e.probe===!0,r=await Promise.all((e.sources??HB()).map(async r=>{let i=await t.getSeedMeta(bx(r.id)),a=null,o=null,s=null,c=r.repositoryUrl,l=await bL(r.id,t.storageInstance);if(l&&(s=l,a={version:s.version,schema:s.schema,builtAt:s.builtAt},c??=aI(s.repositoryUrl??``)??void 0),n)try{s=rS(await r.source.fetchManifest()),a={version:s.version,schema:s.schema,builtAt:s.builtAt},c??=aI(s.repositoryUrl??``)??void 0,await yL(r.id,s,t.storageInstance),nV(r.id,(e.now??Date.now)()),o=null}catch(e){o=e instanceof Error?e.message:String(e)}let u=hV(r.id,s,i),d=s?.indexBytes??u.reduce((e,t)=>e+(t.indexBytes??0),0),f=s?.chunks,p=s?.chunkBytes??(f?.length?f.reduce((e,t)=>e+(t.bytes??0),0):u.reduce((e,t)=>e+(t.chunkBytes??0),0));return{id:r.id,label:r.label,url:r.url,...c?{repositoryUrl:c}:{},...r.description?{description:r.description}:{},autoImport:r.autoImport!==!1,notebooks:u,stored:i?{version:i.seedVersion,schema:i.schema,builtAt:i.builtAt,importedAt:i.importedAt}:null,remote:a,remoteError:o,upToDate:i!=null&&a!=null&&i.schema===9&&i.seedVersion===a.version,count:u.reduce((e,t)=>e+t.count,0),bytes:u.reduce((e,t)=>e+t.bytes,0),indexBytes:d,chunkBytes:p,hasOfflineChunks:(s?.chunks?.length??0)>0||p>0,offlinePolicy:YI(r.id),checkedAt:rV(r.id),subscribed:BI(r.id),autoSync:qI(r.id)}}));return n&&await JF(),{sources:r}}function hV(e,t,n){let r={};for(let t of CI(e))r[t.chunkId]=t;if(t?.notebooks&&t.notebooks.length>0)return t.notebooks.map(i=>{let a=t.chunks.find(e=>e.id===i.notebookId),o=i.chunkBytes??a?.bytes;return{id:r[i.notebookId]?.id??i.notebookId,label:i.label||r[i.notebookId]?.label||i.notebookId,chunkId:i.notebookId,count:i.count,bytes:i.bytes,...i.indexBytes===void 0?{}:{indexBytes:i.indexBytes},...o===void 0?{}:{chunkBytes:o},imported:!!n?.chunks[i.notebookId],subscribed:HI(e,i.notebookId)}});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,chunkBytes:t.bytes,imported:!!n?.chunks[t.id],subscribed:HI(e,t.id)}));return i.length>0?i:CI(e).map(t=>({id:t.id,label:t.label,chunkId:t.chunkId,count:0,bytes:0,imported:!!n?.chunks[t.chunkId],subscribed:HI(e,t.chunkId)}))}async function gV(e={}){let t=e.storage??NI(),n=0;for(let e of gI){let r=bx(e.id);try{let i=await t.getSeedMeta(r);if(i&&i.seedVersion>0)continue;let a=[];for(let n of CI(e.id)){if(n.id===e.id)continue;let r=await t.getSeedMeta(bx(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(`[feedSync] legacy checkpoint adoption failed for ${e.id}`,t)}}return n}async function _V(e={}){return(e.storage??NI()).backfillFeedProvenance()}async function vV(e={}){return(e.storage??NI()).migrateNotebookVocabulary()}async function yV(e={}){let t=e.storage??NI(),n=bx(`seed-core`),r=await t.getSeedMeta(n),i=r?.chunks??{};if(!r||r.seedVersion<=0&&Object.keys(i).length===0&&!r.claim)return!1;let a=bx(`core`),o=await t.getSeedMeta(a),s={...o?.chunks};for(let[e,t]of Object.entries(i)){let n=s[e];s[e]=n?{sha256:n.sha256,noteIds:[...new Set([...n.noteIds??[],...t.noteIds??[]])]}:{...t,noteIds:t.noteIds??[]}}let c=o?{...o,builtAt:``,claim:null,chunks:s}:{...xx(a),chunks:s};return await t.putSeedMeta(c,o??null),await t.putSeedMeta(xx(n),r),!0}var bV=(0,K.createContext)(null);function xV({children:e}){let t=K.useRef(!0);(0,K.useEffect)(()=>(t.current=!0,()=>{t.current=!1}),[]);let[{isReady:n,error:r,revision:i},a]=(0,K.useState)({isReady:!1,error:null,revision:0}),o=SP(),s=(0,K.useCallback)(async()=>{try{if(await vP(o),!t.current||typeof window>`u`)return;a(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){if(!t.current||typeof window>`u`)return;a(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[o]),c=(0,K.useCallback)(async()=>{await s()},[s]);return(0,K.useEffect)(()=>{s()},[s]),(0,K.useEffect)(()=>bP(()=>{a(e=>({isReady:!0,error:null,revision:e.revision+1}))}),[]),(0,K.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(mx);return e.onmessage=()=>{c()},()=>e.close()},[c]),(0,q.jsx)(bV.Provider,{value:{registry:o,isReady:n,error:r,revision:i,refresh:c},children:e})}function SV(){return(0,K.useContext)(bV)}function CV(){let e=(0,K.useContext)(bV);if(!e)throw Error(`useEffortRegistry must be within EffortRegistryProvider`);return e}var wV=(0,K.createContext)(null);function TV({children:e}){let t=K.useRef(!0);(0,K.useEffect)(()=>(t.current=!0,()=>{t.current=!1}),[]);let[{isReady:n,error:r,revision:i},a]=(0,K.useState)({isReady:!1,error:null,revision:0}),o=uz(),s=(0,K.useCallback)(async()=>{try{if(await az(o),!t.current||typeof window>`u`)return;a(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){if(!t.current||typeof window>`u`)return;a(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[o]),c=(0,K.useCallback)(async()=>{await s()},[s]);return(0,K.useEffect)(()=>{s()},[s]),(0,K.useEffect)(()=>sz(()=>{a(e=>({isReady:!0,error:null,revision:e.revision+1}))}),[]),(0,K.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(mx);return e.onmessage=()=>{c()},()=>e.close()},[c]),(0,q.jsx)(wV.Provider,{value:{registry:o,isReady:n,error:r,revision:i,refresh:c},children:e})}function EV(){return(0,K.useContext)(wV)}function DV(){let e=(0,K.useContext)(wV);if(!e)throw Error(`useEquipmentRegistry must be within EquipmentRegistryProvider`);return e}var OV={activeL1Id:null,activeL2Id:null,activeL3Id:null,leftDrawerOpen:!1,rightDrawerOpen:!1,inspectorDrawerOpen:!1,peekTarget:null,expandedIds:new Set,journalFilter:{selectedDate:null,selectedTags:[]},searchFilter:{scope:`all`}};function kV(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 t.open?e.rightDrawerOpen&&!e.inspectorDrawerOpen&&(e.peekTarget??null)===null?e:{...e,rightDrawerOpen:!0,inspectorDrawerOpen:!1,peekTarget:null}:e.rightDrawerOpen?{...e,rightDrawerOpen:!1}:e;case`SET_INSPECTOR_DRAWER`:return t.open?e.inspectorDrawerOpen&&!e.rightDrawerOpen&&(e.peekTarget??null)===null?e:{...e,inspectorDrawerOpen:!0,rightDrawerOpen:!1,peekTarget:null}:!e.inspectorDrawerOpen&&(e.peekTarget??null)===null?e:{...e,inspectorDrawerOpen:!1,peekTarget:null};case`OPEN_PEEK`:return e.peekTarget===t.target&&e.inspectorDrawerOpen&&!e.rightDrawerOpen?e:{...e,peekTarget:t.target,inspectorDrawerOpen:!0,rightDrawerOpen:!1};case`CLOSE_PEEK`:return(e.peekTarget??null)===null?e:{...e,peekTarget:null,inspectorDrawerOpen:!1};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 AV=e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-80;window.scrollTo({top:e,behavior:`smooth`})}},jV={tree:[],navState:OV,dispatch:()=>{},peekTarget:null,openPeek:()=>{},closePeek:()=>{},l3Items:[],setL3Items:()=>{},l3Connections:void 0,setL3Connections:()=>{},l3Actions:[],setL3Actions:()=>{},secondarySpec:void 0,setSecondarySpec:()=>{},contextNav:void 0,setContextNav:()=>{},streamControls:null,setStreamControls:()=>{},analyticsControls:null,setAnalyticsControls:()=>{},scrollToSection:AV,registerScrollFn:()=>{},openCreateJournal:()=>{},registerCreateJournal:()=>{}},MV=(0,K.createContext)(jV);function NV(){return(0,K.useContext)(MV)}function PV(){let e=(0,K.useContext)(MV);return e===jV?null:e}function FV(e){let{tree:t,dispatch:n}=NV();(0,K.useEffect)(()=>{e&&t.some(t=>t.id===e)&&n({type:`SET_ACTIVE_L1`,id:e})},[e,t,n])}function IV(e,t){return e===t?!0:e.kind!==t.kind||e.id!==t.id?!1:e.kind===`link`&&t.kind===`link`?e.label===t.label&&e.to===t.to&&e.sectionId===t.sectionId&&e.onSelect===t.onSelect&&e.onRun===t.onRun&&e.runIcon===t.runIcon&&e.filterTo===t.filterTo&&e.filterLabel===t.filterLabel&&e.timestamp===t.timestamp&&e.badge===t.badge&&e.muted===t.muted&&e.icon===t.icon:e.kind===`section`&&t.kind===`section`?e.label===t.label&&e.entries.length===t.entries.length&&e.entries.every((e,n)=>IV(e,t.entries[n])):e.kind===`wql`&&t.kind===`wql`?e.label===t.label&&e.query===t.query&&e.limit===t.limit:e.kind===`widget`&&t.kind===`widget`&&e.render===t.render}function LV(e,t){return e===t||(!e||e.length===0)&&(!t||t.length===0)?!0:!e||!t||e.length!==t.length?!1:e.every((e,n)=>IV(e,t[n]))}function RV({tree:e,children:t}){let[n,r]=(0,K.useReducer)(kV,OV),[i,a]=(0,K.useState)([]),[o,s]=(0,K.useState)(void 0),[c,l]=(0,K.useState)([]),[u,d]=(0,K.useState)(void 0),[f,p]=(0,K.useState)(void 0),[m,h]=(0,K.useState)(null),[g,_]=(0,K.useState)(null),v=(0,K.useCallback)(e=>{r({type:`OPEN_PEEK`,target:e})},[]),y=(0,K.useCallback)(()=>{r({type:`CLOSE_PEEK`})},[]),b=(0,K.useCallback)(e=>{d(t=>t===e?t:e)},[]),x=(0,K.useCallback)(e=>{s(t=>LV(t,e)?t:e)},[]),S=(0,K.useCallback)(e=>{p(t=>{let n=typeof e==`function`?e(t):e;return t===n||!t&&!n||t&&n&&t.pathname===n.pathname&&t.spec===n.spec?t:n})},[]),C=(0,K.useCallback)(e=>{h(t=>t===e?t:e)},[]),w=(0,K.useCallback)(e=>{_(t=>t===e||!t&&!e||t&&e&&t.weeks===e.weeks&&t.onWeeksChange===e.onWeeksChange&&t.showRange===e.showRange&&t.showUnits===e.showUnits&&t.unitForced===e.unitForced&&t.onOpenQuerySettings===e.onOpenQuerySettings&&t.onReset===e.onReset?t:e)},[]),T=(0,K.useCallback)(e=>{l(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n]?.id&&t.label===e[n]?.label&&t.icon===e[n]?.icon&&t.disabled===e[n]?.disabled&&t.testId===e[n]?.testId&&t.group===e[n]?.group&&t.onRun===e[n]?.onRun)?t:e)},[]),E=Qe(),D=(0,K.useMemo)(()=>{if(o!==void 0)return o;if(f&&f.pathname===E.pathname&&f.spec.length>0)return f.spec},[o,f,E.pathname]),O=(0,K.useRef)(AV),k=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=e.find(e=>e.isActive?e.isActive(E,n):e.action.type===`route`?e.action.to===`/`?E.pathname===`/`||E.pathname===``:E.pathname.startsWith(e.action.to):!1);r({type:`SET_ACTIVE_L1`,id:t?.id??null})},[E.pathname]),(0,K.useEffect)(()=>{r({type:`SET_LEFT_DRAWER`,open:!1}),r({type:`SET_RIGHT_DRAWER`,open:!1}),r({type:`SET_INSPECTOR_DRAWER`,open:!1})},[E.pathname]);let A=(0,K.useRef)(new Map),j=(0,K.useCallback)(e=>{let t=new Map,n=e.map(e=>{let n=e.secondaryAction;if(n?.action.type!==`call`)return e;let r=`${e.id}:${n.id}`,i=n.action.handler;return t.set(r,i),{...e,secondaryAction:{...n,action:{type:`call`,handler:()=>{let e=A.current.get(r);e?e():i()}}}}});A.current=t,a(e=>e.length===n.length&&e.every((e,t)=>e.id===n[t]?.id&&e.label===n[t]?.label&&e.secondaryAction?.id===n[t]?.secondaryAction?.id&&e.secondaryAction?.label===n[t]?.secondaryAction?.label&&e.secondaryRunIcon===n[t]?.secondaryRunIcon)?e:n)},[]),M=(0,K.useCallback)(e=>{r({type:`SET_ACTIVE_L3`,id:e}),O.current(e)},[]),N=(0,K.useCallback)(e=>{O.current=e},[]),P=(0,K.useCallback)(e=>{k.current?.(e)},[]),F=(0,K.useCallback)(e=>{k.current=e},[]),I=n.peekTarget??null,ee=(0,K.useMemo)(()=>({tree:e,navState:n,dispatch:r,peekTarget:I,openPeek:v,closePeek:y,l3Items:i,setL3Items:j,l3Connections:D,setL3Connections:x,l3Actions:c,setL3Actions:T,secondarySpec:u,setSecondarySpec:b,contextNav:f,setContextNav:S,streamControls:m,setStreamControls:C,analyticsControls:g,setAnalyticsControls:w,scrollToSection:M,registerScrollFn:N,openCreateJournal:P,registerCreateJournal:F}),[e,n,I,v,y,i,j,D,x,c,T,u,b,f,S,m,C,g,w,M,N,P,F]);return(0,q.jsx)(MV.Provider,{value:ee,children:t})}function zV(e){if(!e)return null;let t=Xg(e);return t.error?`Couldn't parse "${e}" — ${t.error}`:null}function BV(e,t,n=[]){let r=e.trim();if(!r||/[:{}|]/.test(r)||!Xg(r).error)return null;let i=`:${t}{${[`text:${/\s/.test(r)?`"${r.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:r}`,...n.filter(Boolean)].join(`,`)}}`;return Xg(i).error?null:i}function VV(e,t,n,r){if(!e)return{query:n,error:null};if(!Xg(e).error)return{query:e,error:null};let i=r?.salvageQ?.(e,t)??null;return i&&!Xg(i).error?{query:i,error:null}:{query:n,error:zV(e)}}var HV=1e3;function UV(e){let t=(0,K.useRef)(e);t.current=e;let[n,r]=be(),i=n.get(`q`)??``,[a,o]=(0,K.useState)(()=>{let{defaultQuery:e,legacy:r}=t.current;return i?VV(i,n,e,r).query:r?.toQuery(n)??e}),[s,c]=(0,K.useState)(()=>i?VV(i,n,t.current.defaultQuery,t.current.legacy).error:null),l=(0,K.useRef)(a);l.current=a;let u=(0,K.useRef)(n);u.current=n;let d=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(d.current)return;d.current=!0;let{legacy:e}=t.current,n=u.current,i=n.get(`q`)??``,a=null;if(i?Xg(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,K.useRef)(!0),p=(0,K.useRef)(null),m=(0,K.useRef)(i);(0,K.useEffect)(()=>{if(i===m.current)return;m.current=i,f.current=!0,clearTimeout(p.current),p.current=null,c(VV(i,u.current,t.current.defaultQuery,t.current.legacy).error);let e=i?VV(i,u.current,t.current.defaultQuery,t.current.legacy):{query:t.current.legacy?.toQuery(u.current)??t.current.defaultQuery,error:null};o(t=>t===e.query?t:e.query)},[i]);let h=(0,K.useRef)(t.current.defaultQuery);return(0,K.useEffect)(()=>{let e=t.current.defaultQuery;e!==h.current&&(h.current=e,!i&&o(t=>t===e?t:e))},[i,t.current.defaultQuery]),(0,K.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`q`)??``;if(e===m.current)return;m.current=e,f.current=!0,clearTimeout(p.current),p.current=null;let n=new URLSearchParams(window.location.search),r=e?VV(e,n,t.current.defaultQuery,t.current.legacy):{query:t.current.legacy?.toQuery(n)??t.current.defaultQuery,error:null};c(r.error),o(r.query)};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e),clearTimeout(p.current)}},[]),{query:a,setQuery:(0,K.useCallback)(e=>{if(o(e),!Xg(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},HV)}},[r]),urlQueryError:s}}var WV=[`origin`,`discipline`];function GV(e){let t=e.filter(Boolean);return`:effort${t.length?`{${t.join(`,`)}}`:``}`}function KV(e,t){let n=t.get(`origin`),r=t.get(`discipline`)?.trim();return BV(e,`effort`,[n&&n!==`all`?`origin:${n}`:``,r?`discipline:${r}`:``])}function qV(e){if(!WV.some(t=>e.get(t)))return null;let t=e.get(`origin`),n=e.get(`discipline`)?.trim();return GV([...t&&t!==`all`?[`origin:${t}`]:[],...n?[`discipline:${n}`]:[]])}var JV={keys:WV,toQuery:qV,salvageQ:KV},YV=new Map;function XV(e,t){let n=wI(e);if(!n)return;let r=t?.trim();r?YV.set(n,r):YV.delete(n)}function ZV(e){let t=wI(e),n=YV.get(t);if(n)return n;let r=ks.find(e=>e.slug===t);if(r?.name)return r.name;let i=SI().find(e=>wI(e.chunkId||e.id)===t);return i?.label?i.label:CP(t)}function QV(e){return e.endsWith(`/`)&&e.length>1?e.slice(0,-1):e}function $V(e,t){let n=[`note`,`session`,`post`,`text`,`timePreset`,`rangeStart`,`rangeEnd`,`s`,`tags`,`mode`],r=t??(e===`journal`?`journal`:e===`playground`?`playground`:`note`);return{keys:n,salvageQ(e){return BV(e,r)},toQuery(t){if(!n.some(e=>t.has(e)))return null;let r=null;if(t.has(`note`)||t.has(`session`)||t.has(`post`)){let e=[];(t.get(`note`)??`include`)!==`hide`&&e.push(`journal`),(t.get(`session`)??`include`)!==`hide`&&e.push(`notebooks`),e.length===1&&(r=`source:${e[0]}`)}else e&&(r=`source:${e}`);let i=t.get(`timePreset`)??`2w`,a=i===`all`||i===`custom`?null:`last ${i}`,o=t.get(`text`)?.trim(),s=t.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:notebooks`?u=`:notebooks`:r===`source:playground`?u=`:playground`:r&&d.unshift(r);let f=d.length?`{${d.join(`,`)}}`:``;return[`${u}${f}`,a].filter(Boolean).join(` `)}}}var eH={route:`/journal`,title:`Journal`,defaultWql:`:note{notebook:journal} by {date} last 4w`,level:`note`,target:`note`,scopeOptions:[`journal`,`playground`],defaultLayout:`agenda`,calendarCapable:!0,legacy:$V(`journal`)},tH={route:`/notebooks`,title:`Notebooks`,defaultWql:`:notebook{subscribed:true} by {feed}`,level:`note`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,feedNotice:!0,legacy:$V(`notebooks`)},nH={route:`/notes`,title:`Notes`,defaultWql:`:note{}`,level:`note`,target:`note`,scopeOptions:[`journal`,`notebooks`],emptyMessage:`No note entries match your search.`,calendarCapable:!0,legacy:$V(`notebooks`)},rH={route:`/feeds`,title:`Feeds`,defaultWql:`:feed{}`,level:`session`,target:`feed`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,emptyMessage:`No feeds match your search.`,feedNotice:!0,legacy:$V(`notebooks`,`feed`)},iH={route:`/pages`,title:`Pages`,defaultWql:`:page{}`,level:`note`,target:`page`,scopeOptions:[],emptyMessage:`No pages match your search.`},aH={route:`/efforts`,title:`Efforts`,defaultWql:`:effort`,level:`effort`,target:`effort`,scopeOptions:[],emptyMessage:`No efforts match your search.`,legacy:JV},oH={route:`/equipment`,title:`Equipment`,defaultWql:`:equipment{}`,level:`note`,target:`equipment`,scopeOptions:[`equipment`],emptyMessage:`No equipment matches your search.`},sH={route:`/tags`,title:`Tags`,defaultWql:`:tag{}`,level:`note`,target:`tag`,scopeOptions:[],emptyMessage:`No tags match your search.`},cH={route:`/sessions`,title:`Sessions`,defaultWql:`:session{}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No completed session results recorded in this period.`,calendarCapable:!0},lH={route:`/playgrounds`,title:`Playgrounds`,defaultWql:`:playground{} by {date} last 1w`,level:`note`,target:`note`,scopeOptions:[`playground`],shelfVisible:!0,legacy:$V(`playground`)};function uH(e){return{route:`/session/${e}`,defaultWql:`:session{} from ${e} to ${e}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No session results recorded on ${e}.`}}function dH(e){return{route:`/results/${e}`,defaultWql:`:session{result:${e}, plane:segment}`,level:`segment`,target:`session`,scopeOptions:[],defaultLayout:`rows`,dashboardEnabled:!0,emptyMessage:`No segment records found for result ${e}.`}}function fH(e){let t=wI(e);return{route:`/notebook/${e}`,title:ZV(t),defaultWql:`:note{notebook:${t}} by {date}`,level:`note`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,calendarCapable:!0,notebookSlug:t,legacy:$V(`notebooks`)}}var pH={"/journal":eH,"/notebooks":tH,"/notes":nH,"/feeds":rH,"/pages":iH,"/efforts":aH,"/equipment":oH,"/tags":sH,"/sessions":cH,"/playgrounds":lH};function mH(e){let t=QV(e),n=pH[t];if(n)return n;if(t.startsWith(`/results/`)){let e=t.slice(9);if(e)return dH(e)}if(t.startsWith(`/session/`)){let e=t.slice(9);if(e)return uH(e)}if(t.startsWith(`/notebook/`)){let e=t.slice(10);if(e&&!e.includes(`/`))return fH(e)}}function hH(e){return mH(e)??eH}function gH(e){let t=pH[QV(e)]?.title;if(t)return t;if(QV(e).startsWith(`/notebook/`)){let t=QV(e).slice(10);if(t&&!t.includes(`/`))return ZV(t)}}function _H(e){let t=QV(e);if(pH[t])return!0;if(t.startsWith(`/results/`)||t.startsWith(`/session/`))return t.slice(9)!==``;if(t.startsWith(`/notebook/`)){let e=t.slice(10);return!!(e&&!e.includes(`/`))}return!1}var Z={home:`/`,playgroundRoot:`/playground`,playground:`/playground/:id`,note:`/note/:noteId`,notes:`/notes`,journal:`/journal`,day:`/day/:date`,plan:`/plan`,aiFirst:`/ai-first`,feeds:`/feeds`,feed:`/feed/:slug`,notebooks:`/notebooks`,notebook:`/notebook/:slug`,notebookTarget:`/notebook/:slug/:target`,notebookItem:`/notebook/:slug/:itemDate/:item`,subscribe:`/subscribe`,pages:`/pages`,page:`/page/:slug`,tags:`/tags`,tagCategory:`/t/:type`,tag:`/t/:type/:tag`,sessions:`/sessions`,sessionDetail:`/results/:sessionId`,sessionDate:`/session/:date`,playgrounds:`/playgrounds`,tracker:`/tracker/:runtimeId`,run:`/run/:runtimeId`,load:`/load`,loadJournal:`/load/journal`,loadJournalDate:`/load/journal/:date`,efforts:`/efforts`,effort:`/effort/:slug`,equipment:`/equipment`,equipmentSlug:`/equipment/:slug`,dashboards:`/dashboards`,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`},vH={settingsData:`/settings/data`,settingsDatabase:`/settings/database`,settingsQueries:`/settings/queries`};function yH(e){return`/playground/${encodeURIComponent(e)}`}function bH(e){return`/day/${encodeURIComponent(e)}`}function xH(e,t){return`/day/${encodeURIComponent(e)}?autoStart=${encodeURIComponent(t)}`}function SH(e){return`/note/${encodeURIComponent(e)}`}function CH(e){let t=wI(e);return`/notebook/${encodeURIComponent(t)}`}function wH(e,t){return`/notebook/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function TH(e,t){return`/notebook/${encodeURIComponent(e)}/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}function EH(e){return`/feed/${encodeURIComponent(e)}`}function DH(e){return`/run/${encodeURIComponent(e)}`}function OH({zip:e}){return`/load?zip=${encodeURIComponent(e)}`}function kH(){return`/sessions`}function AH(e){return`/results/${encodeURIComponent(e)}`}function jH(e){return`/page/${encodeURIComponent(e)}`}function MH(){return`/playgrounds`}function NH(){return`/efforts`}function PH(e){return`/equipment/${encodeURIComponent(e)}`}function FH(e){return`/t/${encodeURIComponent(e)}`}function IH(e,t){return`/t/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function LH(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 RH(){return`/dashboards`}function zH(e){return`/dashboard/${encodeURIComponent(e)}`}function BH(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?`/effort/${encodeURIComponent(e)}?${i}`:`/effort/${encodeURIComponent(e)}`}function VH(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 HH(e){return e?`/settings/${e}`:`/settings/appearance`}function UH(e){return e.startsWith(`/playground/`)}function WH(e){return e===`/efforts`||e.startsWith(`/effort/`)||e===`/t/effort`||e.startsWith(`/t/effort/`)}function GH(e){return e===`/equipment`||e.startsWith(`/equipment/`)||e===`/t/equipment`||e.startsWith(`/t/equipment/`)}function KH(e){let t=e.match(/^\/notebook\/([^/]+)\/([^/]+)\/([^/]+)$/);return t?[t[1],t[2],t[3]]:null}function qH(e){let t=e.match(/^\/feed\/([^/]+)$/);return t?t[1]:null}var JH=(0,K.forwardRef)(function({href:e,...t},n){return(0,q.jsx)(M,{...t,to:e,ref:n})}),YH=(0,K.createContext)(()=>{});function XH({close:e,children:t}){return(0,q.jsx)(YH.Provider,{value:e,children:t})}function ZH(){return(0,K.useContext)(YH)}function QH({className:e,...t}){return(0,q.jsx)(`nav`,{...t,className:ra(e,`flex h-full min-h-0 flex-col`)})}function $H({className:e,...t}){return(0,q.jsx)(`div`,{...t,className:ra(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 eU({className:e,...t}){return(0,q.jsx)(`div`,{...t,className:ra(e,`l2-sidebar-body flex flex-1 flex-col overflow-y-auto p-4 [&>[data-slot=section]+[data-slot=section]]:mt-8`)})}function tU({className:e,...t}){let n=(0,K.useId)();return(0,q.jsx)(Ie,{id:n,children:(0,q.jsx)(`div`,{...t,"data-slot":`section`,className:ra(e,`flex flex-col gap-0.5`)})})}function nU({className:e,...t}){return(0,q.jsx)(`h3`,{...t,className:ra(e,`mb-1 px-2 text-xs/6 font-medium text-muted-foreground`)})}var rU=(0,K.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=ZH(),o=ra(`group flex min-h-11 sm:min-h-9 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`,`hover:bg-primary/10 hover:text-primary hover:[&>[data-slot=icon]]:text-primary`,`active:bg-primary/15 active:scale-[0.98]`,`data-[current]:bg-primary/10 data-[current]:text-primary data-[current]:[&>[data-slot=icon]]:text-primary font-bold`),s=r,c=r;return(0,q.jsxs)(`span`,{className:ra(t,`relative`),children:[e&&(0,q.jsx)(_e.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,q.jsx)(JH,{...s,onClick:e=>{s.onClick?.(e),e.defaultPrevented||a()},className:o,"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n}):(0,q.jsx)(`button`,{type:`button`,...c,className:ra(`cursor-default`,o),"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n})]})});function iU({className:e,...t}){return(0,q.jsx)(`span`,{...t,className:ra(e,`truncate`)})}function aU(e){return Object.entries(e).filter(([e])=>e.startsWith(`markdown/dashboards/`)).map(([e,t])=>{let{meta:n}=ac(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))}var oU=new Set;function sU(){for(let e of oU)e()}function cU(e){return oU.add(e),()=>{oU.delete(e)}}function lU(e){return e.map(e=>{let{meta:t}=ac(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 uU(e){let t={};for(let n of e)n.seedOrigin===`seed`&&n.sourcePath?.startsWith(`markdown/dashboards/`)&&(t[n.sourcePath]=n.rawContent);return aU(t)}function dU(e,t){let n=HP(),r=(0,K.useMemo)(()=>n?aU(n):[],[n]),i=(0,K.useMemo)(()=>{if(!e)return null;let t=r.find(t=>t.slug===e);return t?{slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1}:null},[r,e]),[a,o]=(0,K.useState)(()=>i),[s,c]=(0,K.useState)(()=>!!e&&i===null);return(0,K.useEffect)(()=>{if(!e){o(null),c(!1);return}let r=!1;return o(t=>t&&t.slug===e?t:i),c(e=>t!==void 0&&t>0?!0:i?!1:e||!0),Promise.all([eR.listNotes({kind:`dashboard`}),n?Promise.resolve(null):X.getNotesByType(`dashboard`)]).then(([t,n])=>{if(r)return;let a=lU(t).find(t=>t.slug===e);if(a){o({slug:e,title:a.title,rawContent:a.rawContent,editable:!0,noteId:a.noteId});return}if(i){o(i);return}if(n){let t=uU(n).find(t=>t.slug===e);if(t){o({slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1});return}}o(null)}).catch(()=>{r||o(i)}).finally(()=>{r||c(!1)}),()=>{r=!0}},[e,t,i,n]),{source:a,loading:s}}function fU(){let e=HP(),t=(0,K.useMemo)(()=>e?aU(e):[],[e]),[n,r]=(0,K.useState)([]),[i,a]=(0,K.useState)(!0),[o,s]=(0,K.useState)(0);return(0,K.useEffect)(()=>cU(()=>{s(e=>e+1)}),[]),(0,K.useEffect)(()=>{let n=!1;return Promise.all([eR.listNotes({kind:`dashboard`}),e?Promise.resolve(null):X.getNotesByType(`dashboard`)]).then(([i,a])=>{if(n)return;let o=lU(i),s=new Set(o.map(e=>e.slug)),c=e?t:a?uU(a):t,l=[...o.map(e=>({slug:e.slug,title:e.title,editable:!0})),...c.filter(e=>!s.has(e.slug)).map(e=>({slug:e.slug,title:e.title,editable:!1}))];n||r(l)}).catch(()=>{n||r(t.map(e=>({slug:e.slug,title:e.title,editable:!1})))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,e,o]),{items:n,loading:i}}function pU(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function mU(){return pU(new Date)}function hU(e){return e<mU()}function gU(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=pU(a);return o===e?{dateKey:o,date:a}:null}var _U=`schedule:v35:pageNotesMigrated`,vU=new WeakSet,yU=new Set;function bU(){for(let e of[...yU])try{e()}catch{}}function xU(e){return yU.add(e),()=>{yU.delete(e)}}async function SU(e=X.storage){if(!vU.has(e))try{if((await e.readonly(`meta`).get(_U))?.value===!0){vU.add(e);return}await ow(e),await e.readwrite(`meta`).put({key:_U,value:!0}),vU.add(e)}catch{}}var CU={async scheduleNote(e){await SU();let t=await YC(X.storage,e);return bU(),t},async batchSchedule(e){await SU();let t=await XC(X.storage,e);return bU(),t},async updateItem(e,t){let{order:n,position:r,...i}=t,a=r??n,o=await ZC(X.storage,e,{...i,...a===void 0?{}:{position:a}});return bU(),o},async removeItem(e){await QC(X.storage,e),bU()},async listByDateRange(e,t){return await SU(),$C(X.storage,e,t)},async listAll(){await SU();try{return await X.storage.readonly(`schedule_items`).getAll()}catch{return[]}},async listForNote(e){return await SU(),ew(X.storage,e)},async getDayOverlay(e){return await SU(),aw(X.storage,e)},async getUsageCountsByNote(){return await SU(),tw(X.storage)},async attributeSession(e){let t=await nw(X.storage,e);return bU(),t},async findNearbyMatches(e,t=2){return await SU(),rw(X.storage,e,t)},async getNoteRevision(e,t){return qC(X.storage,e,t)},async listNoteRevisions(e){return JC(X.storage,e)},todayKey(e=Date.now()){return BC(e)}};function wU(e){let t=gU(e);if(!t)throw Error(`Invalid journal date: ${e}`);return t.date.getTime()}function TU({persistence:e,moveRecordPlacement:t,addRecordPlacement:n,onScheduleNote:r,listOverlayNotes:i,uuid:a=Br}){let o=new Map;return{async create(t){let n=t.journalDate?wU(t.journalDate):Date.now(),i=await e.createNote({id:a(),title:MT(t.title),rawContent:t.rawContent,tags:t.tags??[],targetDate:n,journalDate:t.journalDate||void 0,type:t.type??`journal`,slug:t.slug,sourceId:t.sourceId,notebookIds:t.notebookIds??[]});return t.journalDate&&t.type!==`dashboard`&&t.type!==`playground`&&r&&await r(i.id,t.journalDate).catch(()=>{}),i},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 wU(t),i?i(t):(await e.listNotes({journalDate:t,kind:`journal`,projection:`summary`})).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))},update(t,n,r){let i=t.id,a=MT(n.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<n.length&&t.rawContent[c]===n[c];)c++;let l=t.rawContent.length,u=n.length;for(;l>c&&u>c&&t.rawContent[l-1]===n[u-1];)l--,u--;let d=Us(t.blocks??{},r?.changes??[{from:c,to:l,insert:n.slice(c,u)}]);for(let e of r?.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=Vs(n,{sourceRevision:s,registeredWidgets:Ns,blocks:d}),p=async()=>e.mutateNote({id:i},{rawContent:n,blocks:f,expectedSourceRevision:s,metadata:a?{title:a}:void 0}),m=(o.get(i)??Promise.resolve()).then(p,p);o.set(i,m);let h=()=>{o.get(i)===m&&o.delete(i)};return m.then(h,h),m},async moveToDate(r,i){let a=wU(i);if(t&&n){let a=(await e.getNote({id:r},{projection:`summary`})).placements?.find(e=>e.date);return a?t(r,a.pageId,{date:i}):n(r,{date:i})}return e.mutateNote({id:r},{metadata:{journalDate:i,targetDate:a}})},delete(t){return e.deleteNote({id:t})}}}var EU=new DR,DU=TU({persistence:eR,moveRecordPlacement:(e,t,n)=>EU.moveRecordPlacement(e,t,n),addRecordPlacement:(e,t)=>EU.addRecordPlacement(e,t),onScheduleNote:async(e,t)=>{await CU.scheduleNote({noteId:e,date:t})},listOverlayNotes:async e=>{let[t,n]=await Promise.all([CU.getDayOverlay(e).catch(()=>void 0),eR.listNotes({journalDate:e,projection:`summary`}).catch(()=>[])]),r=new Map;for(let e of n)r.set(e.id,e);if(t){let n=t.planned.map(e=>e.note).filter(Boolean);for(let t of n)!t||r.has(t.id)||r.set(t.id,{id:t.id,title:t.title,createdAt:t.createdAt,updatedAt:t.createdAt,targetDate:t.date??wU(e),journalDate:e,rawContent:t.rawContent,sourceRevision:t.sourceRevision,blocks:t.blocks,tags:t.tags??[],schemaVersion:1,type:t.type??`note`,sourceId:t.sourceId,notebookId:t.notebookId,notebookIds:t.notebookIds,provenance:t.provenance,seedOrigin:t.seedOrigin})}return Array.from(r.values()).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))}});function OU({persistence:e,journal:t}){async function n(n){let r=await e.listNotes({kind:`dashboard`}),i=new Set;for(let e of r){let{meta:r,body:a}=ac(e.rawContent);if(typeof r.slug==`string`&&r.slug.trim()&&i.add(r.slug.trim()),n&&e.id===n||r.dashboard!==`true`||r[`dashboard.active`]!==`true`)continue;let o={...r};delete o[`dashboard.active`],await t.update(e,`---\n${sc(o)}\n---\n${a}`)}return i}function r(e,t){let{meta:n,body:r}=ac(e),i=(typeof n.slug==`string`&&n.slug.trim()?kb(n.slug):kb(String(n.title??`New Dashboard`)))||`dashboard`,a=1,o=i;for(;t.has(o);)a+=1,o=`${i}-${a}`;if(n.slug===o)return{rawContent:e,slug:o,suffix:a};let s={...n,slug:o};return a>1&&n.title===`New Dashboard`&&(s.title=`${Ob} ${a}`),{rawContent:`---\n${sc(s)}\n---\n${r}`,slug:o,suffix:a}}return{async createDashboard(e=Ob){let i=await n(),a=r(cae(e),i),o=a.suffix>1&&e===`New Dashboard`?`${Ob} ${a.suffix}`:e,s=await t.create({title:o,rawContent:a.rawContent,type:`dashboard`,sourceId:`dashboards`});return sU(),s},async createDashboardFromScope(e){let i=await n(),a=r(xae(e),i),{meta:o}=ac(a.rawContent),s=typeof o.title==`string`&&o.title?o.title:Ob,c=await t.create({title:s,rawContent:a.rawContent,type:`dashboard`,sourceId:`dashboards`});return sU(),c},async cloneDashboard(e,r,i){await n();let{meta:a,body:o}=ac(r),s={...a,slug:e};i&&(s.title=i);let c=`---\n${sc(s)}\n---\n${o}`,l=await t.create({title:typeof s.title==`string`?s.title:e,rawContent:c,type:`dashboard`,sourceId:`dashboards`});return sU(),l},async deleteDashboard(e){await t.delete(e),sU()}}}var kU=OU({persistence:eR,journal:DU});function AU({itemsOverride:e,...t}){let n=Qe(),r=dt(),i=ZH(),{items:a,loading:o}=fU(),s=e??a,c=!e&&o,[l,u]=(0,K.useState)(!1),d=async()=>{u(!0);try{let e=await kU.createDashboard(),{meta:t}=ac(e.rawContent),n=typeof t.slug==`string`&&t.slug?t.slug:e.id;r(zH(n)),i()}finally{u(!1)}},f=n.pathname===`/dashboards`,p=s.filter(e=>e.editable),m=s.filter(e=>!e.editable),h=e=>{let t=zH(e);if(n.pathname===t)return!0;let r=/^\/dashboard\/([^/]+)\/?$/.exec(n.pathname);if(!r)return!1;try{return decodeURIComponent(r[1])===e}catch{return r[1]===e}};return(0,q.jsxs)(`div`,{className:`flex flex-col gap-3 px-2 py-3`,"data-testid":`dashboards-nav-panel`,children:[(0,q.jsx)(tU,{children:(0,q.jsxs)(rU,{current:f,onClick:()=>{r(RH()),i()},children:[(0,q.jsx)(ir,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:`Explorer`})]})}),c?(0,q.jsxs)(tU,{children:[(0,q.jsx)(nU,{children:`Dashboards`}),(0,q.jsx)(`div`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`Loading…`})]}):s.length===0?(0,q.jsxs)(tU,{children:[(0,q.jsx)(nU,{children:`Saved dashboards`}),(0,q.jsx)(`div`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No dashboards yet.`})]}):(0,q.jsxs)(q.Fragment,{children:[p.length>0&&(0,q.jsxs)(tU,{"data-testid":`dashboards-nav-saved`,children:[(0,q.jsx)(nU,{children:`Saved dashboards`}),p.map(e=>(0,q.jsxs)(rU,{current:h(e.slug),"data-testid":`dashboard-nav-item-${e.slug}`,onClick:()=>{r(zH(e.slug)),i()},children:[(0,q.jsx)(ft,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:e.title})]},e.slug))]}),m.length>0&&(0,q.jsxs)(tU,{"data-testid":`dashboards-nav-prebuilt`,children:[(0,q.jsx)(nU,{children:`Prebuilt`}),m.map(e=>(0,q.jsxs)(rU,{current:h(e.slug),"data-testid":`dashboard-nav-item-${e.slug}`,onClick:()=>{r(zH(e.slug)),i()},children:[(0,q.jsx)(Ir,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:e.title})]},e.slug))]})]}),(0,q.jsx)(`div`,{className:`mt-1 border-t border-border/40 pt-2`,children:(0,q.jsxs)(`button`,{type:`button`,onClick:d,disabled:l,"data-testid":`dashboards-nav-new`,className:`flex w-full items-center gap-2 rounded-xl px-2 py-2 max-lg:min-h-11 text-sm font-medium text-muted-foreground transition-colors hover:bg-primary/10 hover:text-primary disabled:opacity-50`,children:[(0,q.jsx)(ti,{className:`size-4 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate`,children:`New dashboard`})]})})]})}function jU(e){return e.replace(/(^|[{,\s!])catalog:("[^"]*"|[\w][\w/-]*)/g,`$1notebook:$2`)}var MU=[{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`}],NU=MU.map(e=>e.id),PU=Object.fromEntries(MU.map(e=>[e.id,e.label]));function FU(e){return PU[e]??e}function IU(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 LU(e,t){let n=new Set(e);if(!t||t.length===0)return MU.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:FU(e)})),...MU.filter(e=>n.has(e.id)&&!i.has(e.id))]}function RU(e,t,n){if(!e)return n;let r=new Set(t);return e.find(e=>r.has(e))??n}function zU(e){if(!e)return{options:[],invalid:[]};let t=[],n=[],r=new Set;for(let i of e){if(!NU.includes(i)){n.includes(i)||n.push(i);continue}r.has(i)||(r.add(i),t.push(i))}return{options:t,invalid:n}}var BU=`/palette`,VU=new rE(`wodwiki.routeWql.v1`,FR?zR:void 0),HU=[...qh,...Jh],UU={notes:`note`,blocks:`block`,efforts:`effort`,collections:`notebooks`,feeds:`notebooks`};function WU(e){let t=e.startsWith(`/`)?e:`/${e}`;return YU[t]??t}function GU(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim())}function KU(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 qU={"/notebooks":`/catalogs`,"/notes":`/feeds`,"/sessions":`/results`,"/dashboards":`/dashboard`},JU={"/notes":`/collections`},YU={"/feeds":`/feeds@2`};function XU(e){return jU(e).replace(/^:(collections?|feeds?)(?![\w:])/,e=>e===`:collections`||e===`:feeds`?`:notebooks`:`:notebook`).replace(/(^|[{,\s])source:(collections|feeds)(?![\w:])/g,`$1source:notebooks`).replace(/(^|[{,\s])source:collection:/g,`$1source:notebook:`).replace(/(^|[{,\s])type:(feed|collection)(?![\w:])/g,`$1type:note`)}function ZU(e,t=VU){let n=WU(e),r=qU[n],i=t.get(n,{alias:r});if(i==null&&r&&(i=t.get(r,{alias:JU[n]})),!i)return{};let a=GU(i.typeOptions),o=GU(i.groupByOptions),s=a&&KU(a,HU,UU),c=o?zU(o):void 0;return{defaultWql:typeof i.defaultWql==`string`&&i.defaultWql.trim().length>0?XU(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 QU(e,t,n=VU){let r=WU(e),i={defaultWql:t.defaultWql?.trim()||void 0,typeOptions:GU(t.typeOptions),groupByOptions:GU(t.groupByOptions)};if(FR){try{await VR(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlConfig] server write failed:`,e),!1}return iW(),!0}return n.set(r,i),iW(),!0}async function $U(e,t=VU){let n=WU(e),r=qU[n];if(FR){try{await HR(r?[t.qualify(n),t.qualify(r)]:[t.qualify(n)])}catch(e){return console.error(`[routeWqlConfig] server delete failed:`,e),!1}return iW(),!0}return t.remove(n,r),iW(),!0}var eW=0,tW=new Set;function nW(e){return tW.add(e),()=>{tW.delete(e)}}function rW(){return eW}function iW(){eW+=1;for(let e of tW)e()}function aW(e){let t=(0,K.useSyncExternalStore)(nW,rW,rW);return(0,K.useMemo)(()=>ZU(e),[e,t])}function oW(e,t){let n=t??ZU(e.route);return!n.defaultWql&&!n.typeOptions&&!n.groupByOptions?e:{...e,defaultWql:n.defaultWql??e.defaultWql,scopeOptions:n.typeOptions?n.typeOptions.filter(e=>Jh.includes(e)):e.scopeOptions,groupByOptions:n.groupByOptions}}function sW(e){let t=aW(e?.route??``);return(0,K.useMemo)(()=>e?oW(e,t):void 0,[e,t])}var cW={bookmark:Lee,calendar:U,"clipboard-list":An,clock:xr,dumbbell:ci,flame:vt,folder:De,"flask-conical":En,heart:$t,library:qe,plus:ti,rss:sr,star:Tn,tag:Ee,activity:dn,wrench:Ct},lW=new rE(`wodwiki.routeWqlShortcuts.v1`,FR?zR:void 0);function uW(e,t){return{id:`all`,label:e,icon:t,wql:``}}var dW={"/journal":`All entries`,"/notebooks":`Subscribed notebooks`,"/notes":`All notes`,"/feeds":`All feeds`,"/pages":`All pages`,"/playgrounds":`All playgrounds`,"/efforts":`All Efforts`,"/equipment":`All Equipment`,"/sessions":`All Sessions`,"/tags":`All Tags`},fW={"/journal":`calendar`,"/notebooks":`library`,"/notes":`rss`,"/feeds":`rss`,"/pages":`clipboard-list`,"/playgrounds":`flask-conical`,"/efforts":`flame`,"/equipment":`dumbbell`,"/sessions":`clipboard-list`,"/tags":`tag`};function pW(e){let t=gW(e);return t===`/notebooks`?[uW(`Subscribed notebooks`,`library`),{id:`all-configured`,label:`All configured`,icon:`bookmark`,wql:`:notebook{subscribed:true,false}`},{id:`available`,label:`Available to subscribe`,icon:`plus`,wql:`:notebook{subscribed:false}`}]:t===`/sessions`?[uW(`All Sessions`,`clipboard-list`),{id:`recent-1d`,label:`Recent (last 1d)`,icon:`clock`,wql:`:session{} last 1d`},{id:`recent-7d`,label:`Last 7 days`,icon:`calendar`,wql:`:session{} last 7d`}]:[uW(dW[t]??`Landing link`,fW[t]??`bookmark`)]}function mW(e){return e.map(e=>({id:`tag-type-${e.name}`,label:e.label,icon:`tag`,wql:`:tag{type:${e.name}}`}))}function hW(e){let t=(0,K.useMemo)(()=>pW(e),[e]),[n,r]=(0,K.useState)([]);return(0,K.useEffect)(()=>{if(gW(e)!==`/tags`)return;let t=!0;return X.getAllTagTypes().then(e=>{t&&r(e)}).catch(()=>{t&&r([])}),()=>{t=!1}},[e]),(0,K.useMemo)(()=>gW(e)===`/tags`?[...t,...mW(n)]:t,[e,t,n])}function gW(e){return e.startsWith(`/`)?e:`/${e}`}var _W={"/notebooks":`/catalogs`,"/notes":`/feeds`},vW={"/feeds":`/feeds@2`};function yW(e){let t=gW(e);return vW[t]??t}function bW(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`||!cW[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:XU(e.wql.trim()),...typeof e.to==`string`?{to:e.to}:{}})))}return t}function xW(e,t=lW){let n=yW(e);return bW(t.get(n,{alias:_W[n]}))}function SW(e,t=lW,n=pW(e)){let r=yW(e),i=_W[r];if(t.getRaw(r)!=null||i!=null&&t.getRaw(i)!=null){let r=xW(e,t);return r.some(e=>e.id===`all`)?r:[n[0],...r]}return n}async function CW(e,t,n=lW){let r=yW(e),i=bW(t);if(FR){try{await VR(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlShortcuts] server write failed:`,e),!1}return OW(),!0}return n.set(r,i),n.getRaw(r)===JSON.stringify(i)&&(OW(),!0)}var wW=0,TW=new Set;function EW(e){return TW.add(e),()=>{TW.delete(e)}}function DW(){return wW}function OW(){wW++;for(let e of TW)e()}function kW(e,t=lW){return(0,K.useSyncExternalStore)(EW,DW),SW(e,t,hW(e))}function AW(e){return Fg(e)?A_({...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))}):A_(e)}function jW(e,t){return e.to?t.pathname===e.to||t.pathname.startsWith(`${e.to}/`):MW(e.wql,t.query)}function MW(e,t){if(!e.trim())return t.trim()===``;if(t.trim()===``)return!1;if(t===e)return!0;let n=Xg(t),r=Xg(e);return!n.error&&!r.error&&AW(n)===AW(r)}var NW=null,PW=new Set;function FW(e){NW=e;for(let e of PW)e()}function IW(e){return PW.add(e),()=>{PW.delete(e)}}function LW(){return NW}function RW(){return(0,K.useSyncExternalStore)(IW,LW)}function zW(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}}function BW(e){switch(e.kind){case`journal`:return bH(e.id);case`playground`:return yH(e.id);case`workout`:return e.category===`effort`?BH(e.id):e.category===`equipment`?PH(e.id):e.category?TH(e.category,e.id):SH(e.raw)}}var VW=/^(?:uuid-|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)/i;function HW(e){return typeof e==`string`&&e&&!VW.test(e)?e:void 0}function UW(e){return!!e.sourceId?.startsWith(`notebook:`)||e.sourcePath?.startsWith(`markdown/notebooks/`)===!0}function WW(e){return e.type===`dashboard`||e.sourceId===`dashboards`||e.sourcePath?.startsWith(`markdown/dashboards/`)===!0}function GW(e){return e.sourceId===`efforts`||e.sourcePath?.startsWith(`markdown/efforts/`)===!0}function KW(e){return e.sourceId===`equipment`||e.sourcePath?.startsWith(`markdown/equipment/`)===!0}function qW(e){return e.type===`tag`&&e.id.startsWith(`tag/`)}function JW(e){let t=/^tag\/([^/]+)\/(.+)$/.exec(e.id);return t?{type:t[1],label:t[2]}:void 0}function YW(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 XW(e){let t=e.sourceId;if(t?.startsWith(`notebook:`)){let e=t.slice(9);if(e&&e!==`_root`){let t=e.indexOf(`/`);return t===-1?{slug:e,item:``}:{slug:e.slice(0,t),item:e.slice(t+1)}}}let n=/^markdown\/notebooks\/([^/]+)\/(.+)\.md$/.exec(e.sourcePath??``);if(n)return{slug:n[1],item:n[2].toLowerCase()===`readme`?``:n[2]};let r=e.id;if(VW.test(r))return{slug:``,item:``};let[i,...a]=r.split(`/`);return{slug:i,item:a.join(`/`)}}function ZW(e){return e.sourceId===`playground`||e.type===`playground`||e.id.startsWith(`playground/`)}function QW(e){let t=e.slug??e.id;return t.startsWith(`playground/`)?t.slice(11):t}function $W(e){if(!e.startsWith(`remote:`))return;let t=e.slice(7),n=t.indexOf(`:`);return n>0?t.slice(0,n):void 0}function eG(e){let t=tG(e),n=Wy(e),r=t.notebookId??Uy(e),i=e.id.startsWith(`remote:`)||e.retention===`indexed`,a=i?$W(e.id):void 0,o=Ds(e,n,r),s=i?!1:t.editable??(o.editable&&Os(e,n,r));return{...t,noteType:e.type,notebookId:r,...e.notebookIds===void 0?{}:{notebookIds:e.notebookIds},feedId:t.feedId??e.feedSourceId??a??(n===`user`?`local`:`core`),editable:s,ownership:o,...e.public===void 0?{}:{isPublic:e.public},...i?{isRemotePreview:!0,editable:!1}:{},...e.seedChunkId?{seedChunkId:e.seedChunkId}:{}}}function tG(e){let t=e.id,n=e.title,r=e.tags&&e.tags.length>0?e.tags:void 0;if(e.type===`feed`&&t.startsWith(`feed/`)){let i=t.slice(5),a=e.tags??[];return{id:t,kind:`feed`,sourceNotebook:`feeds`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:e.sourcePath,detail:e.rawContent.split(`
|
|
790
|
+
`),await s.writeText(`${c}.csv`,ux(o))),$I(await s.toBlob(),`${i}-${r.nowMs()}.zip`)}async function cL(e,t,n){let r=[],i=new Set,a=0,o=0;for(let s of e){let e=s.note?.id??s.revisions?.[0]?.noteId??s.sessions[0]?.noteId??s.events[0]?.noteId;if(!(e&&n.skipBundles?.has(e))){if(!n.revisionsRestored&&s.revisions&&s.revisions.length>0)try{let e=t.persistenceStorage;if(!e)throw Error(`Revision import requires provider.persistenceStorage`);await t.persistenceReady,await e.saveBlockRevisions(s.revisions)}catch(t){r.push(`Failed to restore revisions for ${e??`unknown note`}: ${t instanceof Error?t.message:String(t)}`);continue}if(s.note&&!n.skipNotes.has(s.note.id))try{let e=await t.getRecord(s.note.id),n={...s.note,tags:s.note.tags??[],sourceRevision:e?.sourceRevision??s.note.sourceRevision,blocks:e?.rawContent===s.note.rawContent?e.blocks:s.note.blocks};await t.saveRecord(n),i.add(s.note.id)}catch(e){r.push(`Failed to import note ${s.note.id}: ${e instanceof Error?e.message:String(e)}`);continue}if(s.sessions.length>0||s.events.length>0){let e=t.persistenceStorage;if(!e){r.push(`Telemetry import requires provider.persistenceStorage`);continue}await t.persistenceReady;for(let n of s.sessions)try{if(!await t.getRecord(n.noteId))throw Error(`Parent note ${n.noteId} does not exist`);let r=await e.getBlockRevision(n.noteId,n.blockId,n.blockVersion);if(!r||r.kind!==`wod`)throw Error(`Pinned wod BlockRevision [${n.noteId}, ${n.blockId}, ${n.blockVersion}] does not exist`);let i=s.events.filter(e=>e.resultId===n.id);for(let e of i)if(e.noteId!==n.noteId||e.blockId!==n.blockId||e.blockVersion!==n.blockVersion||e.blockContentId!==n.blockContentId)throw Error(`Event ${e.id} does not match session ${n.id} identity`);let c=i.filter(e=>e.grain===`event`),l=i.filter(e=>e.grain===`summary`),u=l.length>0?l:My(Fy(c),{noteId:n.noteId,resultId:n.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,origin:n.origin,pageId:n.pageId,workoutTimestamp:n.startTime});await e.withTransaction([`notes`,`block_revisions`,`sessions`,`events`],async e=>{await e.saveSession(n),i.length>0&&(await e.appendEvents(c),await e.finalizeSummaries(n.id,u))}),a++,o+=c.length+u.length}catch(e){r.push(`Failed to import session ${n.id}: ${e instanceof Error?e.message:String(e)}`)}}}}return{noteIds:i,sessions:a,events:o,errors:r}}async function Lue(e,t){try{let n=rL(e,of),r=n.id?await t.getRecord(n.id):null;return await t.saveRecord({...n,sourceRevision:r?.sourceRevision??n.sourceRevision,blocks:r?.rawContent===n.rawContent?r.blocks:n.blocks}),{imported:1,sessionsImported:0,eventsImported:0,errors:[]}}catch(e){return{imported:0,sessionsImported:0,eventsImported:0,errors:[e instanceof Error?e.message:String(e)]}}}async function Rue(e,t){let n=bc(e),r=await cL(n.bundles,t,{skipNotes:new Set});return{imported:r.noteIds.size,sessionsImported:r.sessions,eventsImported:r.events,errors:[...n.errors,...r.errors]}}async function zue(e,t){let n=dx(e),r=await cL(n.bundles,t,{skipNotes:new Set});return{imported:r.noteIds.size,sessionsImported:r.sessions,eventsImported:r.events,errors:[...n.errors,...r.errors]}}async function lL(e,t){let n=e.name.toLowerCase();if(n.endsWith(`.md`)||n.endsWith(`.markdown`))return Lue(await e.text(),t);if(n.endsWith(`.jsonl`))return Rue(await e.text(),t);if(n.endsWith(`.csv`))return zue(await e.text(),t);let r=of,i;try{i=await ZI.default.loadAsync(await e.arrayBuffer())}catch{throw new Nue}let a=[],o=new Set,s=new Set,c=0,l=0,u=Object.keys(i.files).filter(e=>!i.files[e]?.dir),d=u.filter(e=>!e.startsWith(`dist/`)),f=d.some(e=>e.endsWith(`.jsonl`)||e.endsWith(`.csv`)||e.endsWith(`.md`)&&!/(?:^|\/)README\.md$/i.test(e))?d:u,p=f.filter(e=>e.endsWith(`.jsonl`)),m=f.filter(e=>e.endsWith(`.csv`)),h=f.filter(e=>e.endsWith(`.md`)&&!/(?:^|\/)README\.md$/i.test(e));if(p.length===0&&m.length===0&&h.length===0)throw new Pue;let g=[];for(let e of p){let t=await i.files[e].async(`text`);g.push({source:e,parsed:bc(t)})}let _=new Set(p.map(e=>e.replace(/\.jsonl$/i,``)));for(let e of m){if(_.has(e.replace(/\.csv$/i,``)))continue;let t=await i.files[e].async(`text`);g.push({source:e,parsed:dx(t)})}for(let{source:e,parsed:n}of g)for(let r of n.bundles){if(!r.revisions||r.revisions.length===0)continue;let n=r.note?.id??r.revisions[0]?.noteId;try{let e=t.persistenceStorage;if(!e)throw Error(`Revision import requires provider.persistenceStorage`);await t.persistenceReady,await e.saveBlockRevisions(r.revisions)}catch(t){n&&s.add(n),a.push(`${e}: Failed to restore revisions for ${n??`unknown`}: ${t instanceof Error?t.message:String(t)}`)}}for(let e of h)try{let n=rL(await i.files[e].async(`text`),r);if(n.id&&s.has(n.id)){a.push(`Failed to import ${e}: revision restoration failed for ${n.id}`);continue}let c=n.id?await t.getRecord(n.id):null,l=await t.saveRecord({...n,seedOrigin:c?.seedOrigin??`user`,sourceRevision:c?.sourceRevision??n.sourceRevision,blocks:c?.rawContent===n.rawContent?c.blocks:n.blocks});o.add(l.id)}catch(t){a.push(`Failed to import ${e}: ${t instanceof Error?t.message:String(t)}`)}for(let{source:e,parsed:n}of g){a.push(...n.errors.map(t=>`${e}: ${t}`));let r=await cL(n.bundles,t,{skipNotes:o,revisionsRestored:!0,skipBundles:s});for(let e of r.noteIds)o.add(e);c+=r.sessions,l+=r.events,a.push(...r.errors.map(t=>`${e}: ${t}`))}return{imported:o.size,sessionsImported:c,eventsImported:l,errors:a}}async function Bue(){{let e=await fetch(`/api/v1/feed/status`);if(e.ok)return{...await e.json(),mode:`self-hosted`}}return await ZP(),{...await FS(YP),mode:`browser-repo`}}async function uL(e={}){let t=await fetch(`/api/v1/feed/publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Publish failed (HTTP ${t.status})`)}let n=await t.json();return{report:n,feedUrl:n.feedUrl}}var Vue=3e4,Hue=5e3;async function dL(e,t,n){let r=new AbortController,i,a=new Promise((t,a)=>{i=setTimeout(()=>{r.abort(),a(new Fue(e,`Feed repository export timed out during ${e} (${Math.max(1,Math.round(n/1e3))}s).`))},n)});try{return await Promise.race([t(r.signal),a])}finally{i!==void 0&&clearTimeout(i)}}async function fL(e={}){let{stageTimeoutMs:t=Vue,...n}=e;await dL(`storage initialization`,()=>ZP(),t);let r=new QI,i=await dL(`feed compilation`,e=>PS(YP,r,{...n,layout:`repository`,recordCheckpoint:!1,signal:e}),t);return $I(await dL(`zip archive generation`,()=>r.toBlob(),t),`${(n.name??`wod-wiki-feed-repository`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`wod-wiki-feed-repository`}.zip`),await dL(`checkpoint persistence`,()=>NS(YP,i),Math.min(t,Hue)).catch(()=>void 0),i}function Uue(){return typeof window<`u`&&`showDirectoryPicker`in window}async function pL(e={}){let t=window;if(!t.showDirectoryPicker)throw Error(`Directory picker is not supported in this browser; use ZIP export instead.`);let n;try{n=await t.showDirectoryPicker({mode:`readwrite`})}catch{return null}return await ZP(),PS(YP,new koe(n),{...e,layout:`repository`,recordCheckpoint:!0})}var mL=`catalog:`;function hL(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`catalog:`)&&`manifest`in e}function gL(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`feed:index:`)&&`index`in e}function Wue(e){return typeof e==`object`&&!!e&&`key`in e&&typeof e.key==`string`&&e.key.startsWith(`seed:`)}async function _L(e){return e||(await ZP().catch(()=>void 0),YP)}async function vL(e){let t=e??YP;FF()||await ZF(t).catch(()=>void 0)}async function yL(e,t,n){let r={key:`${mL}${e}`,feedId:e,manifest:t,updatedAt:Date.now()};try{let e=await _L(n);if(!e)return;await e.transaction([`meta`],`readwrite`,async e=>{await e.readwrite(`meta`).put(r)})}catch{}}async function bL(e,t){try{let n=await _L(t);if(!n)return;let r=await n.readonly(`meta`).get(`${mL}${e}`);return hL(r)?r.manifest:void 0}catch{return}}async function xL(e,t,n,r){let i={key:gx(e,t),feedId:e,notebookId:t,index:n,updatedAt:Date.now()};try{let e=await _L(r);if(!e)return;await e.transaction([`meta`],`readwrite`,async e=>{await e.readwrite(`meta`).put(i)})}catch{}}async function Gue(e,t,n){try{let r=await _L(n);if(!r)return;let i=await r.readonly(`meta`).get(gx(e,t));return gL(i)?i.index:void 0}catch{return}}function Kue(e){return e.notebooks&&e.notebooks.length>0?e.notebooks:e.chunks.filter(e=>e.id.startsWith(`notebook.`)).map(t=>{let n=Sx(t.id)??t.id.slice(9);return{notebookId:t.id,label:n.replace(/-/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),indexPath:`indexes/notebooks/${t.id}.json`,version:e.version,commit:e.commit??``,builtAt:e.builtAt,sha256:t.sha256,bytes:t.bytes,chunkBytes:t.bytes,count:t.count}})}async function SL(e,t){let n=iI(e)??(e.startsWith(`/`)?sI(e):null);if(!n&&!t?.source)throw Error(`Enter an absolute http(s) URL of a feed directory.`);let r;r=t?.source?await t.source.fetchManifest():await new OS(n).readJson(`manifest.json`);let i=rS(r),a=n??e,o=t?.feedId??xI().find(e=>iI(e.url)===n)?.id;o&&await yL(o,i,t?.storage);let s=Kue(i),c=s.length>0?s.reduce((e,t)=>e+t.count,0):i.chunks.reduce((e,t)=>e+t.count,0),l=i.indexBytes??s.reduce((e,t)=>e+(t.indexBytes??0),0),u=i.chunkBytes??(i.chunks.length>0?i.chunks.reduce((e,t)=>e+(t.bytes??0),0):s.reduce((e,t)=>e+(t.chunkBytes??0),0)),d=aI(i.repositoryUrl??``)??void 0,f;try{f=new URL(a).hostname||`Feed`}catch{f=`Feed`}return{url:a,manifest:i,name:i.name?.trim()||f,...i.description?.trim()?{description:i.description.trim()}:{},...d?{repositoryUrl:d}:{},version:i.version,schema:i.schema,builtAt:i.builtAt,notebooks:s,notebookCount:s.length,itemCount:c,indexBytes:l,chunkBytes:u,hasOfflineChunks:i.chunks.length>0||u>0}}var CL=new Map,wL=new Map,TL=new Map;function EL(e){let t=`remote:${e.feedId}:${e.record.uuid}`;wL.set(t,e),wL.set(e.record.uuid,e),TL.set(e.record.uuid,e)}function DL(e){return wL.get(e)??TL.get(e)}function que(e){let t=/^remote:([^:]+):(.+)$/.exec(e);return t?{feedId:t[1],uuid:t[2]}:{uuid:e}}function OL(e,t){if(t){let n=new TextEncoder;return{async read(e){if(/\.md$/i.test(e)&&t.fetchText)return n.encode(await t.fetchText(e));let r=await t.fetchChunk(e);return n.encode(JSON.stringify(r))},async readText(n){if(t.fetchText)return t.fetchText(n);if(/\.json$/i.test(n))return JSON.stringify(await t.fetchChunk(n));throw Error(`Feed source for ${e.feedId} cannot read text '${n}'`)},async stat(){}}}return new OS(e.feedUrl)}function kL(e,t){if(e)return wI(e);let n=/^markdown\/notebooks\/([^/]+)\//.exec(t??``);return n?.[1]?wI(n[1]):`workouts`}function AL(e){return e.title?.trim()?e.title.trim():(e.path.split(`/`).at(-1)??e.path).replace(/\.md$/i,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}async function jL(e,t){let n=typeof e==`string`?{noteId:e}:e,r=n.noteId??n.uuid;if(r){let e=DL(r);if(e)return{entry:e,canonicalUuid:e.record.uuid,requestedFeedId:e.feedId}}let i=n.noteId?que(n.noteId):{feedId:n.feedId,uuid:n.uuid},a=n.uuid??i.uuid,o=n.feedId??i.feedId,s=n.feedUrl??(o?_I(o)?.url:void 0);if(n.record||(n.recordPath||n.rawUrl||n.path)&&(s||t?.source)){let e=n.record??{uuid:a??``,path:n.path??n.recordPath??n.rawUrl??``,...n.recordPath?{recordPath:n.recordPath}:{},...n.rawUrl?{rawUrl:n.rawUrl}:{},commit:``,version:n.version??1,sha256:``,...n.title?{title:n.title}:{},...n.date===void 0?{}:{date:n.date}};if(o||s||t?.source){let t=o??`remote`,r={feedId:t,feedUrl:s??``,notebookSlug:n.notebookSlug??kL(n.notebookId,e.path),record:e};return e.uuid&&EL(r),{entry:r,canonicalUuid:e.uuid||a,requestedFeedId:t}}}let c=await _L(t?.storage);if(c&&a)try{let e=await c.readonly(`meta`).getAll();for(let t of e){if(!gL(t)||o&&t.feedId!==o)continue;let e=t.index.records.find(e=>e.uuid===a);if(!e)continue;let n=s??_I(t.feedId)?.url??``,r={feedId:t.feedId,feedUrl:n,notebookSlug:kL(t.notebookId,e.path),record:e};return EL(r),{entry:r,canonicalUuid:e.uuid,requestedFeedId:t.feedId}}}catch{}if(o&&(s||t?.source)&&a)try{let e=OL({feedId:o,feedUrl:s??``,notebookSlug:`workouts`,record:{uuid:a,path:``,commit:``,version:1,sha256:``}},t?.source),n=c?await bL(o,c):void 0;!n&&t?.source?n=rS(await t.source.fetchManifest()):!n&&s&&(n=rS(await new OS(s).readJson(`manifest.json`)));for(let t of n?.notebooks??[]){let n=await tC(e,t.indexPath);c&&await xL(o,t.notebookId,n,c);for(let e of n.records)EL({feedId:o,feedUrl:s??``,notebookSlug:kL(t.notebookId,e.path),record:e});let r=DL(a);if(r)return{entry:r,canonicalUuid:r.record.uuid,requestedFeedId:o}}}catch{}return{entry:void 0,canonicalUuid:a,requestedFeedId:o}}function Jue(e){return{path:e.sourcePath??`${e.id}.md`,content:e.rawContent,blocks:e.blocks,blockIndex:[],blockEfforts:[],blockEquipment:[],commit:e.seedCommit,uuid:e.id,version:e.seedVersion}}async function ML(e,t={}){let{entry:n,canonicalUuid:r,requestedFeedId:i}=await jL(e,t),a=await _L(t.storage);if(a&&r&&!t.forceRefresh)try{let e=await a.readonly(`notes`).get(r);if(e){let t=e.seedOrigin!==`seed`&&e.feedOrigin!==`feed`&&!e.retention,r=n?.record.version??0,a=e.seedVersion??0,o=e.retention===`cached`&&e.rawContent.length>0&&(r===0||a>=r);if(t||e.retention===`session-pinned`||e.retention===`schedule-pinned`||o){let t=Jue(e),r=e.feedSourceId??i;return{note:e,seedRow:t,row:t,feedId:r,...n?{notebookSlug:n.notebookSlug,record:n.record}:{},...r?{remoteNoteId:`remote:${r}:${e.id}`}:{},canonicalNoteId:e.id,fromCache:!0}}}}catch{}if(!n)return;let o=await nC(OL(n,t.source),n.record,{fetchImpl:t.fetchImpl});if(a&&t.cache!==!1){let e=await iC(a,{feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,seedRow:o,retention:`cached`,upstreamStatus:`live`});return{note:e,seedRow:o,row:o,feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,remoteNoteId:`remote:${n.feedId}:${e.id}`,canonicalNoteId:e.id,fromCache:!1}}let s=n.record.uuid||o.uuid||r||o.path;return{note:{id:s,title:n.record.title||o.blockIndex[0]?.noteTitle||AL(n.record),rawContent:o.content,sourceRevision:1,blocks:o.blocks,...n.record.date===void 0?{}:{date:n.record.date},createdAt:n.record.date??0,notebookId:`notebook/${n.notebookSlug}`,feedOrigin:`feed`,feedSourceId:n.feedId,seedOrigin:`seed`,seedChunkId:`notebook.${n.notebookSlug}`,seedVersion:n.record.version??o.version??1,sourcePath:o.path,retention:`cached`,upstreamStatus:`live`},seedRow:o,row:o,feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,remoteNoteId:`remote:${n.feedId}:${s}`,canonicalNoteId:s,fromCache:!1}}async function NL(e,t={}){let{entry:n}=await jL(e,t);if(!n)return;let r=await nC(OL(n,t.source),n.record,{fetchImpl:t.fetchImpl});if(t.cache!==!1)try{let e=await _L(t.storage);e&&await iC(e,{feedId:n.feedId,notebookSlug:n.notebookSlug,record:n.record,seedRow:r,retention:`cached`,upstreamStatus:`live`})}catch{}return r}async function Yue(e,t,n={}){let{entry:r}=await jL(e,n);if(!r)throw Error(`Remote record metadata not found for ${e}`);let i=await _L(n.storage);if(!i)throw Error(`Storage is not ready for cloning remote record`);return Ioe(i,OL(r,n.source),{feedId:r.feedId,record:r.record,targetNotebookId:t,sourceNotebookId:`notebook/${r.notebookSlug}`})}async function PL(e,t,n){try{return(await SL(t,{feedId:e,storage:n})).manifest}catch{return}}function FL(e,t){let n=e.label.trim();if(!n)return t?.name?.trim()||e.id;if(e.tier===`imported`&&t?.name?.trim()){let r;try{r=new URL(e.url).hostname}catch{r=``}if(n===`Source`||n===e.url||r&&n===r)return t.name.trim()}return n}var IL=`a Wod.Wiki community seed source`;function LL(e,t){let n=e.description?.trim()||void 0;if(n&&!n.includes(IL))return n;let r=t?.description?.trim()||void 0;return r&&!r.includes(IL)?r:n??r}async function RL(){let e=new Map,t=new Map,n=new Map;try{await ZP().catch(()=>void 0),await vL();let r=await YP.readonly(`meta`).getAll();for(let i of r)if(hL(i))e.set(i.feedId,i.manifest);else if(Wue(i))t.set(i.key,i);else if(gL(i)){n.set(i.key,i.index);let e=_I(i.feedId)?.url??``,t=Sx(i.notebookId)??wI(i.notebookId);for(let n of i.index.records)EL({feedId:i.feedId,feedUrl:e,notebookSlug:t,record:n})}}catch{}return{catalogs:e,checkpoints:t,indexes:n}}async function zL(){await ZP().catch(()=>void 0),await vL();let[e,t,n,{catalogs:r,checkpoints:i,indexes:a}]=await Promise.all([jI.getAllNotebooks().catch(()=>[]),YP.readonly(`notes`).getAll().catch(()=>[]),YP.readonly(`notebook_links`).getAll().catch(()=>[]),RL()]),o=new Map(t.map(e=>[e.id,e])),s=Ms(t,n,Hy),c=[],l=new Set;for(let t of e){if(t.origin!==`user`&&t.origin!=="default")continue;let e=o.get(`notebook/${t.slug}`),n=`${t.origin==="default"?`core`:`local`}#${t.slug}`;l.add(n),c.push({id:t.id,feedId:t.origin==="default"?`core`:`local`,feedLabel:t.origin==="default"?`Core`:`Yours (Local)`,chunkId:`notebook.${t.slug}`,slug:t.slug,label:t.name,description:t.description,category:t.origin,count:s.get(Cs(t.slug))??0,subscribed:!0,installed:!0,origin:t.origin,public:e?.public===!0,icon:t.icon})}for(let e of xI()){let t=r.get(e.id),n=i.get(bx(e.id)),o=FL(e,t);if(t?.notebooks&&t.notebooks.length>0)for(let r of t.notebooks){let i=Sx(r.notebookId)??wI(r.notebookId),s=`${e.id}#${i}`;if(l.has(s))continue;l.add(s);let u=n?.chunks?.[r.notebookId],d=a.get(gx(e.id,r.notebookId));c.push({id:`${e.id}:${r.notebookId}`,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.notebookId,slug:i,label:r.label,description:t.description??e.description,category:r.category,count:r.count,version:r.version,commit:r.commit,sha256:r.sha256,updatedAt:r.updatedAt,builtAt:r.builtAt,indexPath:r.indexPath,subscribed:HI(e.id,r.notebookId),installed:!!(u||d),origin:`feed`})}else if(t)for(let r of t.chunks){if(!r.id.startsWith(`notebook.`))continue;let i=Sx(r.id)??r.id.slice(9),s=`${e.id}#${i}`;if(l.has(s))continue;l.add(s);let u=n?.chunks?.[r.id],d=a.get(gx(e.id,r.id));c.push({id:`${e.id}:${r.id}`,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.id,slug:i,label:i.replace(/-/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),description:t.description??e.description,count:r.count,version:t.version,sha256:r.sha256,builtAt:t.builtAt,indexPath:`indexes/notebooks/${r.id}.json`,subscribed:HI(e.id,r.id),installed:!!(u||d),origin:`feed`})}else{let t=CI(e.id);for(let r of t){let t=wI(r.chunkId||r.id),i=`${e.id}#${t}`;if(l.has(i))continue;l.add(i);let s=n?.chunks?.[r.chunkId],u=a.get(gx(e.id,r.chunkId));c.push({id:r.id,feedId:e.id,feedLabel:o,feedUrl:e.url,chunkId:r.chunkId,slug:t,label:r.label,description:r.description,category:r.category,count:u?.count??s?.noteIds?.length??0,indexPath:`indexes/notebooks/${r.chunkId}.json`,subscribed:HI(e.id,r.chunkId),installed:!!(s||u),origin:`feed`})}}}return c}var BL={async getAllFeeds(){let[{catalogs:e,checkpoints:t},n]=await Promise.all([RL(),Bue().catch(()=>({hasPublicContent:!1,publishedVersion:null,builtAt:null,dirty:!1,publicNotebooks:0,publicNotes:0,publicSessions:0,changes:[],mode:`self-hosted`}))]),r=[],i=n.feedUrl??(typeof window<`u`?`${window.location.origin}/feed/`:`wod-wiki-feed-repository (.zip / folder)`);r.push({id:`local`,label:`My Published Feed`,url:i,description:n.publicNotebooks>0?`Publishes ${n.publicNotebooks} public notebook(s), ${n.publicNotes} note(s), and ${n.publicSessions} opted-in session(s).`:`Mark any user-owned notebook as Public to publish via self-hosted server or export a wod-wiki-feed-repository.`,tier:`local`,subscribed:!0,installed:!0,notebookCount:n.publicNotebooks,itemCount:n.publicNotes,localVersion:n.publishedVersion??void 0,remoteVersion:n.publishedVersion??void 0,unpublishedChanges:n.dirty,builtAt:n.builtAt??void 0});let a=[mI,...xI()];for(let n of a){let i=e.get(n.id),a=t.get(bx(n.id)),o=n.id===`core`||BI(n.id),s=(a?.seedVersion??0)>0,c=CI(n.id),l=i?.notebooks?i.notebooks.length:i?i.chunks.filter(e=>e.id.startsWith(`notebook.`)).length:c.length,u=a?Object.values(a.chunks??{}).reduce((e,t)=>e+(Array.isArray(t?.noteIds)?t.noteIds.length:0),0):0,d=i?.notebooks?i.notebooks.reduce((e,t)=>e+t.count,0):i?i.chunks.reduce((e,t)=>e+t.count,0):0,f=a?.seedVersion||void 0,p=i?.version,m=!!(o&&f&&p&&p>f);r.push({id:n.id,label:FL(n,i),url:n.id===`core`?sI(oI):n.url,repositoryUrl:i?.repositoryUrl??n.repositoryUrl,description:LL(n,i),tier:n.id===`core`?`core`:n.tier??`imported`,subscribed:o,installed:s,notebookCount:l,itemCount:d||u,localVersion:f,remoteVersion:p,updateAvailable:m,builtAt:i?.builtAt??a?.builtAt})}return r},getAllNotebooks:zL,async getRemoteNotebookNotes(e,t){let n=wI(e),r=`notebook.${n}`,i=await zL(),a=t??(typeof window<`u`?new URLSearchParams(window.location.search).get(`feed`)??void 0:void 0),o=i.find(e=>e.origin===`feed`&&e.slug===n&&(!a||e.feedId===a));if(!o&&a){let e=_I(a);e?.url&&(await PL(a,e.url),o=(await zL()).find(e=>e.origin===`feed`&&e.slug===n&&e.feedId===a))}if(!o){let e=dI();for(let t of e)await PL(t.id,t.url);e.length>0&&(o=(await zL()).find(e=>e.origin===`feed`&&e.slug===n))}let s=o?.feedUrl??(a?_I(a)?.url:void 0),c=o?.feedId??a;if(!s||!c)return[];let l=o?.indexPath??`indexes/notebooks/${r}.json`,u=`${s}#${l}@${o?.sha256??`latest`}`,d=CL.get(u);if(!d){let e=await Gue(c,r);e&&(!o?.sha256||e.sha256===o.sha256)&&(d=e,CL.set(u,d))}if(!d)try{d=await tC(new OS(s),l),CL.set(u,d),await xL(c,r,d)}catch{return[]}return d.records.map(e=>{EL({feedId:c,feedUrl:s,notebookSlug:n,record:e});let t=`remote:${c}:${e.uuid}`,i=e.path.replace(/^markdown\/notebooks\/[^/]+\//,``).replace(/\.md$/i,``);return{id:t,title:AL(e),rawContent:``,sourceRevision:1,blocks:{},...e.date===void 0?{}:{date:e.date},createdAt:e.date??0,notebookId:`notebook/${n}`,sourceId:`notebook:${n}/${i}`,sourcePath:e.path,feedOrigin:`feed`,feedSourceId:c,seedOrigin:`seed`,seedChunkId:r,seedVersion:e.version,tags:[`preview:remote`]}})}};function Xue(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 Zue(e){let t=Date.now();if(!Xue(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}}}var VL=new Set;function Que(e){VL.add(e)}function HL(e){VL.delete(e)}function UL(e){return VL.has(e)}function WL(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:Fy(t)}}var GL={registeredWidgets:Ns},KL=new Map,qL=[`notes`,`block_revisions`,`note_revisions`,`schedule_items`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`notebook_links`];function JL(e){return[...e].sort((e,t)=>t.createdAt-e.createdAt)}function YL(e,t){return t==null?e:e.slice(0,t)}function XL(e){return new Date(`${e}T12:00:00`).getTime()}function ZL(e){let t=ls(e.links,e.pages),n=us(t),r=t.find(e=>e.date!==void 0)?.date,i=r===void 0?NaN:XL(r);return{id:e.note.id,title:e.note.title,slug:n.pageSlug,pageId:n.pageId,journalDate:n.journalDate??(e.note.type===`journal`&&e.note.date!==void 0?Fw(new Date(e.note.date)):void 0),placements:t,createdAt:e.note.createdAt,updatedAt:e.note.createdAt,targetDate:e.note.date??(Number.isFinite(i)?i: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,notebookId:e.note.notebookId,notebookIds:e.note.notebookIds,provenance:e.note.provenance,seedOrigin:e.note.seedOrigin,schemaVersion:1}}function QL(e){return{id:e.id,title:e.title,journalDate:e.type===`journal`&&e.date!==void 0?Fw(new Date(e.date)):void 0,createdAt:e.createdAt,updatedAt:e.createdAt,targetDate:e.date??e.createdAt,rawContent:e.rawContent,blocks:e.blocks,sourceRevision:e.sourceRevision,tags:e.tags??[],type:e.type??`note`,sourceId:e.sourceId,notebookId:e.notebookId,notebookIds:e.notebookIds,provenance:e.provenance,seedOrigin:e.seedOrigin,schemaVersion:1}}function $ue(e){if(e?.dateRange)return e.dateRange;if(e?.daysBack!=null){let t=Date.now();return{start:t-e.daysBack*864e5,end:t}}}var $L=class e{storage;contentProviderOverride;mode=`history`;capabilities={canWrite:!0,canDelete:!0,canFilter:!0,canMultiSelect:!0,supportsHistory:!0};constructor(e=X,t){this.storage=e,this.contentProviderOverride=t}get persistenceStorage(){return this.storage}get provider(){return this.contentProviderOverride??this}async createNote(e){if(await this.provider.persistenceReady,HL(e.id),await this.storage.getNote(e.id))throw Error(`Note already exists: ${e.id}`);return this.provider.saveRecord({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,...e.notebookIds===void 0?{}:{notebookIds:e.notebookIds}})}async getNote(e,t={}){await this.provider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new AT(`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.provider.getRecord(n.id);if(!o)throw new AT(`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.provider.getRecords(e);if(e.journalDate&&(t=t.filter(t=>t.placements&&t.placements.length>0?t.placements.some(t=>t.date===e.journalDate):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.offset||e.limit)&&(t=t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))),e.projection===`history-detail`&&(t=await Promise.all(t.map(e=>this.getNote(e.id,{projection:`history-detail`,resultSelection:{mode:`all-for-note`}})))),t}async mutateNote(t,n){await this.provider.persistenceReady;let r=await this.resolveNote(t);if(!r)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(t)}`);if(n.expectedSourceRevision!==void 0&&n.expectedSourceRevision!==r.sourceRevision)throw new AT(`STALE_SOURCE`,`Note ${r.id} changed since it was loaded`);let i=n.attachments?.add?await Promise.all(n.attachments.add.map(e=>Zue(e))):[];return await this.storage.withTransaction([...qL,`attachments`],async t=>{let a=new e(t);if(await a.updateRecord(r.id,{...n.metadata,rawContent:n.rawContent,blocks:n.blocks,expectedSourceRevision:n.expectedSourceRevision,results:n.workoutResult?.data,blockId:n.workoutResult?.blockId,blockVersion:n.workoutResult?.blockVersion,blockContentId:n.workoutResult?.blockContentId,origin:n.workoutResult?.origin,resultId:n.workoutResult?.id}),n.rawContent!==void 0&&n.rawContent!==r.rawContent){let e=await a.getRecord(r.id);await Zw(r.id,n.rawContent,t,{targetDate:e?.targetDate})}for(let e of i)await t.saveAttachment({...e,id:e.id??Br(),noteId:r.id,resultId:n.workoutResult?.id,createdAt:Date.now()});for(let e of n.attachments?.remove??[])await t.deleteAttachment(e)}),this.getNote(r.id,{includeAttachments:!!n.attachments})}async saveNote(e){if(await this.provider.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 AT(`STALE_SOURCE`,`Note ${e.noteId} no longer exists`);return this.provider.saveRecord({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,r){if(await this.provider.persistenceReady,n.noteId!==t.noteId)throw new AT(`RESULT_NOTE_MISMATCH`,`Session belongs to another Note`);let i=SC(t.noteId),a=i.isRemote?i.uuid:t.noteId,o=await this.storage.getNote(a)??(a===t.noteId?void 0:await this.storage.getNote(t.noteId));if(i.isRemote||o&&(!Os(o,Wy(o),Uy(o))||Ds(o,Wy(o),Uy(o)).kind!==`user`)){let e;if(!o&&i.isRemote){let n=await NL(t.noteId).catch(()=>void 0),r=DL(t.noteId);n?e={row:n,canonicalNoteId:r?.record.uuid??i.uuid,remoteNoteId:t.noteId,feedId:r?.feedId??i.feedId,notebookSlug:r?.notebookSlug,record:r?.record}:t.rawContent?.trim()&&(e={id:i.uuid,title:t.metadata?.title,rawContent:t.rawContent,blocks:t.blocks,feedSourceId:r?.feedId??i.feedId,sourceNotebookId:r?.notebookSlug?`notebook/${r.notebookSlug}`:void 0})}let r=n.sessionDate??Fw(new Date(n.createdAt||n.startTime||Date.now())),a=await FC(this.storage.storage,{noteId:o?o.id:t.noteId,blockId:n.blockId,...n.blockContentId?{blockContentId:n.blockContentId}:{},sessionId:n.id,journalDate:r,startedAt:n.startTime,...n.scheduleItemId?{scheduleItemId:n.scheduleItemId}:{},origin:n.origin,...e?{remotePayload:e}:{}});return KL.set(a.session.id,a.session),{note:a.note,revision:a.revision,session:a.session}}return this.storage.withTransaction([`notes`,`block_revisions`,`note_revisions`,`schedule_items`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`sessions`,`events`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`notebook_links`],async i=>{await new e(i).saveNote(t);let a=await i.getNote(t.noteId),o=a?.blocks[n.blockId];if(!a||!o||o.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Selected workout is not in the saved Note`);let s=await i.getBlockRevision(a.id,o.id,o.version);if(!s)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Selected workout revision is missing`);if(await i.getSessionById(n.id)||KL.has(n.id))throw Error(`Session already exists: ${n.id}`);let c=zs(s.rawContent,GL).find(e=>e.scriptBlock),l=n.sessionDate??Fw(new Date(n.createdAt||n.startTime||Date.now())),u=n.notebookIds?.length?n.notebookIds:a.notebookIds&&a.notebookIds.length>0?a.notebookIds:void 0,d={...n,blockId:o.id,blockVersion:s.version,blockContentId:c?.scriptBlock?.contentId,noteSourceRevision:n.noteSourceRevision??a.sourceRevision,sessionDate:l,status:`in-progress`,...u?{notebookIds:u}:{}};return r?.deferPersist?KL.set(d.id,d):await i.saveSession(d),{note:a,revision:s,session:d}})}async finishSession(e,t,n,r){await this.provider.persistenceReady;let i=await this.storage.withTransaction([`sessions`,`notes`,`block_revisions`,`events`,`notebook_links`,`schedule_items`],async i=>{let a=await i.getSessionById(e)??KL.get(e);if(!a&&r?.noteId&&r?.blockId){let o=SC(r.noteId),s=o.isRemote?o.uuid:r.noteId,c=await i.getNote(s)??(s===r.noteId?void 0:await i.getNote(r.noteId)),l=c?.id??s,u=c?Object.values(c.blocks).filter(e=>e.kind===`wod`):[],d=c?.blocks[r.blockId]??(r.blockContentId?u.find(e=>zs(c?.rawContent.slice(e.from,e.to)??``,GL).find(e=>e.scriptBlock)?.scriptBlock?.contentId===r.blockContentId):void 0)??(u.length===1?u[0]:void 0),f=d?.id??r.blockId,p=r.blockVersion??d?.version,m=p===void 0?void 0:await i.getBlockRevision(l,f,p);if(m||=(await i.getBlockHistory(l,f)).reduce((e,t)=>!e||t.version>e.version?t:e,void 0),!m&&d&&c&&(m=await i.getBlockRevision(c.id,d.id,d.version)),!m&&(d||r.blockContent!==void 0)){let e=d&&c&&typeof d.from==`number`&&typeof d.to==`number`?c.rawContent.slice(d.from,d.to):r.blockContent??``,a=d?.dialect??r.blockDialect,o=a===`log`?`log`:a===`time`?`time`:void 0,s={noteId:l,blockId:f,version:p??1,kind:`wod`,rawContent:e,savedAt:n??t.endTime??Date.now(),...o?{dialect:o}:{},...d?.sport??r.blockSport?{sport:d?.sport??r.blockSport}:{}};await i.storage.readwrite(`block_revisions`).put(s),m=s}if(m){let i=zs(m.rawContent,GL).find(e=>e.scriptBlock),o=r.sessionDate??Fw(new Date(t.endTime||t.startTime||n||Date.now())),s=c?.notebookIds&&c.notebookIds.length>0?c.notebookIds:void 0;a={id:e,noteId:m.noteId,blockId:m.blockId,blockVersion:m.version,blockContentId:r.blockContentId??i?.scriptBlock?.contentId,noteSourceRevision:c?.sourceRevision,origin:r.origin??`journal`,...r.scheduleItemId?{scheduleItemId:r.scheduleItemId}:{},sessionDate:o,startTime:t.startTime,endTime:t.endTime,duration:t.duration??0,completed:t.completed,status:`in-progress`,createdAt:n??t.endTime??Date.now(),...s?{notebookIds:s}:{}}}}if(!a)throw new AT(`RESULT_NOT_FOUND`,`Session not found: ${e}`);let o=await i.getBlockRevision(a.noteId,a.blockId,a.blockVersion);if(!o&&r?.blockContent!==void 0){let e=r.blockDialect===`log`?`log`:r.blockDialect===`time`?`time`:void 0,s={noteId:a.noteId,blockId:a.blockId,version:a.blockVersion,kind:`wod`,rawContent:r.blockContent,savedAt:n??t.endTime??Date.now(),...e?{dialect:e}:{},...r.blockSport?{sport:r.blockSport}:{}};await i.storage.readwrite(`block_revisions`).put(s),o=s}if(!o)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision is missing`);let s=a.sessionDate??Fw(new Date(t.endTime||t.startTime||a.createdAt||Date.now())),c={...a,sessionDate:s,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??a.createdAt};if(await i.saveSession(c),c.scheduleItemId)try{let e=i.storage.readwrite(`schedule_items`),t=await e.get(c.scheduleItemId);t&&t.status!==`completed`&&await e.put({...t,status:`completed`,updatedAt:c.endTime||Date.now()})}catch{}let l=c.notebookIds??[];if(l.length>0){let e=l.map(e=>({id:`${e}:session:${c.id}`,notebookId:e,targetKind:`session`,targetId:c.id,noteId:c.noteId,createdAt:c.createdAt}));await i.storage.readwrite(`notebook_links`).putMany(e)}if(t.logs?.length){let e={noteId:c.noteId,resultId:c.id,blockId:c.blockId,blockVersion:c.blockVersion,blockContentId:c.blockContentId,origin:c.origin,pageId:c.pageId,workoutTimestamp:c.endTime};await i.appendEvents(jy(t.logs,e)),await i.finalizeSummaries(c.id,My(t.logs,e))}return c});return KL.delete(e),i}async getBlockRevision(e,t,n){return await this.provider.persistenceReady,this.storage.getBlockRevision(e,t,n)}async getBlockHistory(e,t){return await this.provider.persistenceReady,this.storage.getBlockHistory(e,t)}async getNoteBlockHistory(e){return await this.provider.persistenceReady,this.storage.getNoteBlockHistory(e)}async deleteNote(e){await this.provider.persistenceReady;let t=await this.resolveNote(e);if(!t)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);await this.provider.deleteRecord(t.id)}async getSessionById(e){return await this.provider.persistenceReady,this.storage.getSessionById(e)}async rederiveResultAnalytics(e){await this.provider.persistenceReady;let t=await this.storage.getSessionById(e);if(!t)throw new AT(`RESULT_NOT_FOUND`,`Result not found: ${e}`);let n=await this.storage.getBlockRevision(t.noteId,t.blockId,t.blockVersion),r=n&&zs(n.rawContent).find(e=>e.scriptBlock)?.scriptBlock;if(!r||n?.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Cannot re-derive result ${e}: pinned workout revision is missing`);let i={...r,results:void 0,id:t.blockId,version:t.blockVersion,dialect:n.dialect,sport:n.sport,widgetIds:{},statements:nu().read(r.content,n.sport).statements},a=this.storage.getEventsByResult?await this.storage.getEventsByResult(e):[],o=nT(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(jy(o,e)),await n.finalizeSummaries(t.id,My(o,e))})}return t}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`)),YL(JL(n),t.limit)}async selectLocalCandidateIds(e,t){let n=null,r=null,i=e=>{if(n===null){n=new Set(e);return}let t=new Set;for(let r of e)n.has(r)&&t.add(r);n=t};if(e?.journalDate&&(i(await this.storage.getNoteIdsForJournalDate(e.journalDate)),n.size===0))return{candidateIds:[],loadedNotes:r};if(e?.tags&&e.tags.length>0){for(let t of e.tags)if(i(await this.storage.getNoteIdsForTag(t)),n.size===0)return{candidateIds:[],loadedNotes:r}}if(e?.kind&&e.kind!==`note`&&n===null){let t=await this.storage.getNotesByType(e.kind);if(r=new Map(t.map(e=>[e.id,e])),i(t.map(e=>e.id)),n.size===0)return{candidateIds:[],loadedNotes:r}}if(t){let e=new Set,a=(await this.storage.getAllPages()).filter(e=>{if(!e.date)return!1;let n=XL(e.date);return Number.isFinite(n)&&n>=t.start&&n<=t.end});if(a.length>0){let t=await Promise.all(a.map(e=>this.storage.getPageNotes(e.id)));for(let n of t)for(let t of n)e.add(t.noteId)}if(n===null){let a=await this.storage.getNotesByDateRange(t.start,t.end),o=new Set(a.map(e=>e.id));for(let t of e)o.add(t);if(e.size===0&&(r=new Map(a.map(e=>[e.id,e]))),i([...o]),n.size===0)return{candidateIds:[],loadedNotes:r}}else{let a=[...n];if(!r){let e=await this.storage.getNotesByIds(a);r=new Map(e.map(e=>[e.id,e]))}let o=[];for(let n of a){let i=r.get(n);if(!i)continue;let a=i.date??i.createdAt;(a>=t.start&&a<=t.end||e.has(n))&&o.push(n)}if(i(o),n.size===0)return{candidateIds:[],loadedNotes:r}}}if(n===null){let e=await this.storage.getAllNotes();if(r=new Map(e.map(e=>[e.id,e])),i(e.map(e=>e.id)),n.size===0)return{candidateIds:[],loadedNotes:r}}let a=[...n],o=e?.search?.toLowerCase();if((e?.kind||o)&&!r){let e=await this.storage.getNotesByIds(a);r=new Map(e.map(e=>[e.id,e]))}if(r&&(e?.kind||o)){let t=[];for(let n of a){let i=r.get(n);i&&(e?.kind&&(i.type??`note`)!==e.kind||o&&!i.title.toLowerCase().includes(o)&&!i.rawContent.toLowerCase().includes(o)||t.push(n))}return{candidateIds:t,loadedNotes:r}}return{candidateIds:a,loadedNotes:r}}async getRecords(e){let t=$ue(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]});e?.kind&&e.kind!==`note`&&n.push({field:`type`,values:[e.kind]}),e?.search?.trim()&&n.push({field:`text`,value:e.search.trim()});let r=e?.projection===`history-detail`||e?.projection===`workbench`,i=!!e?.journalDate||!!e?.tags?.length||!!t,a=!r&&!i,o=e?.limit!==void 0&&!e?.journalDate&&e?.kind!==`note`&&!t&&!e?.tags?.length?(e?.offset??0)+e.limit:void 0,s={plan:a?`notes`:`detail`,...n.length?{selection:n}:{},order:[{field:`date`,direction:`desc`},{field:`createdAt`,direction:`desc`}],...o===void 0?{}:{offset:0,limit:o}},c=await this.storage.queryDomain(s),l;if(c?.plan===`detail`)l=c.rows.map(ZL);else if(c?.plan===`notes`)l=c.rows.map(QL);else{let n=await this.selectLocalCandidateIds(e,t),r=n.candidateIds,i=n.loadedNotes;if(r.length===0)return[];if(o!==void 0&&r.length>o){if(!i){let e=await this.storage.getNotesByIds(r);i=new Map(e.map(e=>[e.id,e]))}let e=i;r=[...r].sort((t,n)=>{let r=e.get(t),i=e.get(n);return(i?.date??i?.createdAt??0)-(r?.date??r?.createdAt??0)}).slice(0,o)}l=a?(i?r.map(e=>i.get(e)).filter(e=>e!==void 0):await this.storage.getNotesByIds(r)).map(QL):[...(await this.storage.getDetailBatches(r)).values()].map(ZL)}return l=l.filter(n=>(!t||n.targetDate>=t.start&&n.targetDate<=t.end)&&(e?.tags??[]).every(e=>n.tags.includes(e))),l.sort((e,t)=>t.targetDate-e.targetDate)}async getRecord(e){let t=await this.resolveStoredNote(e);if(!t)return null;let n=(await this.storage.getDetailBatches([t.id])).get(t.id);if(!n)return null;let r=ZL(n),i=(await this.storage.getSessionsForNote(t.id)).sort((e,t)=>t.createdAt-e.createdAt)[0],a=zs(t.rawContent,GL).map(e=>{let n=Object.values(t.blocks).find(t=>t.from===e.from&&t.to===e.to);return n?{...e,id:n.id,version:n.version,scriptBlock:e.scriptBlock?{...e.scriptBlock,id:n.id,version:n.version}:void 0}:e});return{...r,sections:a,results:i?WL(i,await this.storage.getEventsByResult(i.id)):void 0}}async cloneRecord(e,t){let n=await this.getRecord(e);if(!n)throw Error(`Source entry not found: ${e}`);let r=t??Date.now();return this.saveRecord({title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:r,journalDate:Fw(new Date(r)),type:`journal`,sourceId:n.id})}async saveRecord(t){let n=Date.now(),r=t.id??(t.type===`playground`?Vw(n):Br());if(!t.id&&t.type===`playground`){let e=r;for(let t=1;await this.storage.getNote(r);t++){if(t>100)throw Error(`Unable to allocate unique playground timestamp ID`);r=`${e}-${t}`}}await this.storage.withTransaction([...qL],async n=>{let i=await n.getNote(r),a=i?t.sourceRevision:0;if(a===void 0)throw new AT(`STALE_SOURCE`,`An expected source revision is required for ${r}`);let o=new e(n),s=await o.changedManualTags(r,t.tags),c=t.blocks??(i?.rawContent===t.rawContent?i.blocks:Vs(t.rawContent,{...GL,sourceRevision:a||1}));await n.saveNoteSource({noteId:r,rawContent:t.rawContent,blocks:c,expectedSourceRevision:a,createdAt:t.createdAt,metadata:{title:t.title,type:t.type,tags:s,targetDate:t.targetDate,sourceId:t.sourceId}}),await o.updateRelationships(r,{journalDate:t.journalDate,slug:t.slug}),await o.updateTags(r,t.rawContent,s);let l=await n.getNote(r);if(l){let e=t.seedOrigin??i?.seedOrigin??`user`,a=l.id.startsWith(`notebook/`)||l.id.startsWith(`effort/`)||l.id.startsWith(`equipment/`)||l.id.startsWith(`t/`);if(e===`seed`||l.feedOrigin===`feed`||a)l.seedOrigin!==e&&await n.saveNote({...l,seedOrigin:e});else{let a=t.notebookIds!==void 0||t.notebookId!==void 0,o=[...t.notebookIds??[],...t.notebookId?[t.notebookId]:[]].map(e=>e.trim()).filter(Boolean).map(e=>Cs(e)).filter(e=>!bs(e)),s=a&&t.notebookIds!==void 0?[]:(i?.notebookIds??[]).filter(Boolean).map(e=>Cs(e)).filter(e=>!bs(e)),c=Array.from(new Set([...l.type===`playground`||l.sourceId===`playground`?[`notebook/playground`]:[],...s,...o])),u=c.find(e=>e!==`notebook/playground`)??c[0],d={...l,seedOrigin:e,notebookIds:c,...u?{notebookId:u}:{notebookId:void 0}};Vx(l,d)||await n.saveNote(d);try{let e=n.storage.readwrite(`notebook_links`),i=await e.getAllFromIndex(`by-note`,r),a=new Set(c),o=new Set(i.filter(e=>e.targetKind===`note`&&e.targetId===r).map(e=>Cs(e.notebookId)));if(t.notebookIds!==void 0)for(let t of i)t.targetKind===`note`&&t.targetId===r&&!a.has(Cs(t.notebookId))&&await e.delete(t.id);let s=Date.now(),l=c.filter(e=>!o.has(e)).map(e=>({id:IS(e,`note`,r),notebookId:e,targetKind:`note`,targetId:r,noteId:r,createdAt:s}));l.length>0&&await e.putMany(l)}catch{}}}});let i=await this.getRecord(r);if(!i)throw Error(`Saved note disappeared: ${r}`);return i}async updateRecord(t,n){let r=await this.resolveStoredNote(t);if(!r)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${t}`);await this.storage.withTransaction([...qL],async t=>{let i=await t.getNote(r.id);if(!i)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${r.id}`);let a=n.rawContent??i.rawContent,o=i.id.startsWith(`remote:`)||i.retention===`indexed`||i.retention===`session-pinned`||i.retention===`cached`||i.feedOrigin===`feed`||i.upstreamStatus===`unsubscribed`||i.upstreamStatus===`removed`;if(n.rawContent!==void 0&&n.rawContent!==i.rawContent&&o){let e=Ds(i,Wy(i),Uy(i));if(!e.editable)throw Error(`Note '${i.id}' is read-only (${e.kind}) and cannot be edited directly.`)}if(n.rawContent!==void 0&&n.expectedSourceRevision===void 0)throw new AT(`STALE_SOURCE`,`An expected source revision is required for ${i.id}`);let s=n.expectedSourceRevision??i.sourceRevision,c=new e(t),l=n.tags===void 0?void 0:await c.changedManualTags(i.id,n.tags),u=n.blocks??(a===i.rawContent?i.blocks:Vs(a,{...GL,sourceRevision:s}));if(await t.saveNoteSource({noteId:i.id,rawContent:a,blocks:u,expectedSourceRevision:s,metadata:{title:n.title,type:n.type,tags:l,targetDate:n.targetDate,sourceId:n.sourceId}}),await c.updateRelationships(i.id,n),(n.tags!==void 0||a!==i.rawContent)&&await c.updateTags(i.id,a,l),n.results){if(!n.blockId||!n.blockVersion)throw Error(`Recording a result requires its frozen block pin`);let e=await t.getBlockRevision(i.id,n.blockId,n.blockVersion);if(!e||e.kind!==`wod`)throw new AT(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision not found`);let r=n.resultId?await t.getSessionById(n.resultId):void 0;if(r&&(r.noteId!==i.id||r.blockId!==n.blockId||r.blockVersion!==n.blockVersion))throw new AT(`RESULT_NOTE_MISMATCH`,`Cannot replace a Session pin`);let a=n.results,o={...r,id:n.resultId??Br(),noteId:i.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,noteSourceRevision:r?.noteSourceRevision??i.sourceRevision,sessionDate:n.sessionDate??r?.sessionDate??Fw(new Date(a.endTime??a.startTime??r?.createdAt??Date.now())),...n.scheduleItemId??r?.scheduleItemId?{scheduleItemId:n.scheduleItemId??r?.scheduleItemId}:{},origin:n.origin??r?.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:r?.createdAt??a.endTime??Date.now()};if(await t.saveSession(o),o.scheduleItemId)try{let e=t.storage.readwrite(`schedule_items`),n=await e.get(o.scheduleItemId);n&&n.status!==`completed`&&await e.put({...n,status:`completed`,updatedAt:o.endTime||Date.now()})}catch{}if(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(jy(a.logs,e)),await t.finalizeSummaries(o.id,My(a.logs,e))}}});let i=await this.getRecord(r.id);if(!i)throw Error(`Saved note disappeared: ${r.id}`);return i}async addRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e),r=await this.resolveTargetPage(n,t);await this.storage.addNoteToPage(n,r.id);let i=await this.getRecord(n);if(!i)throw Error(`Saved note disappeared: ${n}`);return i}async removeRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e);await this.storage.removeNoteFromPage(n,t);let r=await this.getRecord(n);if(!r)throw Error(`Saved note disappeared: ${n}`);return r}async moveRecordPlacement(e,t,n){let r=await this.resolvePlacementNoteId(e),i=await this.resolveTargetPage(r,n);await this.storage.moveNoteBetweenPages(r,t,i.id);let a=await this.getRecord(r);if(!a)throw Error(`Saved note disappeared: ${r}`);return a}async getPageRecords(e){let t=await this.storage.getPageBySlug(e);if(!t)return[];let n=await this.storage.getPagePlacements(t.id);if(n.length===0)return[];let r=await this.storage.getDetailBatches(n.map(e=>e.noteId));return n.map(e=>r.get(e.noteId)).filter(e=>e!==void 0).map(ZL)}async deleteRecord(e){await this.storage.deleteNote(e)}async getAttachments(e){return this.storage.getAttachmentsForNote(e)}async saveAttachment(e,t){let n={...t,id:t.id??Br(),noteId:e,createdAt:Date.now()};return await this.storage.saveAttachment(n),n}async deleteAttachment(e){await this.storage.deleteAttachment(e)}async updateRelationships(e,t){for(let n of[`journalDate`,`slug`]){let r=t[n];if(r===void 0)continue;if(!r){for(let t of await this.storage.getNotePages(e)){let r=await this.storage.getPage(t.pageId);(n===`journalDate`?r?.date:r?.slug&&!r.date)&&await this.storage.removeNoteFromPage(e,t.pageId)}continue}let i=await this.resolvePage(e,n,r);await this.storage.addNoteToPage(e,i.id)}}async resolvePage(e,t,n){if(t===`journalDate`)return this.storage.getOrCreatePageForDate(n);let r=await this.storage.getPageBySlug(n);if(r)return r;let i={id:Br(),slug:n,title:(await this.storage.getNote(e))?.title,createdAt:Date.now()};return await this.storage.savePage(i),i}async resolveTargetPage(e,t){if(t.date)return this.storage.getOrCreatePageForDate(t.date);if(t.slug)return this.resolvePage(e,`slug`,t.slug);throw Error(`A placement target needs a date or a slug`)}async resolvePlacementNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.storage.getNote(e)??(t===e?void 0:await this.storage.getNote(t));if(!n)throw new AT(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async resolveStoredNote(e){let t=e.startsWith(`playground/`)?e.slice(11):e;return await this.storage.getNote(e)??(t===e?void 0:await this.storage.getNote(t))??await this.storage.getNoteBySlug(e)??(t===e?void 0:await this.storage.getNoteBySlug(t))}async changedManualTags(e,t){let n=(await this.storage.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.storage.getAllTagTypes()).map(e=>e.name),i=zs(t,GL).filter(e=>e.type===`frontmatter`).flatMap(e=>pc(e.displayContent,r)),a=n??(await this.storage.getNote(e))?.tags??[];await this.storage.setNoteTags(e,[...a,...i.map(e=>e.type?e:e.label)])}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=>Lw(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=>Lw(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 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 AT(`RESULT_NOT_FOUND`,`Result not found: ${t.resultId}`);if(r.noteId!==e.id)throw new AT(`RESULT_NOTE_MISMATCH`,`Result ${t.resultId} does not belong to note ${e.id}`);return{results:WL(r,await n(r))}}if(t.mode===`latest-for-section`||t.mode===`all-for-section`){let n=JL(await this.storage.getSessionsForSection(e.id,t.blockId));if(t.mode===`all-for-section`){let e=YL(n,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(n[0])}}let r=JL(await this.storage.getSessionsForNote(e.id));if(t.mode===`all-for-note`){let e=YL(r,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(r[0])}}async payloadOf(e){return e?WL(e,this.storage.getEventsByResult?await this.storage.getEventsByResult(e.id):[]):void 0}},eR=new $L,tR=new Map,nR=`wodwiki:pending-note-saves:v1`;function rR(){try{let e=localStorage.getItem(nR),t=e?JSON.parse(e):{};if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=r;t&&typeof t.noteId==`string`&&typeof t.rawContent==`string`&&t.blocks&&typeof t.expectedSourceRevision==`number`&&(n[e]={...t,noteId:e,stagedAt:t.stagedAt??0})}return n}catch{return{}}}function iR(e){try{Object.keys(e).length===0?localStorage.removeItem(nR):localStorage.setItem(nR,JSON.stringify(e))}catch{}}function ede(e){if(UL(e.noteId))return;let t=rR();t[e.noteId]=e,iR(t)}function aR(e){let t=rR();e in t&&(delete t[e],iR(t))}var oR=new Map;function tde(e,t){let n=oR.get(e);return n||(n=new Set,oR.set(e,n)),n.add(t),()=>{let n=oR.get(e);n&&(n.delete(t),n.size===0&&oR.delete(e))}}var sR=null;async function nde(){let e=rR();for(let t of Object.values(e)){if(UL(t.noteId)){aR(t.noteId);continue}let e=tR.get(t.noteId);if(e&&await e.then(()=>void 0,()=>void 0),UL(t.noteId)){aR(t.noteId);continue}let n=rR()[t.noteId];if(!n)continue;let r=oR.get(n.noteId);if(r&&r.size>0){let e=!1;for(let t of[...r])try{await t()&&(e=!0)}catch{e=!0}if(e)continue}let i=eR.saveNote({noteId:n.noteId,rawContent:n.rawContent,blocks:n.blocks,expectedSourceRevision:n.expectedSourceRevision,...n.metadata?{metadata:n.metadata}:{},...n.noteType?{noteType:n.noteType}:{}});tR.set(n.noteId,i);try{await i}catch{}finally{tR.get(n.noteId)===i&&tR.delete(n.noteId)}aR(n.noteId)}}function cR(){return sR??=nde().finally(()=>{sR=null}),sR}async function lR(e){let t=[...tR].filter(([t])=>t===e).map(([,e])=>e.then(()=>void 0,()=>void 0));t.length>0&&await Promise.all(t),await cR()}async function uR(){if(tR.size>0){let e=[...tR.values()].map(e=>e.then(()=>void 0,()=>void 0));await Promise.all(e)}await cR()}function dR(e,...t){console.warn(`[${e}]`,...t)}function fR(e,...t){console.error(`[${e}]`,...t)}var pR=new Set;function mR(e){return pR.add(e),()=>{pR.delete(e)}}function hR(e){for(let t of pR)try{t(e)}catch(e){fR(`resultRecorder`,`error in listener:`,e)}}function gR(e){return{async record({resultId:t,noteId:n,blockId:r,runBlock:i,blockVersion:a,blockContentId:o,blockContent:s,blockDialect:c,blockSport:l,data:u,createdAt:d,origin:f,scheduleItemId:p,sessionDate:m}){let h=a??(i&&`version`in i&&typeof i.version==`number`?i.version:void 0),g=o??i?.contentId,_=s??(i&&`content`in i&&typeof i.content==`string`?i.content:void 0),v=c??(i&&`dialect`in i&&typeof i.dialect==`string`?i.dialect:void 0),y=l??(i&&`sport`in i&&typeof i.sport==`string`?i.sport:void 0),b=n&&r?{noteId:n,blockId:r,...h===void 0?{}:{blockVersion:h},...g?{blockContentId:g}:{},..._===void 0?{}:{blockContent:_},...v?{blockDialect:v}:{},...y?{blockSport:y}:{},...f?{origin:f}:{},...p?{scheduleItemId:p}:{},...m?{sessionDate:m}:{}}:void 0,x=await e.finishSession(t,u,d,b);return wR(t),bR(t,{status:`saved`}),hR(x),x}}}var _R=gR(eR),vR=new Map,yR=new Set;function rde(){for(let e of yR)try{e()}catch(e){fR(`resultRecorder`,`error in unload state listener:`,e)}}function bR(e,t){if(t===null){if(!vR.has(e))return;vR.delete(e)}else vR.set(e,t);rde()}function ide(e){return yR.add(e),()=>{yR.delete(e)}}function ade(e){let t=e in SR(),n=vR.get(e);return n?(n.status===`pending`||n.status===`failed`)&&!t?(vR.delete(e),{status:`idle`}):n:t?{status:`pending`}:{status:`idle`}}var xR=`wodwiki:pending-halted-sessions:v1`;function ode(e){let t=e=>e instanceof Date?e:typeof e==`string`||typeof e==`number`?new Date(e):new Date,n=e=>({...e,...e.timestamp===void 0?{}:{timestamp:t(e.timestamp)},...Array.isArray(e.metrics)?{metrics:e.metrics.map(e=>e&&typeof e==`object`&&e.timestamp!==void 0?{...e,timestamp:t(e.timestamp)}:e)}:{},...e.timeSpan&&typeof e.timeSpan==`object`?{timeSpan:{...e.timeSpan,...e.timeSpan.startTime===void 0?{}:{startTime:t(e.timeSpan.startTime)},...e.timeSpan.endTime===void 0?{}:{endTime:t(e.timeSpan.endTime)}}}:{}});return{...e,...Array.isArray(e.logs)?{logs:e.logs.map(e=>n(e))}:{}}}function SR(){try{let e=localStorage.getItem(xR),t=e?JSON.parse(e):{};if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=r;t&&typeof t.resultId==`string`&&t.data&&typeof t.createdAt==`number`&&(n[e]={...t,resultId:e,data:ode(t.data)})}return n}catch{return{}}}function CR(e){try{Object.keys(e).length===0?localStorage.removeItem(xR):localStorage.setItem(xR,JSON.stringify(e))}catch{}}function sde(e){let t=SR();t[e.resultId]=e,CR(t),bR(e.resultId,{status:`pending`})}function wR(e){let t=SR();e in t&&(delete t[e],CR(t));let n=vR.get(e);n&&n.status!==`saved`&&bR(e,null)}var TR=null;function ER(e=_R){return TR??=(async()=>{let t=SR();if(Object.keys(t).length!==0){e===_R&&await ZP().catch(()=>void 0);for(let n of Object.values(t)){bR(n.resultId,{status:`flushing`});try{await e.record({resultId:n.resultId,noteId:n.noteId??``,blockId:n.blockId??``,...n.blockVersion===void 0?{}:{blockVersion:n.blockVersion},...n.blockContentId?{blockContentId:n.blockContentId}:{},...n.blockContent===void 0?{}:{blockContent:n.blockContent},...n.blockDialect?{blockDialect:n.blockDialect}:{},...n.blockSport?{blockSport:n.blockSport}:{},data:n.data,createdAt:n.createdAt,...n.origin?{origin:n.origin}:{},...n.scheduleItemId?{scheduleItemId:n.scheduleItemId}:{},...n.sessionDate?{sessionDate:n.sessionDate}:{}}),wR(n.resultId),bR(n.resultId,{status:`saved`})}catch(e){let t=e instanceof Error?e.message:String(e);fR(`resultRecorder`,`pending unload flush failed:`,e),bR(n.resultId,{status:`failed`,error:t})}}}})().finally(()=>{TR=null}),TR}typeof window<`u`&&ER();var DR=class extends $L{async getRecord(e){return await Promise.all([uR(),ER()]),super.getRecord(e)}async getRecords(e){return await Promise.all([uR(),ER()]),super.getRecords(e)}},OR={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 kR(e){return OR[e]}var AR=Object.freeze(Object.keys(OR)),jR=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)}},MR=class extends Error{sound;constructor(e){super(`Unknown sound "${e}" — it has no entry in the sound table`),this.sound=e,this.name=`UnknownSoundError`}},NR=new class{enabled;sink;constructor(e,t){if(this.sink=e??new jR,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=kR(e);if(!n)throw new MR(e);`init`in this.sink&&typeof this.sink.init==`function`&&this.sink.init(),await this.sink.playNotes(n.notes,t)}},PR=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 PR;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 PR;var FR=!0,IR=[`wodwiki.routeWql.v1`,`wodwiki.routeWqlShortcuts.v1`,`wodwiki.soundProfiles.v1`],LR=[],RR=new Map,zR={getItem:e=>RR.get(e)??null,setItem:(e,t)=>RR.set(e,t),removeItem:e=>RR.delete(e)};async function BR(){let e=await Promise.all(IR.map(e=>YP.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`)))),t=await Promise.all(LR.map(e=>YP.readonly(`meta`).get(e)));for(let t of e)for(let e of t)RR.set(e.key,e.value);for(let e of t)e&&RR.set(e.key,e.value)}async function VR(e,t){t===null?(await YP.readwrite(`meta`).delete(e),RR.delete(e)):(await YP.readwrite(`meta`).put({key:e,value:t}),RR.set(e,t))}async function HR(e){if(e.length===1)return VR(e[0],null);await YP.transaction([`meta`],`readwrite`,async t=>{for(let n of e)await t.readwrite(`meta`).delete(n)});for(let t of e)RR.delete(t)}async function UR(e){return await YP.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`))}async function WR(e,t){await YP.readwrite(`meta`).put({key:e,value:t})}async function GR(e){await YP.readwrite(`meta`).delete(e)}var KR=`wodwiki-telemetry`,qR=1,JR=`events`,YR=`wodwiki.telemetry.consent`,XR=class{events=new PR;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(YR)!==`denied`}get consent(){return this._consent}setConsent(e){if(this._consent!==e){this._consent=e;try{this.storage?.setItem(YR,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(JR,`readonly`).objectStore(JR).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(JR,`readwrite`);return a.objectStore(JR).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(KR,qR);return r.onupgradeneeded=()=>{let e=r.result;if(!e.objectStoreNames.contains(JR)){let t=e.createObjectStore(JR,{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))}},ZR;function QR(){let e=Date.now(),t=ZR===void 0?0:e-ZR;return ZR=e,t}var $R=FR?new XR({sink:e=>WR(`telemetry:${crypto.randomUUID()}`,{name:e.name,payload:e.payload,at:e.at}),load:async()=>(await UR(`telemetry:`)).map(e=>e.value).sort((e,t)=>e.at-t.at)}):new XR,ez={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 tz(){let e=(0,K.useSyncExternalStore)(e=>$R.subscribeConsent(e),()=>$R.consent);return{track:(0,K.useCallback)((e,t)=>$R.record(e,t),[]),consent:e,setConsent:(0,K.useCallback)(e=>$R.setConsent(e),[])}}var nz=[25,50,75,90];function rz(e,t=nz){let n=(0,K.useRef)(new Set);(0,K.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),$R.record(`scroll`,{percent_scrolled:r,page_path:e}))};return window.addEventListener(`scroll`,r,{passive:!0}),r(),()=>{window.removeEventListener(`scroll`,r)}},[e,t])}var iz=new class{_db;constructor(e){this._db=e}get db(){return this._db??X}async load(){let e=await this.db.getAllEquipment();return _P(this.db.storage,`equipment`,e)}async save(e){await this.db.saveEquipment(e)}async delete(e){await this.db.deleteEquipment(e)}};async function az(e){let t=await X.getAllEquipment();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),cz()}var oz=new Set;function sz(e){return oz.add(e),()=>oz.delete(e)}function cz(){for(let e of oz)e()}var lz=null;function uz(){return lz||=new xne({storage:iz}),lz}var dz=`sound-`;function fz(e){if(!e.startsWith(`sound-`))return;let t=e.slice(6);return t.length>0?t:void 0}function pz(e){let t=fz(e);return t?[{kind:`metric`,type:`sound`,value:t}]:[]}function mz(e,t=[]){let n=[],r=new Set([...xz().map(e=>e.slug),...t.map(e=>e.name.trim())]);for(let t of e){let e=t.label.trim();e.length>0&&r.add(e)}for(let t of e){let e=t.label.trim();if(e.length===0)continue;let i=t.contributions?.length?[...t.contributions]:[...pz(e)],a=t.type?.trim();a&&a!==e&&a!==`category`&&r.has(a)&&!i.some(e=>e.kind===`tag`&&e.slug===a)&&i.push({kind:`tag`,slug:a}),n.push({slug:e,...a===`category`?{isCategory:!0}:{},contributions:i})}return n}function hz(e){let t=xz(),n=new Set(t.map(e=>e.slug)),r=e.filter(e=>!n.has(e.slug)||e.contributions.length>0),i=new Set(r.map(e=>e.slug));return rs([...t.filter(e=>!i.has(e.slug)),...r])}function gz(e){return e.filter(e=>e.name.trim().length>0).map(e=>({slug:e.name.trim(),isCategory:!0,contributions:e.contributions??[]}))}async function _z(){return vz.loadTags()}var vz=new class{async loadTags(){let[e,t,n]=await Promise.all([X.getAllTags(),X.getAllTagTypes().catch(()=>[]),uS(X.storage,{notebookId:`notebook/custom`}).catch(()=>[])]),r=new Map(e.map(e=>[e.label,e])),i=new Map(t.map(e=>[e.name,e]));for(let e of n)e.kind===`tag`&&e.payload?r.set(e.slug,e.payload):e.kind===`tag-type`&&e.payload&&i.set(e.slug,e.payload);let a=[...i.values()],o=[...r.values()];return[...gz(a),...mz(o,a)]}},yz=rs(xz()),bz=new Set;function xz(){return[{slug:`tonnage`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]},{slug:`metabolic`,contributions:[{kind:`metric`,type:`met`,value:8},{kind:`metric`,type:`metMinutes`,value:`met * convert(elapsed, min)`},{kind:`metric`,type:`summaries.totalMetMinutes`,value:`sum(metMinutes)`}]},{slug:`kettlebell-24kg`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]}]}function Sz(){return yz}var Cz=null;function wz(){return Cz||=_z().then(e=>{yz=hz(e);for(let e of bz)e();return yz}).finally(()=>{Cz=null}),Cz}async function Tz(){yz=hz(await _z());for(let e of bz)e();return yz}function Ez(e){return bz.add(e),()=>bz.delete(e)}var Dz=new Map,Oz=new Map;function kz(e){Oz.set(e.runtimeId,e)}function Az(e){let t=Oz.get(e);return t&&Oz.delete(e),t}function jz(e){return Oz.get(e)}function Mz(e){for(let t of Oz.values())if(t.journalDate===e)return t}function Nz(e){Oz.delete(e)}var Pz=`wodwiki:halted-run:v1`;function Fz(){try{if(typeof window<`u`&&window.sessionStorage)return window.sessionStorage}catch{}return null}function Iz(){let e=Fz();if(!e)return null;try{let t=e.getItem(Pz);if(!t)return null;let n=JSON.parse(t);return typeof n.sessionId!=`string`||!n.sessionId||typeof n.timestamp!=`number`||!Number.isFinite(n.timestamp)?null:{sessionId:n.sessionId,...typeof n.runtimeId==`string`?{runtimeId:n.runtimeId}:{},...typeof n.noteId==`string`?{noteId:n.noteId}:{},...typeof n.workoutTitle==`string`?{workoutTitle:n.workoutTitle}:{},timestamp:n.timestamp,...typeof n.elapsedMs==`number`&&Number.isFinite(n.elapsedMs)?{elapsedMs:n.elapsedMs}:{}}}catch{return null}}function Lz(e){let t=Fz();if(t)try{t.setItem(Pz,JSON.stringify(e))}catch{}}function Rz(){let e=Fz();if(e)try{e.removeItem(Pz)}catch{}}var zz={status:`idle`,elapsedTime:0,stepCount:0,startTime:null},Bz=bt(e=>({runtime:null,activeNoteId:null,activeSessionId:null,haltedRun:Iz(),subscriptionManager:null,execution:zz,userOutputOverrides:new Map,setRuntime:(t,n=null)=>e(e=>({runtime:t,activeNoteId:n??(t?e.activeNoteId:null),...t===null?{execution:zz}:{}})),setActiveSessionMeta:(t,n=null)=>e(()=>({activeSessionId:t,activeNoteId:n})),setHaltedRun:t=>e({haltedRun:t}),setSubscriptionManager:t=>e({subscriptionManager:t}),setExecution:t=>e(e=>({execution:{...e.execution,...t}})),resetExecution:()=>e({execution:zz}),setUserOverride:(t,n)=>e(e=>{let r=new Map(e.userOutputOverrides),i=n instanceof Qo?n:Qo.from(n,t);return r.set(t,i),{userOutputOverrides:r}}),clearUserOverride:t=>e(e=>{if(!e.userOutputOverrides.has(t))return e;let n=new Map(e.userOutputOverrides);return n.delete(t),{userOutputOverrides:n}})}));function Vz(e){Lz(e),Bz.getState().setHaltedRun(e)}function Hz(e){let t=Iz()??Bz.getState().haltedRun;return!t||e&&t.noteId&&t.noteId!==e?null:t}function Uz(e){let t=Iz()??Bz.getState().haltedRun;e&&t&&t.sessionId!==e||(Rz(),Bz.getState().setHaltedRun(null))}var Wz=new WeakMap;function Gz(e,t){t&&Wz.set(e,t)}function Kz(e){return Wz.get(e)}function qz(e){let t=new Zd;return t.seed(Xd),t.seed(e.efforts),nf({efforts:t.list(),equipment:e.equipment})}function Jz(e,t){if(e.kind!==`wod`||!e.dialect)throw Error(`The saved revision is not a workout.`);let n=zs(e.rawContent).find(t=>t.type===e.dialect);if(!n?.scriptBlock)throw Error(`The saved workout fence cannot be read.`);let r=n.scriptBlock.content,i=t?.efforts===void 0?t?.referenceIndex:qz({efforts:t.efforts,equipment:t.equipment??[]}),a=t&&(!(`tags`in t)||t.tags.length>0)?t.tagIndex:Sz();return{id:e.blockId,content:r,dialect:e.dialect,sport:e.sport,statements:nu({tags:a,...i?{references:i}:{}}).read(r,e.sport).statements,startLine:0,endLine:e.rawContent.split(`
|
|
791
|
+
`).length-1,version:e.version,state:`idle`,widgetIds:{},createdAt:e.savedAt}}async function Yz(e,t,n,r,i=eR,a){let o=Date.now();Bz.getState().setActiveSessionMeta(n,e.noteId);let s=await i.startSession(e,{id:n,noteId:e.noteId,blockId:t.id,blockContentId:t.contentId,origin:r??`journal`,...a?.scheduleItemId?{scheduleItemId:a.scheduleItemId}:{},...a?.sessionDate?{sessionDate:a.sessionDate}:{},startTime:o,endTime:o,duration:0,completed:!1,status:`in-progress`,createdAt:o},a);s.note.id!==e.noteId&&Bz.getState().setActiveSessionMeta(n,s.note.id);let c=i.persistenceStorage?.storage??X.storage,l=await GS(c,s.note.id).catch(()=>[]),u=await dS(c,{note:l.length>0?{...s.note,notebookIds:l}:s.note}).catch(()=>void 0),d=!!(u&&(u.efforts.length>0||u.equipment.length>0||u.tags.length>0||u.tagTypes.length>0)),f=Jz(s.revision,d?u:void 0);return d&&u&&Gz(f,u),{...s,block:f}}async function Xz(e,t,n,r,i){let a=SC(e),o=a.isRemote?a.uuid:e,s=await X.getNote(o)??(o===e?void 0:await X.getNote(e));if(!s&&a.isRemote){let t=i?.resolveRemoteWorkout?await i.resolveRemoteWorkout(e):await NL(e).catch(()=>void 0),n=DL(e),r=t?`content`in t&&`path`in t?{row:t,canonicalNoteId:n?.record.uuid??a.uuid,remoteNoteId:e,feedId:n?.feedId??a.feedId,notebookSlug:n?.notebookSlug,record:n?.record}:t:void 0;r&&(s=(await PC(X.storage,{noteId:e,remotePayload:r})).note)}if(!s)throw Error(`The note is unavailable. Save the note before starting a workout.`);return Yz({noteId:s.id,rawContent:s.rawContent,blocks:s.blocks,expectedSourceRevision:s.sourceRevision},t,n,r,eR,{...i?.deferPersist===void 0?{}:{deferPersist:i.deferPersist},...i?.scheduleItemId?{scheduleItemId:i.scheduleItemId}:{},...i?.sessionDate?{sessionDate:i.sessionDate}:{}})}var Zz=`sound`,Qz=`wodwiki.soundProfiles.v1`,$z=`profiles`,eB=new rE(Qz,FR?zR:void 0);function tB(e){return`${dz}${e}`}function nB(e){return[{kind:`metric`,type:`sound`,value:e}]}function rB(e=eB){let t=e.get($z);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 iB(e,t=eB){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(FR){try{await VR(t.qualify($z),r)}catch(e){return console.error(`[soundProfiles] server write failed:`,e),!1}return dB(),!0}return t.set($z,n),t.getRaw($z)===r&&(dB(),!0)}var aB=Promise.resolve();async function oB(e,t=eB){let n=aB.then(async()=>iB(e(rB(t)),t));return aB=n.catch(()=>!1),n}async function sB(e,t){let n=tB(e),r=(await t.getAllTags()).find(e=>e.label===n);if(r){let n=nB(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:Zz});return}await t.putTag({id:`sound-profile-${e}`,label:n,type:Zz,contributions:nB(e),createdAt:Date.now()})}async function cB(e,t){let n=tB(e),r=(await t.getAllTags()).find(e=>e.label===n);r&&await t.deleteTag(r.id)}var lB=new Set,uB=0;function dB(){uB+=1;for(let e of lB)e()}function fB(e){return lB.add(e),()=>{lB.delete(e)}}function pB(){return uB}async function mB(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===Y.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??X,o=t.persistence??new $L(a),s=await a.getSessionById(n);if(!s||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),hR(s),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(s),`captured-no-rederive`;throw e}}async function hB(e,t={}){let{resultId:n,occurrence:r,metricType:i}=e;if(!n||!i)throw TypeError(`clearMetricCorrection: resultId and metricType are required`);let a=t.storage??X,o=t.persistence??new $L(a),s=await a.getSessionById(n);if(!s||await a.withTransaction([`events`],async e=>{let t=(await e.getEventsByResult(n)).filter(e=>e.grain===`event`&&e.outputType===`segment`&&(!r?.blockKey||e.sourceBlockKey===r.blockKey)&&(r?.sourceStatementId===void 0||e.sourceStatementId===r.sourceStatementId)&&(r?.stackLevel===void 0||e.stackLevel===r.stackLevel)&&e.metrics.some(e=>e.origin===`user`&&String(e.type).toLowerCase()===i.toLowerCase()));if(t.length===0)return`not-found`;let a=[];for(let e of t){let t=e.metrics.filter(e=>e.origin!==`user`||String(e.type).toLowerCase()!==i.toLowerCase()),n=e.timeSpan?.started??e.timestamp;a.push({...e,metrics:t,...e.metricTemporal?{metricTemporal:t.map(()=>({temporalKind:`instant`,instant:n}))}:{}})}return await e.appendEvents(a),`captured`})===`not-found`)return`not-found`;try{return await o.rederiveResultAnalytics(n),hR(s),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(s),`captured-no-rederive`;throw e}}async function gB(e,t,n={}){let r=n.storage??X,i=n.persistence??new $L(r),a=await r.getSessionById(e);if(!a)return`not-found`;let o=(r.getEventsByResult?await r.getEventsByResult(e):[]).filter(e=>e.grain===`event`&&e.metrics.some(e=>e.type===Y.SessionRPE&&e.origin===`user`));o.length>0&&r.deleteEvents&&await r.deleteEvents(o.map(e=>e.id));let s=r.getEventsByResult?await r.getEventsByResult(e):[],c=`session`,l=0,u=s.filter(e=>e.outputType===`segment`);if(u.length>0){let e=u[u.length-1];c=e.sourceBlockKey??`session`,l=e.stackLevel??0}let d=a.endTime??a.startTime??Date.now(),f={id:`${e}:rpe:${Date.now()}`,resultId:e,noteId:a.noteId,blockId:a.blockId,blockVersion:a.blockVersion,blockContentId:a.blockContentId,pageId:a.pageId,origin:`user`,timestamp:d,grain:`event`,outputType:`segment`,metrics:[{type:Y.SessionRPE,value:t,origin:`user`,image:`rpe: ${t}`}],sourceBlockKey:c,stackLevel:l};r.appendEvents&&await r.appendEvents([f]);try{return await i.rederiveResultAnalytics(e),hR(a),`captured`}catch(e){if(e instanceof AT&&e.code===`BLOCK_REVISION_NOT_FOUND`)return hR(a),`captured-no-rederive`;throw e}}var _B=null,vB=new Set;function yB(e){_B!==e&&(_B=e,vB.forEach(e=>e(_B)))}function bB(){return _B}function xB(e){return vB.add(e),()=>{vB.delete(e)}}var SB=(0,K.createContext)({transport:null});function CB(){let e=(0,K.useContext)(SB),[t,n]=K.useState(()=>bB());return K.useEffect(()=>xB(n),[]),e.transport??t}var wB=({children:e,transport:t})=>{let n=(0,K.useMemo)(()=>({transport:t}),[t]);return(0,q.jsx)(SB.Provider,{value:n,children:e})},TB=(0,K.createContext)(void 0);function EB({children:e,audioAdapter:t=NR}){let[n,r]=(0,K.useState)(t.isEnabled()),i=CB();(0,K.useEffect)(()=>{t.setEnabled(n)},[n,t]);let a=(0,K.useCallback)((e,r=1)=>{if(n){if(i?.connected){console.log(`[AudioContext] Routing sound '${e}' to cast receiver`);try{i.send({type:`rpc-audio`,name:e,volume:r})}catch(n){console.error(`[AudioContext] Failed to send rpc-audio`,n),t.playSound(e,r).catch(DB)}}else t.playSound(e,r).catch(DB)}},[n,i,t]),o=(0,K.useCallback)(()=>{let e=!n;r(e),e&&(t.setEnabled(!0),t.playSound(`beep`).catch(DB))},[n,t]),s=(0,K.useCallback)(()=>{a(`chime`)},[a]),c=(0,K.useCallback)(()=>{a(`click`,.5)},[a]),l=(0,K.useMemo)(()=>({isEnabled:n,toggleAudio:o,playTestSound:s,playSound:a,playClick:c}),[n,o,s,a,c]);return(0,q.jsx)(TB.Provider,{value:l,children:e})}function DB(e){console.error(`[AudioContext] Sound playback failed`,e)}function OB(){let e=(0,K.useContext)(TB);if(e===void 0)throw Error(`useAudio must be used within an AudioProvider`);return e}function kB(){return(0,K.useContext)(TB)}var AB=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},jB=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 AB(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return rS(await e.json())}resolveTargetUrl(e){if(/^https?:\/\//i.test(e)){let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password)throw new AB(`Disallowed feed resource URL`);return t.toString()}let t=e.replace(/^\/+/,``);return`${this.baseUrl}${t}`}async fetchChunk(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new AB(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}async fetchText(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new AB(`feed text fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.text()}},MB={core:1};function NB(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function PB(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}var FB=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=rS(e.manifest??await this.source.fetchManifest()),n=bx(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??xx(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=new Set(t.chunks.map(e=>e.id)),s=[...t.chunks,...(t.notebooks??[]).filter(e=>!o.has(e.notebookId)).map(e=>({id:e.notebookId,path:e.indexPath,sha256:e.sha256,bytes:e.bytes,count:e.count}))],c=s.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),l=!!(t.notebooks&&t.notebooks.length>0),u=c.filter(n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),i=a.chunks[n.id];if(e.forceAll||!i)return!0;if(r){if((r.version??0)>(i.version??0))return!0}else if(!l&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});u.sort((e,t)=>Number(t.id===yx)-Number(e.id===yx));let d=Object.keys(a.chunks).filter(e=>!s.some(t=>t.id===e)),f={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!u.length&&!d.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return f;f.status=`imported`;let p=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:f.appliedChunks,totalChunks:u.length,totalNotes:f.totalNotes,totalEfforts:f.totalEfforts,totalEquipment:f.totalEquipment,totalBlocks:f.totalBlocks,skippedUserOwned:f.skippedUserOwned,deleted:f.deleted,preservedPinned:f.preservedPinned,addedNotes:f.addedNotes,updatedNotes:f.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}}),m=e=>{f.totalNotes+=e.totalNotes,f.totalEfforts+=e.totalEfforts,f.totalEquipment+=e.totalEquipment,f.totalBlocks+=e.totalBlocks,f.skippedUserOwned+=e.skippedUserOwned,f.deleted+=e.deleted,f.preservedPinned=(f.preservedPinned??0)+(e.preservedPinned??0),f.addedNotes+=e.addedNotes,f.updatedNotes+=e.updatedNotes},h=(e,n,r)=>({...a,chunks:{...a.chunks,[e.id]:{sha256:e.sha256,version:n?.version,builtAt:n?.builtAt??t.builtAt,importedAt:this.now(),noteIds:r}},importedAt:this.now()}),g=0;if(u[0]?.id===`canvas`){let n=u[0],r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:s,noteIds:c}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id)),l=h(n,r,c);p(`applying`,n.id),m(await this.storage.applyChunk({chunkId:n.id,rows:s,manifest:t,expectedMeta:i,meta:l})),f.appliedChunks++,a=l,i=l,p(`committed`,n.id),e.onFirstPaintApplied?.(),g=1}let _=[];for(let n=g;n<u.length;n+=4){let r=u.slice(n,n+4),i=await Promise.all(r.map(async n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:i,noteIds:s}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id));return{chunk:n,notebook:r,rows:i,noteIds:s}}));_.push(...i)}let v=[];for(let e of _){let n=h(e.chunk,e.notebook,e.noteIds);v.push({chunkId:e.chunk.id,rows:e.rows,manifest:t,expectedMeta:i,meta:n}),a=n,i=n}for(let e of d){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()};v.push({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r}),a=r,i=r}let y={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};if(v.push({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:y}),v.length>0){if(_.length>0&&p(`applying`,_[0].chunk.id),this.storage.applyChunks){m(await this.storage.applyChunks(v)),f.appliedChunks+=_.length;for(let e of _)p(`committed`,e.chunk.id)}else for(let e of v)m(await this.storage.applyChunk(e)),e.chunkId&&_.some(t=>t.chunk.id===e.chunkId)&&(f.appliedChunks++,p(`committed`,e.chunkId))}return p(`finalizing`,null),f}async fetchSingleRecordRow(e){if(e.recordPath)try{let t=await this.source.fetchChunk(e.recordPath);return Array.isArray(t)?aS(t):[oS(t)]}catch(t){if(!e.rawUrl&&!/\.md$/i.test(e.path))throw t}let t=e.rawUrl??e.path,n=this.source.fetchText?await this.source.fetchText(t):String(await this.source.fetchChunk(t));return[await $S({path:e.path,markdown:n,uuid:e.uuid,commit:e.commit,version:e.version,title:e.title,date:e.date})]}async fetchChunkData(e,t,n,r,i,a){let o,s=e.records,c=!!(n.chunks[e.id]&&r.granularRecords&&(t?.indexPath||e.records));if(!a||c||r.granularRecords&&e.records&&e.records.length>0){if(t?.indexPath&&(s=iS(await this.source.fetchChunk(t.indexPath)).records),s&&s.length>0){let t=!r.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,n=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(a&&c&&n.length>s.length/2){if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else{let t=[];for(let r=0;r<n.length;r+=8){let a=n.slice(r,r+8);i(`fetching`,e.id,a[0]?.uuid,r,n.length);let o=await Promise.all(a.map(e=>this.fetchSingleRecordRow(e)));for(let e of o)t.push(...e)}o=t}}else if(a){if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else o=[]}else if(i(`fetching`,e.id),o=aS(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(o.map(e=>fS(e.path)));return{rows:o,noteIds:l}}},IB=45e3;function LB(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 RB(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function zB(e,t){if(e.offlinePolicy)return e.offlinePolicy;if(e.id===`core`)return`offline-full`;try{let n=(await t.getMeta?.(oC))?.entries?.[e.id]?.offlinePolicy;if(n===`index-only`||n===`offline-full`)return n}catch{}return`index-only`}async function BB(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=bx(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);s.hadCheckpoint=(c?.seedVersion??0)>0;let l=await zB(e,r);if(l===`offline-full`&&!t.force&&!t.probeManifests&&PB(c,e.embeddedVersion))return s.outcome=`current`,s;if(RB(c,i,a()))return s.outcome=`busy`,s;let u=rS(await e.source.fetchManifest());s.manifestChecked=!0,s.manifest=u,await r.putMeta?.({key:`catalog:${e.id}`,feedId:e.id,manifest:u,updatedAt:a()}).catch(()=>void 0);let d=Array.isArray(u.notebooks)&&u.notebooks.length>0;if(l===`index-only`&&d){let n=u.notebooks.filter(t=>e.notebookIds!==void 0&&e.notebookIds!==null?e.notebookIds.length!==0&&e.notebookIds.includes(t.notebookId):!0),i=await Promise.all(n.map(t=>r.getMeta?.(gx(e.id,t.notebookId)).catch(()=>void 0)));if(t.background&&!e.autoSyncOn)return s.outcome=n.some((e,t)=>{let n=i[t];return!n?.index||e.version>(n.index.version??0)||!!(e.sha256&&n.index.sha256!==e.sha256)})?`update-pending`:`current`,s;let o=!1,c=0;for(let[s,l]of n.entries()){let n=i[s];if(!(t.force===!0||!n?.index||l.version>(n.index.version??0)||l.sha256&&n.index.sha256!==l.sha256))continue;let u=iS(await e.source.fetchChunk(l.indexPath));await r.putMeta?.({key:gx(e.id,l.notebookId),feedId:e.id,notebookId:l.notebookId,index:u,updatedAt:a()});let d=new Set(u.records.map(e=>e.uuid)),f=await r.reconcileRemovedRecords?.(e.id,l.notebookId,d);c+=f?.preservedPinned??0,o=!0}return s.outcome=o?`imported`:`current`,o&&(s.applied=!0,s.importedVersion=u.version,s.added=0,s.updated=0),c>0&&(s.preservedPinned=c),s}let f=t.force?`import`:NB(c?.seedVersion,u.version);if(f===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);let p=u.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`)));if(t.background&&!e.autoSyncOn)return s.outcome=p.some(e=>{let t=u.notebooks?.find(t=>t.notebookId===e.id),n=c?.chunks[e.id];return!n||t&&(t.version??0)>(n.version??0)?!0:n.sha256!==e.sha256})?`update-pending`:`current`,s;let m=!!(c&&Object.keys(c.chunks).length>0),h=new Set([...u.chunks.map(e=>e.id),...(u.notebooks??[]).map(e=>e.notebookId)]),g=!m||p.every(e=>c?.chunks[e.id]?.sha256===e.sha256),_=m&&Object.keys(c.chunks).some(e=>!h.has(e));if(!t.force&&f===`current`&&c?.schema===9&&c.builtAt===u.builtAt&&g&&!_)return s.outcome=`current`,s;let v={...c??xx(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(v,c??null);try{let i=await new FB(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:!t.force&&!!(e.granularRecords&&m),manifest:u,stored:v});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=u.version,s.added=i.addedNotes,s.updated=i.updatedNotes,i.preservedPinned&&(s.preservedPinned=i.preservedPinned))}finally{try{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}catch(t){console.warn(`[feedSync] ${e.id} claim release skipped after concurrent update`,t)}}return s}catch(t){return console.warn(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=LB(t),s}}function VB(){try{return typeof localStorage<`u`&&localStorage.getItem(`wodwiki.seedImport.enabled`)!==`0`}catch{return!1}}function HB(){let e=new Set(Sue()),t=sI(oI);return[{id:`core`,label:`Core`,source:new jB(t),url:t,embeddedVersion:MB.core??0},...gI.map(e=>({id:e.id,label:e.label,source:new jB(e.url),url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},embeddedVersion:0,autoImport:e.autoImport??!1,tier:e.tier,...e.description?{description:e.description}:{}})),...dI().map(e=>({id:e.id,label:e.label,source:new jB(e.url),url:e.url,repositoryUrl:e.repositoryUrl,embeddedVersion:MB[e.id]??0,autoImport:!1}))].filter(t=>!e.has(t.id))}function UB(e){try{if(typeof BroadcastChannel<`u`){let t=new BroadcastChannel(mx);t.postMessage(e),t.close()}}catch{}}async function WB(){BP(),await Tz().catch(()=>{});let e=SP();e.isInitialized()&&await vP(e);let t=uz();t.isInitialized()&&await az(t)}function GB(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`}async function KB(e,t,n,r){let i=n.now??Date.now,a=n.broadcast??UB,o=n.reportActivity!==!1;if(t.manifestChecked&&nV(e.id,i()),t.manifest&&await yL(e.id,t.manifest,n.storage?.storageInstance).catch(()=>void 0),t.outcome===`error`){let i=t.error??`feed sync failed`;n.mode===`background`&&r?.set(e.id,{sourceId:e.id,label:e.label,state:`error`}),o&&TE(i);return}t.outcome===`imported`&&t.applied&&(a({kind:`seed-imported`,source:e.id,version:t.importedVersion}),await WB().catch(()=>void 0),o&&CE({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 qB(){return typeof Worker<`u`&&!1}async function JB(e,t,n){return new Promise(r=>{let i;try{i=new Worker(new URL(`/assets/feedSync.worker-CTJcuCvq.js`,``+import.meta.url),{type:`module`})}catch(e){console.warn(`[feedSync] seed worker unavailable; running on main thread`,e),r(null);return}let a=t.mode===`background`?new Map:void 0,o=[],s=[],c=e.length,l=!1,u=e=>{wE(null),i.terminate(),r(e)};i.onerror=e=>{console.warn(`[feedSync] feed worker failed`,e.message??`unknown error`),u(l?GB(o):null)},i.onmessage=n=>{l=!0;let r=n.data;if(r.type===`progress`){let n=e.find(e=>e.id===r.sourceId);wE({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}),r.progress.phase===`committed`&&(r.progress.chunkId===`efforts`||r.progress.chunkId===`equipment`)&&s.push(WB().catch(()=>void 0)),t.onProgress?.({...r.progress,sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,sourceIndex:e.indexOf(n)+1,totalSources:c});return}if(r.type===`first-paint`){s.push(WB().catch(()=>void 0)),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),s.push(KB(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:c});return}Promise.allSettled(s).then(()=>{a&&eV([...a.values()]),u(GB(r.outcomes.length?r.outcomes:o))})},i.postMessage({type:`run`,dbName:Wle(),userId:qP.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:sI(e.url),...e.tier?{tier:e.tier}:{},embeddedVersion:e.embeddedVersion,autoSyncOn:qI(e.id),notebookIds:t.notebookIds===void 0?zI(e.id)===`partial`?WI(e.id)??void 0:t.mode===`background`&&zI(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0,offlinePolicy:t.offlinePolicy??YI(e.id)}))})})}var YB=null,XB=0,ZB=new Set;function QB(){return YB}function $B(e){return ZB.add(e),()=>{ZB.delete(e)}}function eV(e){YB=e.length?{id:++XB,updates:e}:null;for(let e of ZB)e()}function tV(e){YB?.updates.some(t=>t.sourceId===e)&&eV(YB.updates.filter(t=>t.sourceId!==e))}function nV(e,t){fue(e,t)}function rV(e){return pue(e)}async function iV(e={}){let t=[],n=e.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=e.mode===`background`?new Map:void 0;if(!(e.isEnabled??VB)())return`disabled`;let i=e.owner??`seed-${(e.now??Date.now)()}-${Math.random().toString(36).slice(2,8)}`,a=e.sources??HB();if(!e.storage&&!e.now&&qB()){let t=await JB(a,e,i);if(t)return t}for(let[o,s]of a.entries()){let c=await oV(s,e,n,i,o+1,a.length,r);console.debug(`[feedSync] ${s.id} outcome: ${c}`),t.push(c)}return r&&eV([...r.values()]),GB(t)}async function aV(e={}){let t=e.sources??HB(),n=e.storage??NI();await yV({storage:n}).catch(e=>console.warn(`[feedSync] core registry migration failed`,e));let r;try{r=await n.getSeedMeta(bx(`core`))}catch(e){return console.warn(`[feedSync] boot provider probe failed`,e),`error`}if(!r||r.seedVersion<=0)return iV({...e,sources:t.filter(e=>e.autoImport!==!1)});let i=t.filter(e=>e.id===`core`||zI(e.id)!==`unsubscribed`);return iV({...e,sources:i,probeManifests:!0,mode:`background`,reportActivity:!1})}async function oV(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?SE(`download`,e.label):()=>{};try{let l=await BB({id:e.id,label:e.label,source:e.source,embeddedVersion:e.embeddedVersion,autoSyncOn:qI(e.id),...e.tier?{tier:e.tier}:{},notebookIds:t.notebookIds===void 0?zI(e.id)===`partial`?WI(e.id)??void 0:t.mode===`background`&&zI(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0,offlinePolicy:t.offlinePolicy??YI(e.id)},{storage:n,owner:r,now:s,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`},{onProgress:t=>{wE({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}),t.phase===`committed`&&(t.chunkId===`efforts`||t.chunkId===`equipment`)&&WB(),c?.({...t,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a})},onFirstPaint:()=>{BP(),t.onFirstPaint?.()}});return await KB(e,l,t,o),u(l.outcome,l.error),l.outcome}finally{wE(null),d()}}async function sV(e,t={}){let n=(t.sources??HB()).find(t=>t.id===e);if(!n)return console.warn(`[feedSync] unknown feed source: ${e}`),`error`;let r=await iV({...t,sources:[n]});return(r===`imported`||r===`current`)&&(t.subscribe===!1?BI(e)||VI(e,!1):!t.preserveSubscriptionState&&!t.notebookIds&&(VI(e,!0),t.offlinePolicy&&XI(e,t.offlinePolicy)),await JF(),tV(e)),r}async function cV(e,t={}){let n=t.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=t.offlinePolicy??(e===`core`?`offline-full`:`index-only`);return VI(e,!0),XI(e,r),t.autoSync!==void 0&&JI(e,t.autoSync),await JF(),sV(e,{...t,offlinePolicy:r,subscribe:!0,...t.notebookIds?{preserveSubscriptionState:!0}:{}})}async function lV(e,t,n={}){let r=n.storage??NI();return r.storageInstance&&!FF()&&await ZF(r.storageInstance).catch(()=>void 0),XI(e,`offline-full`),!t?.length&&!BI(e)&&VI(e,!0),await JF(),sV(e,{...n,offlinePolicy:`offline-full`,notebookIds:t,preserveSubscriptionState:!!t?.length})}async function uV(e,t,n,r={}){let i=r.storage??NI();if(i.storageInstance&&!FF()&&await ZF(i.storageInstance).catch(()=>void 0),n){UI(e,t,!0),await JF();let n=r.offlinePolicy??YI(e);return{outcome:await sV(e,{...r,offlinePolicy:n,notebookIds:[t],preserveSubscriptionState:!0,force:n===`offline-full`||r.force})}}{UI(e,t,!1),await JF(),await i.deleteMeta?.(gx(e,t)).catch(()=>void 0);let n=await i.getSeedMeta(bx(e));if(!n||!n.chunks[t]){let n=await i.removeNotebookContent?.(e,t)??{deleted:0,preservedPinned:0};if(n.deleted>0||n.preservedPinned>0){BP();let t=SP();t.isInitialized()&&await vP(t);let n=uz();n.isInitialized()&&await az(n),UB({kind:`seed-removed`,source:e})}return{deleted:n.deleted,preservedPinned:n.preservedPinned}}let r={...n.chunks};if(delete r[t],Object.keys(r).length===0){let t=await i.removeSourceContent(n);BP();let r=SP();r.isInitialized()&&await vP(r);let a=uz();return a.isInitialized()&&await az(a),UB({kind:`seed-removed`,source:e}),{deleted:t.deleted,preservedPinned:t.preservedPinned}}let a={...n,chunks:r,importedAt:Date.now()},o={schema:9,version:n.seedVersion,builtAt:n.builtAt,chunks:[]},s=await i.applyChunk({chunkId:t,rows:[],manifest:o,expectedMeta:n,meta:a}),c=await i.removeNotebookContent?.(e,t)??{deleted:0,preservedPinned:0};BP();let l=SP();l.isInitialized()&&await vP(l);let u=uz();return u.isInitialized()&&await az(u),UB({kind:`seed-removed`,source:e}),{deleted:s.deleted+c.deleted,preservedPinned:(s.preservedPinned??0)+c.preservedPinned}}}async function dV(e,t={}){if(e===`core`)return{deleted:0,preservedPinned:0};let n=t.storage??NI();n.storageInstance&&!FF()&&await ZF(n.storageInstance).catch(()=>void 0);let r=await n.getSeedMeta(bx(e)),i=n.removeSourceContentById?await n.removeSourceContentById(e):r?await n.removeSourceContent(r):{deleted:0,preservedPinned:0};VI(e,!1),JI(e,!1),await JF(),tV(e),BP();let a=SP();a.isInitialized()&&await vP(a);let o=uz();return o.isInitialized()&&await az(o),UB({kind:`seed-removed`,source:e}),{deleted:i.deleted,preservedPinned:i.preservedPinned}}async function fV(e,t={}){if(e===`core`)return{deleted:0,preservedPinned:0};let n=t.storage??NI(),r=await dV(e,t);return await n.deleteMeta?.(`catalog:${e}`).catch(()=>void 0),dI().some(t=>t.id===e)?yue(e):xue(e),await JF(),r}async function pV(e={}){let t=e.storage??NI(),n=!1,r=!1;return await Promise.all((e.sources??HB()).map(async e=>{try{let i=await t.getSeedMeta(bx(e.id));if(!i||i.seedVersion<=0)return;e.autoImport===!1?r=!0:n=!0}catch{}})),{coreImported:n,libraryImported:r}}async function mV(e={}){let t=e.storage??NI();t.storageInstance&&!FF()&&await ZF(t.storageInstance).catch(()=>void 0);let n=e.probe===!0,r=await Promise.all((e.sources??HB()).map(async r=>{let i=await t.getSeedMeta(bx(r.id)),a=null,o=null,s=null,c=r.repositoryUrl,l=await bL(r.id,t.storageInstance);if(l&&(s=l,a={version:s.version,schema:s.schema,builtAt:s.builtAt},c??=aI(s.repositoryUrl??``)??void 0),n)try{s=rS(await r.source.fetchManifest()),a={version:s.version,schema:s.schema,builtAt:s.builtAt},c??=aI(s.repositoryUrl??``)??void 0,await yL(r.id,s,t.storageInstance),nV(r.id,(e.now??Date.now)()),o=null}catch(e){o=e instanceof Error?e.message:String(e)}let u=hV(r.id,s,i),d=s?.indexBytes??u.reduce((e,t)=>e+(t.indexBytes??0),0),f=s?.chunks,p=s?.chunkBytes??(f?.length?f.reduce((e,t)=>e+(t.bytes??0),0):u.reduce((e,t)=>e+(t.chunkBytes??0),0));return{id:r.id,label:r.label,url:r.url,...c?{repositoryUrl:c}:{},...r.description?{description:r.description}:{},autoImport:r.autoImport!==!1,notebooks:u,stored:i?{version:i.seedVersion,schema:i.schema,builtAt:i.builtAt,importedAt:i.importedAt}:null,remote:a,remoteError:o,upToDate:i!=null&&a!=null&&i.schema===9&&i.seedVersion===a.version,count:u.reduce((e,t)=>e+t.count,0),bytes:u.reduce((e,t)=>e+t.bytes,0),indexBytes:d,chunkBytes:p,hasOfflineChunks:(s?.chunks?.length??0)>0||p>0,offlinePolicy:YI(r.id),checkedAt:rV(r.id),subscribed:BI(r.id),autoSync:qI(r.id)}}));return n&&await JF(),{sources:r}}function hV(e,t,n){let r={};for(let t of CI(e))r[t.chunkId]=t;if(t?.notebooks&&t.notebooks.length>0)return t.notebooks.map(i=>{let a=t.chunks.find(e=>e.id===i.notebookId),o=i.chunkBytes??a?.bytes;return{id:r[i.notebookId]?.id??i.notebookId,label:i.label||r[i.notebookId]?.label||i.notebookId,chunkId:i.notebookId,count:i.count,bytes:i.bytes,...i.indexBytes===void 0?{}:{indexBytes:i.indexBytes},...o===void 0?{}:{chunkBytes:o},imported:!!n?.chunks[i.notebookId],subscribed:HI(e,i.notebookId)}});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,chunkBytes:t.bytes,imported:!!n?.chunks[t.id],subscribed:HI(e,t.id)}));return i.length>0?i:CI(e).map(t=>({id:t.id,label:t.label,chunkId:t.chunkId,count:0,bytes:0,imported:!!n?.chunks[t.chunkId],subscribed:HI(e,t.chunkId)}))}async function gV(e={}){let t=e.storage??NI(),n=0;for(let e of gI){let r=bx(e.id);try{let i=await t.getSeedMeta(r);if(i&&i.seedVersion>0)continue;let a=[];for(let n of CI(e.id)){if(n.id===e.id)continue;let r=await t.getSeedMeta(bx(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(`[feedSync] legacy checkpoint adoption failed for ${e.id}`,t)}}return n}async function _V(e={}){return(e.storage??NI()).backfillFeedProvenance()}async function vV(e={}){return(e.storage??NI()).migrateNotebookVocabulary()}async function yV(e={}){let t=e.storage??NI(),n=bx(`seed-core`),r=await t.getSeedMeta(n),i=r?.chunks??{};if(!r||r.seedVersion<=0&&Object.keys(i).length===0&&!r.claim)return!1;let a=bx(`core`),o=await t.getSeedMeta(a),s={...o?.chunks};for(let[e,t]of Object.entries(i)){let n=s[e];s[e]=n?{sha256:n.sha256,noteIds:[...new Set([...n.noteIds??[],...t.noteIds??[]])]}:{...t,noteIds:t.noteIds??[]}}let c=o?{...o,builtAt:``,claim:null,chunks:s}:{...xx(a),chunks:s};return await t.putSeedMeta(c,o??null),await t.putSeedMeta(xx(n),r),!0}var bV=(0,K.createContext)(null);function xV({children:e}){let t=K.useRef(!0);(0,K.useEffect)(()=>(t.current=!0,()=>{t.current=!1}),[]);let[{isReady:n,error:r,revision:i},a]=(0,K.useState)({isReady:!1,error:null,revision:0}),o=SP(),s=(0,K.useCallback)(async()=>{try{if(await vP(o),!t.current||typeof window>`u`)return;a(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){if(!t.current||typeof window>`u`)return;a(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[o]),c=(0,K.useCallback)(async()=>{await s()},[s]);return(0,K.useEffect)(()=>{s()},[s]),(0,K.useEffect)(()=>bP(()=>{a(e=>({isReady:!0,error:null,revision:e.revision+1}))}),[]),(0,K.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(mx);return e.onmessage=()=>{c()},()=>e.close()},[c]),(0,q.jsx)(bV.Provider,{value:{registry:o,isReady:n,error:r,revision:i,refresh:c},children:e})}function SV(){return(0,K.useContext)(bV)}function CV(){let e=(0,K.useContext)(bV);if(!e)throw Error(`useEffortRegistry must be within EffortRegistryProvider`);return e}var wV=(0,K.createContext)(null);function TV({children:e}){let t=K.useRef(!0);(0,K.useEffect)(()=>(t.current=!0,()=>{t.current=!1}),[]);let[{isReady:n,error:r,revision:i},a]=(0,K.useState)({isReady:!1,error:null,revision:0}),o=uz(),s=(0,K.useCallback)(async()=>{try{if(await az(o),!t.current||typeof window>`u`)return;a(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){if(!t.current||typeof window>`u`)return;a(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[o]),c=(0,K.useCallback)(async()=>{await s()},[s]);return(0,K.useEffect)(()=>{s()},[s]),(0,K.useEffect)(()=>sz(()=>{a(e=>({isReady:!0,error:null,revision:e.revision+1}))}),[]),(0,K.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(mx);return e.onmessage=()=>{c()},()=>e.close()},[c]),(0,q.jsx)(wV.Provider,{value:{registry:o,isReady:n,error:r,revision:i,refresh:c},children:e})}function EV(){return(0,K.useContext)(wV)}function DV(){let e=(0,K.useContext)(wV);if(!e)throw Error(`useEquipmentRegistry must be within EquipmentRegistryProvider`);return e}var OV={activeL1Id:null,activeL2Id:null,activeL3Id:null,leftDrawerOpen:!1,rightDrawerOpen:!1,inspectorDrawerOpen:!1,peekTarget:null,expandedIds:new Set,journalFilter:{selectedDate:null,selectedTags:[]},searchFilter:{scope:`all`}};function kV(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 t.open?e.rightDrawerOpen&&!e.inspectorDrawerOpen&&(e.peekTarget??null)===null?e:{...e,rightDrawerOpen:!0,inspectorDrawerOpen:!1,peekTarget:null}:e.rightDrawerOpen?{...e,rightDrawerOpen:!1}:e;case`SET_INSPECTOR_DRAWER`:return t.open?e.inspectorDrawerOpen&&!e.rightDrawerOpen&&(e.peekTarget??null)===null?e:{...e,inspectorDrawerOpen:!0,rightDrawerOpen:!1,peekTarget:null}:!e.inspectorDrawerOpen&&(e.peekTarget??null)===null?e:{...e,inspectorDrawerOpen:!1,peekTarget:null};case`OPEN_PEEK`:return e.peekTarget===t.target&&e.inspectorDrawerOpen&&!e.rightDrawerOpen?e:{...e,peekTarget:t.target,inspectorDrawerOpen:!0,rightDrawerOpen:!1};case`CLOSE_PEEK`:return(e.peekTarget??null)===null?e:{...e,peekTarget:null,inspectorDrawerOpen:!1};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 AV=e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-80;window.scrollTo({top:e,behavior:`smooth`})}},jV={tree:[],navState:OV,dispatch:()=>{},peekTarget:null,openPeek:()=>{},closePeek:()=>{},l3Items:[],setL3Items:()=>{},l3Connections:void 0,setL3Connections:()=>{},l3Actions:[],setL3Actions:()=>{},secondarySpec:void 0,setSecondarySpec:()=>{},contextNav:void 0,setContextNav:()=>{},streamControls:null,setStreamControls:()=>{},analyticsControls:null,setAnalyticsControls:()=>{},scrollToSection:AV,registerScrollFn:()=>{},openCreateJournal:()=>{},registerCreateJournal:()=>{}},MV=(0,K.createContext)(jV);function NV(){return(0,K.useContext)(MV)}function PV(){let e=(0,K.useContext)(MV);return e===jV?null:e}function FV(e){let{tree:t,dispatch:n}=NV();(0,K.useEffect)(()=>{e&&t.some(t=>t.id===e)&&n({type:`SET_ACTIVE_L1`,id:e})},[e,t,n])}function IV(e,t){return e===t?!0:e.kind!==t.kind||e.id!==t.id?!1:e.kind===`link`&&t.kind===`link`?e.label===t.label&&e.to===t.to&&e.sectionId===t.sectionId&&e.onSelect===t.onSelect&&e.onRun===t.onRun&&e.runIcon===t.runIcon&&e.filterTo===t.filterTo&&e.filterLabel===t.filterLabel&&e.timestamp===t.timestamp&&e.badge===t.badge&&e.muted===t.muted&&e.icon===t.icon:e.kind===`section`&&t.kind===`section`?e.label===t.label&&e.entries.length===t.entries.length&&e.entries.every((e,n)=>IV(e,t.entries[n])):e.kind===`wql`&&t.kind===`wql`?e.label===t.label&&e.query===t.query&&e.limit===t.limit:e.kind===`widget`&&t.kind===`widget`&&e.render===t.render}function LV(e,t){return e===t||(!e||e.length===0)&&(!t||t.length===0)?!0:!e||!t||e.length!==t.length?!1:e.every((e,n)=>IV(e,t[n]))}function RV({tree:e,children:t}){let[n,r]=(0,K.useReducer)(kV,OV),[i,a]=(0,K.useState)([]),[o,s]=(0,K.useState)(void 0),[c,l]=(0,K.useState)([]),[u,d]=(0,K.useState)(void 0),[f,p]=(0,K.useState)(void 0),[m,h]=(0,K.useState)(null),[g,_]=(0,K.useState)(null),v=(0,K.useCallback)(e=>{r({type:`OPEN_PEEK`,target:e})},[]),y=(0,K.useCallback)(()=>{r({type:`CLOSE_PEEK`})},[]),b=(0,K.useCallback)(e=>{d(t=>t===e?t:e)},[]),x=(0,K.useCallback)(e=>{s(t=>LV(t,e)?t:e)},[]),S=(0,K.useCallback)(e=>{p(t=>{let n=typeof e==`function`?e(t):e;return t===n||!t&&!n||t&&n&&t.pathname===n.pathname&&t.spec===n.spec?t:n})},[]),C=(0,K.useCallback)(e=>{h(t=>t===e?t:e)},[]),w=(0,K.useCallback)(e=>{_(t=>t===e||!t&&!e||t&&e&&t.weeks===e.weeks&&t.onWeeksChange===e.onWeeksChange&&t.showRange===e.showRange&&t.showUnits===e.showUnits&&t.unitForced===e.unitForced&&t.onOpenQuerySettings===e.onOpenQuerySettings&&t.onReset===e.onReset?t:e)},[]),T=(0,K.useCallback)(e=>{l(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n]?.id&&t.label===e[n]?.label&&t.icon===e[n]?.icon&&t.disabled===e[n]?.disabled&&t.testId===e[n]?.testId&&t.group===e[n]?.group&&t.onRun===e[n]?.onRun)?t:e)},[]),E=Qe(),D=(0,K.useMemo)(()=>{if(o!==void 0)return o;if(f&&f.pathname===E.pathname&&f.spec.length>0)return f.spec},[o,f,E.pathname]),O=(0,K.useRef)(AV),k=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=e.find(e=>e.isActive?e.isActive(E,n):e.action.type===`route`?e.action.to===`/`?E.pathname===`/`||E.pathname===``:E.pathname.startsWith(e.action.to):!1);r({type:`SET_ACTIVE_L1`,id:t?.id??null})},[E.pathname]),(0,K.useEffect)(()=>{r({type:`SET_LEFT_DRAWER`,open:!1}),r({type:`SET_RIGHT_DRAWER`,open:!1}),r({type:`SET_INSPECTOR_DRAWER`,open:!1})},[E.pathname]);let A=(0,K.useRef)(new Map),j=(0,K.useCallback)(e=>{let t=new Map,n=e.map(e=>{let n=e.secondaryAction;if(n?.action.type!==`call`)return e;let r=`${e.id}:${n.id}`,i=n.action.handler;return t.set(r,i),{...e,secondaryAction:{...n,action:{type:`call`,handler:()=>{let e=A.current.get(r);e?e():i()}}}}});A.current=t,a(e=>e.length===n.length&&e.every((e,t)=>e.id===n[t]?.id&&e.label===n[t]?.label&&e.secondaryAction?.id===n[t]?.secondaryAction?.id&&e.secondaryAction?.label===n[t]?.secondaryAction?.label&&e.secondaryRunIcon===n[t]?.secondaryRunIcon)?e:n)},[]),M=(0,K.useCallback)(e=>{r({type:`SET_ACTIVE_L3`,id:e}),O.current(e)},[]),N=(0,K.useCallback)(e=>{O.current=e},[]),P=(0,K.useCallback)(e=>{k.current?.(e)},[]),F=(0,K.useCallback)(e=>{k.current=e},[]),I=n.peekTarget??null,ee=(0,K.useMemo)(()=>({tree:e,navState:n,dispatch:r,peekTarget:I,openPeek:v,closePeek:y,l3Items:i,setL3Items:j,l3Connections:D,setL3Connections:x,l3Actions:c,setL3Actions:T,secondarySpec:u,setSecondarySpec:b,contextNav:f,setContextNav:S,streamControls:m,setStreamControls:C,analyticsControls:g,setAnalyticsControls:w,scrollToSection:M,registerScrollFn:N,openCreateJournal:P,registerCreateJournal:F}),[e,n,I,v,y,i,j,D,x,c,T,u,b,f,S,m,C,g,w,M,N,P,F]);return(0,q.jsx)(MV.Provider,{value:ee,children:t})}function zV(e){if(!e)return null;let t=Xg(e);return t.error?`Couldn't parse "${e}" — ${t.error}`:null}function BV(e,t,n=[]){let r=e.trim();if(!r||/[:{}|]/.test(r)||!Xg(r).error)return null;let i=`:${t}{${[`text:${/\s/.test(r)?`"${r.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:r}`,...n.filter(Boolean)].join(`,`)}}`;return Xg(i).error?null:i}function VV(e,t,n,r){if(!e)return{query:n,error:null};if(!Xg(e).error)return{query:e,error:null};let i=r?.salvageQ?.(e,t)??null;return i&&!Xg(i).error?{query:i,error:null}:{query:n,error:zV(e)}}var HV=1e3;function UV(e){let t=(0,K.useRef)(e);t.current=e;let[n,r]=be(),i=n.get(`q`)??``,[a,o]=(0,K.useState)(()=>{let{defaultQuery:e,legacy:r}=t.current;return i?VV(i,n,e,r).query:r?.toQuery(n)??e}),[s,c]=(0,K.useState)(()=>i?VV(i,n,t.current.defaultQuery,t.current.legacy).error:null),l=(0,K.useRef)(a);l.current=a;let u=(0,K.useRef)(n);u.current=n;let d=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(d.current)return;d.current=!0;let{legacy:e}=t.current,n=u.current,i=n.get(`q`)??``,a=null;if(i?Xg(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,K.useRef)(!0),p=(0,K.useRef)(null),m=(0,K.useRef)(i);(0,K.useEffect)(()=>{if(i===m.current)return;m.current=i,f.current=!0,clearTimeout(p.current),p.current=null,c(VV(i,u.current,t.current.defaultQuery,t.current.legacy).error);let e=i?VV(i,u.current,t.current.defaultQuery,t.current.legacy):{query:t.current.legacy?.toQuery(u.current)??t.current.defaultQuery,error:null};o(t=>t===e.query?t:e.query)},[i]);let h=(0,K.useRef)(t.current.defaultQuery);return(0,K.useEffect)(()=>{let e=t.current.defaultQuery;e!==h.current&&(h.current=e,!i&&o(t=>t===e?t:e))},[i,t.current.defaultQuery]),(0,K.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`q`)??``;if(e===m.current)return;m.current=e,f.current=!0,clearTimeout(p.current),p.current=null;let n=new URLSearchParams(window.location.search),r=e?VV(e,n,t.current.defaultQuery,t.current.legacy):{query:t.current.legacy?.toQuery(n)??t.current.defaultQuery,error:null};c(r.error),o(r.query)};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e),clearTimeout(p.current)}},[]),{query:a,setQuery:(0,K.useCallback)(e=>{if(o(e),!Xg(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},HV)}},[r]),urlQueryError:s}}var WV=[`origin`,`discipline`];function GV(e){let t=e.filter(Boolean);return`:effort${t.length?`{${t.join(`,`)}}`:``}`}function KV(e,t){let n=t.get(`origin`),r=t.get(`discipline`)?.trim();return BV(e,`effort`,[n&&n!==`all`?`origin:${n}`:``,r?`discipline:${r}`:``])}function qV(e){if(!WV.some(t=>e.get(t)))return null;let t=e.get(`origin`),n=e.get(`discipline`)?.trim();return GV([...t&&t!==`all`?[`origin:${t}`]:[],...n?[`discipline:${n}`]:[]])}var JV={keys:WV,toQuery:qV,salvageQ:KV},YV=new Map;function XV(e,t){let n=wI(e);if(!n)return;let r=t?.trim();r?YV.set(n,r):YV.delete(n)}function ZV(e){let t=wI(e),n=YV.get(t);if(n)return n;let r=ks.find(e=>e.slug===t);if(r?.name)return r.name;let i=SI().find(e=>wI(e.chunkId||e.id)===t);return i?.label?i.label:CP(t)}function QV(e){return e.endsWith(`/`)&&e.length>1?e.slice(0,-1):e}function $V(e,t){let n=[`note`,`session`,`post`,`text`,`timePreset`,`rangeStart`,`rangeEnd`,`s`,`tags`,`mode`],r=t??(e===`journal`?`journal`:e===`playground`?`playground`:`note`);return{keys:n,salvageQ(e){return BV(e,r)},toQuery(t){if(!n.some(e=>t.has(e)))return null;let r=null;if(t.has(`note`)||t.has(`session`)||t.has(`post`)){let e=[];(t.get(`note`)??`include`)!==`hide`&&e.push(`journal`),(t.get(`session`)??`include`)!==`hide`&&e.push(`notebooks`),e.length===1&&(r=`source:${e[0]}`)}else e&&(r=`source:${e}`);let i=t.get(`timePreset`)??`2w`,a=i===`all`||i===`custom`?null:`last ${i}`,o=t.get(`text`)?.trim(),s=t.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:notebooks`?u=`:notebooks`:r===`source:playground`?u=`:playground`:r&&d.unshift(r);let f=d.length?`{${d.join(`,`)}}`:``;return[`${u}${f}`,a].filter(Boolean).join(` `)}}}var eH={route:`/journal`,title:`Journal`,defaultWql:`:note{notebook:journal} by {date} last 4w`,level:`note`,target:`note`,scopeOptions:[`journal`,`playground`],defaultLayout:`agenda`,calendarCapable:!0,legacy:$V(`journal`)},tH={route:`/notebooks`,title:`Notebooks`,defaultWql:`:notebook{subscribed:true} by {feed}`,level:`note`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,feedNotice:!0,legacy:$V(`notebooks`)},nH={route:`/notes`,title:`Notes`,defaultWql:`:note{}`,level:`note`,target:`note`,scopeOptions:[`journal`,`notebooks`],emptyMessage:`No note entries match your search.`,calendarCapable:!0,legacy:$V(`notebooks`)},rH={route:`/feeds`,title:`Feeds`,defaultWql:`:feed{}`,level:`session`,target:`feed`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,emptyMessage:`No feeds match your search.`,feedNotice:!0,legacy:$V(`notebooks`,`feed`)},iH={route:`/pages`,title:`Pages`,defaultWql:`:page{}`,level:`note`,target:`page`,scopeOptions:[],emptyMessage:`No pages match your search.`},aH={route:`/efforts`,title:`Efforts`,defaultWql:`:effort`,level:`effort`,target:`effort`,scopeOptions:[],emptyMessage:`No efforts match your search.`,legacy:JV},oH={route:`/equipment`,title:`Equipment`,defaultWql:`:equipment{}`,level:`note`,target:`equipment`,scopeOptions:[`equipment`],emptyMessage:`No equipment matches your search.`},sH={route:`/tags`,title:`Tags`,defaultWql:`:tag{}`,level:`note`,target:`tag`,scopeOptions:[],emptyMessage:`No tags match your search.`},cH={route:`/sessions`,title:`Sessions`,defaultWql:`:session{}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No completed session results recorded in this period.`,calendarCapable:!0},lH={route:`/playgrounds`,title:`Playgrounds`,defaultWql:`:playground{} by {date} last 1w`,level:`note`,target:`note`,scopeOptions:[`playground`],shelfVisible:!0,legacy:$V(`playground`)};function uH(e){return{route:`/session/${e}`,defaultWql:`:session{} from ${e} to ${e}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No session results recorded on ${e}.`}}function dH(e){return{route:`/results/${e}`,defaultWql:`:session{result:${e}, plane:segment}`,level:`segment`,target:`session`,scopeOptions:[],defaultLayout:`rows`,dashboardEnabled:!0,emptyMessage:`No segment records found for result ${e}.`}}function fH(e){let t=wI(e);return{route:`/notebook/${e}`,title:ZV(t),defaultWql:`:note{notebook:${t}} by {date}`,level:`note`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,calendarCapable:!0,notebookSlug:t,legacy:$V(`notebooks`)}}var pH={"/journal":eH,"/notebooks":tH,"/notes":nH,"/feeds":rH,"/pages":iH,"/efforts":aH,"/equipment":oH,"/tags":sH,"/sessions":cH,"/playgrounds":lH};function mH(e){let t=QV(e),n=pH[t];if(n)return n;if(t.startsWith(`/results/`)){let e=t.slice(9);if(e)return dH(e)}if(t.startsWith(`/session/`)){let e=t.slice(9);if(e)return uH(e)}if(t.startsWith(`/notebook/`)){let e=t.slice(10);if(e&&!e.includes(`/`))return fH(e)}}function hH(e){return mH(e)??eH}function gH(e){let t=pH[QV(e)]?.title;if(t)return t;if(QV(e).startsWith(`/notebook/`)){let t=QV(e).slice(10);if(t&&!t.includes(`/`))return ZV(t)}}function _H(e){let t=QV(e);if(pH[t])return!0;if(t.startsWith(`/results/`)||t.startsWith(`/session/`))return t.slice(9)!==``;if(t.startsWith(`/notebook/`)){let e=t.slice(10);return!!(e&&!e.includes(`/`))}return!1}var Z={home:`/`,playgroundRoot:`/playground`,playground:`/playground/:id`,note:`/note/:noteId`,notes:`/notes`,journal:`/journal`,day:`/day/:date`,plan:`/plan`,aiFirst:`/ai-first`,feeds:`/feeds`,feed:`/feed/:slug`,notebooks:`/notebooks`,notebook:`/notebook/:slug`,notebookTarget:`/notebook/:slug/:target`,notebookItem:`/notebook/:slug/:itemDate/:item`,subscribe:`/subscribe`,pages:`/pages`,page:`/page/:slug`,tags:`/tags`,tagCategory:`/t/:type`,tag:`/t/:type/:tag`,sessions:`/sessions`,sessionDetail:`/results/:sessionId`,sessionDate:`/session/:date`,playgrounds:`/playgrounds`,tracker:`/tracker/:runtimeId`,run:`/run/:runtimeId`,load:`/load`,loadJournal:`/load/journal`,loadJournalDate:`/load/journal/:date`,efforts:`/efforts`,effort:`/effort/:slug`,equipment:`/equipment`,equipmentSlug:`/equipment/:slug`,dashboards:`/dashboards`,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`},vH={settingsData:`/settings/data`,settingsDatabase:`/settings/database`,settingsQueries:`/settings/queries`};function yH(e){return`/playground/${encodeURIComponent(e)}`}function bH(e){return`/day/${encodeURIComponent(e)}`}function xH(e,t){return`/day/${encodeURIComponent(e)}?autoStart=${encodeURIComponent(t)}`}function SH(e){return`/note/${encodeURIComponent(e)}`}function CH(e){let t=wI(e);return`/notebook/${encodeURIComponent(t)}`}function wH(e,t){return`/notebook/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function TH(e,t){return`/notebook/${encodeURIComponent(e)}/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}function EH(e){return`/feed/${encodeURIComponent(e)}`}function DH(e){return`/run/${encodeURIComponent(e)}`}function OH({zip:e}){return`/load?zip=${encodeURIComponent(e)}`}function kH(){return`/sessions`}function AH(e){return`/results/${encodeURIComponent(e)}`}function jH(e){return`/page/${encodeURIComponent(e)}`}function MH(){return`/playgrounds`}function NH(){return`/efforts`}function PH(e){return`/equipment/${encodeURIComponent(e)}`}function FH(e){return`/t/${encodeURIComponent(e)}`}function IH(e,t){return`/t/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function LH(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 RH(){return`/dashboards`}function zH(e){return`/dashboard/${encodeURIComponent(e)}`}function BH(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?`/effort/${encodeURIComponent(e)}?${i}`:`/effort/${encodeURIComponent(e)}`}function VH(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 HH(e){return e?`/settings/${e}`:`/settings/appearance`}function UH(e){return e.startsWith(`/playground/`)}function WH(e){return e===`/efforts`||e.startsWith(`/effort/`)||e===`/t/effort`||e.startsWith(`/t/effort/`)}function GH(e){return e===`/equipment`||e.startsWith(`/equipment/`)||e===`/t/equipment`||e.startsWith(`/t/equipment/`)}function KH(e){let t=e.match(/^\/notebook\/([^/]+)\/([^/]+)\/([^/]+)$/);return t?[t[1],t[2],t[3]]:null}function qH(e){let t=e.match(/^\/feed\/([^/]+)$/);return t?t[1]:null}var JH=(0,K.forwardRef)(function({href:e,...t},n){return(0,q.jsx)(M,{...t,to:e,ref:n})}),YH=(0,K.createContext)(()=>{});function XH({close:e,children:t}){return(0,q.jsx)(YH.Provider,{value:e,children:t})}function ZH(){return(0,K.useContext)(YH)}function QH({className:e,...t}){return(0,q.jsx)(`nav`,{...t,className:ra(e,`flex h-full min-h-0 flex-col`)})}function $H({className:e,...t}){return(0,q.jsx)(`div`,{...t,className:ra(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 eU({className:e,...t}){return(0,q.jsx)(`div`,{...t,className:ra(e,`l2-sidebar-body flex flex-1 flex-col overflow-y-auto p-4 [&>[data-slot=section]+[data-slot=section]]:mt-8`)})}function tU({className:e,...t}){let n=(0,K.useId)();return(0,q.jsx)(Ie,{id:n,children:(0,q.jsx)(`div`,{...t,"data-slot":`section`,className:ra(e,`flex flex-col gap-0.5`)})})}function nU({className:e,...t}){return(0,q.jsx)(`h3`,{...t,className:ra(e,`mb-1 px-2 text-xs/6 font-medium text-muted-foreground`)})}var rU=(0,K.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=ZH(),o=ra(`group flex min-h-11 sm:min-h-9 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`,`hover:bg-primary/10 hover:text-primary hover:[&>[data-slot=icon]]:text-primary`,`active:bg-primary/15 active:scale-[0.98]`,`data-[current]:bg-primary/10 data-[current]:text-primary data-[current]:[&>[data-slot=icon]]:text-primary font-bold`),s=r,c=r;return(0,q.jsxs)(`span`,{className:ra(t,`relative`),children:[e&&(0,q.jsx)(_e.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,q.jsx)(JH,{...s,onClick:e=>{s.onClick?.(e),e.defaultPrevented||a()},className:o,"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n}):(0,q.jsx)(`button`,{type:`button`,...c,className:ra(`cursor-default`,o),"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n})]})});function iU({className:e,...t}){return(0,q.jsx)(`span`,{...t,className:ra(e,`truncate`)})}function aU(e){return Object.entries(e).filter(([e])=>e.startsWith(`markdown/dashboards/`)).map(([e,t])=>{let{meta:n}=ac(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))}var oU=new Set;function sU(){for(let e of oU)e()}function cU(e){return oU.add(e),()=>{oU.delete(e)}}function lU(e){return e.map(e=>{let{meta:t}=ac(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 uU(e){let t={};for(let n of e)n.seedOrigin===`seed`&&n.sourcePath?.startsWith(`markdown/dashboards/`)&&(t[n.sourcePath]=n.rawContent);return aU(t)}function dU(e,t){let n=HP(),r=(0,K.useMemo)(()=>n?aU(n):[],[n]),i=(0,K.useMemo)(()=>{if(!e)return null;let t=r.find(t=>t.slug===e);return t?{slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1}:null},[r,e]),[a,o]=(0,K.useState)(()=>i),[s,c]=(0,K.useState)(()=>!!e&&i===null);return(0,K.useEffect)(()=>{if(!e){o(null),c(!1);return}let r=!1;return o(t=>t&&t.slug===e?t:i),c(e=>t!==void 0&&t>0?!0:i?!1:e||!0),Promise.all([eR.listNotes({kind:`dashboard`}),n?Promise.resolve(null):X.getNotesByType(`dashboard`)]).then(([t,n])=>{if(r)return;let a=lU(t).find(t=>t.slug===e);if(a){o({slug:e,title:a.title,rawContent:a.rawContent,editable:!0,noteId:a.noteId});return}if(i){o(i);return}if(n){let t=uU(n).find(t=>t.slug===e);if(t){o({slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1});return}}o(null)}).catch(()=>{r||o(i)}).finally(()=>{r||c(!1)}),()=>{r=!0}},[e,t,i,n]),{source:a,loading:s}}function fU(){let e=HP(),t=(0,K.useMemo)(()=>e?aU(e):[],[e]),[n,r]=(0,K.useState)([]),[i,a]=(0,K.useState)(!0),[o,s]=(0,K.useState)(0);return(0,K.useEffect)(()=>cU(()=>{s(e=>e+1)}),[]),(0,K.useEffect)(()=>{let n=!1;return Promise.all([eR.listNotes({kind:`dashboard`}),e?Promise.resolve(null):X.getNotesByType(`dashboard`)]).then(([i,a])=>{if(n)return;let o=lU(i),s=new Set(o.map(e=>e.slug)),c=e?t:a?uU(a):t,l=[...o.map(e=>({slug:e.slug,title:e.title,editable:!0})),...c.filter(e=>!s.has(e.slug)).map(e=>({slug:e.slug,title:e.title,editable:!1}))];n||r(l)}).catch(()=>{n||r(t.map(e=>({slug:e.slug,title:e.title,editable:!1})))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,e,o]),{items:n,loading:i}}function pU(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function mU(){return pU(new Date)}function hU(e){return e<mU()}function gU(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=pU(a);return o===e?{dateKey:o,date:a}:null}var _U=`schedule:v35:pageNotesMigrated`,vU=new WeakSet,yU=new Set;function bU(){for(let e of[...yU])try{e()}catch{}}function xU(e){return yU.add(e),()=>{yU.delete(e)}}async function SU(e=X.storage){if(!vU.has(e))try{if((await e.readonly(`meta`).get(_U))?.value===!0){vU.add(e);return}await ow(e),await e.readwrite(`meta`).put({key:_U,value:!0}),vU.add(e)}catch{}}var CU={async scheduleNote(e){await SU();let t=await YC(X.storage,e);return bU(),t},async batchSchedule(e){await SU();let t=await XC(X.storage,e);return bU(),t},async updateItem(e,t){let{order:n,position:r,...i}=t,a=r??n,o=await ZC(X.storage,e,{...i,...a===void 0?{}:{position:a}});return bU(),o},async removeItem(e){await QC(X.storage,e),bU()},async listByDateRange(e,t){return await SU(),$C(X.storage,e,t)},async listAll(){await SU();try{return await X.storage.readonly(`schedule_items`).getAll()}catch{return[]}},async listForNote(e){return await SU(),ew(X.storage,e)},async getDayOverlay(e){return await SU(),aw(X.storage,e)},async getUsageCountsByNote(){return await SU(),tw(X.storage)},async attributeSession(e){let t=await nw(X.storage,e);return bU(),t},async findNearbyMatches(e,t=2){return await SU(),rw(X.storage,e,t)},async getNoteRevision(e,t){return qC(X.storage,e,t)},async listNoteRevisions(e){return JC(X.storage,e)},todayKey(e=Date.now()){return BC(e)}};function wU(e){let t=gU(e);if(!t)throw Error(`Invalid journal date: ${e}`);return t.date.getTime()}function TU({persistence:e,moveRecordPlacement:t,addRecordPlacement:n,onScheduleNote:r,listOverlayNotes:i,uuid:a=Br}){let o=new Map;return{async create(t){let n=t.journalDate?wU(t.journalDate):Date.now(),i=await e.createNote({id:a(),title:MT(t.title),rawContent:t.rawContent,tags:t.tags??[],targetDate:n,journalDate:t.journalDate||void 0,type:t.type??`journal`,slug:t.slug,sourceId:t.sourceId,notebookIds:t.notebookIds??[]});return t.journalDate&&t.type!==`dashboard`&&t.type!==`playground`&&r&&await r(i.id,t.journalDate).catch(()=>{}),i},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 wU(t),i?i(t):(await e.listNotes({journalDate:t,kind:`journal`,projection:`summary`})).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))},update(t,n,r){let i=t.id,a=MT(n.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<n.length&&t.rawContent[c]===n[c];)c++;let l=t.rawContent.length,u=n.length;for(;l>c&&u>c&&t.rawContent[l-1]===n[u-1];)l--,u--;let d=Us(t.blocks??{},r?.changes??[{from:c,to:l,insert:n.slice(c,u)}]);for(let e of r?.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=Vs(n,{sourceRevision:s,registeredWidgets:Ns,blocks:d}),p=async()=>e.mutateNote({id:i},{rawContent:n,blocks:f,expectedSourceRevision:s,metadata:a?{title:a}:void 0}),m=(o.get(i)??Promise.resolve()).then(p,p);o.set(i,m);let h=()=>{o.get(i)===m&&o.delete(i)};return m.then(h,h),m},async moveToDate(r,i){let a=wU(i);if(t&&n){let a=(await e.getNote({id:r},{projection:`summary`})).placements?.find(e=>e.date);return a?t(r,a.pageId,{date:i}):n(r,{date:i})}return e.mutateNote({id:r},{metadata:{journalDate:i,targetDate:a}})},delete(t){return e.deleteNote({id:t})}}}var EU=new DR,DU=TU({persistence:eR,moveRecordPlacement:(e,t,n)=>EU.moveRecordPlacement(e,t,n),addRecordPlacement:(e,t)=>EU.addRecordPlacement(e,t),onScheduleNote:async(e,t)=>{await CU.scheduleNote({noteId:e,date:t})},listOverlayNotes:async e=>{let[t,n]=await Promise.all([CU.getDayOverlay(e).catch(()=>void 0),eR.listNotes({journalDate:e,projection:`summary`}).catch(()=>[])]),r=new Map;for(let e of n)r.set(e.id,e);if(t){let n=t.planned.map(e=>e.note).filter(Boolean);for(let t of n)!t||r.has(t.id)||r.set(t.id,{id:t.id,title:t.title,createdAt:t.createdAt,updatedAt:t.createdAt,targetDate:t.date??wU(e),journalDate:e,rawContent:t.rawContent,sourceRevision:t.sourceRevision,blocks:t.blocks,tags:t.tags??[],schemaVersion:1,type:t.type??`note`,sourceId:t.sourceId,notebookId:t.notebookId,notebookIds:t.notebookIds,provenance:t.provenance,seedOrigin:t.seedOrigin})}return Array.from(r.values()).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))}});function OU({persistence:e,journal:t}){async function n(n){let r=await e.listNotes({kind:`dashboard`}),i=new Set;for(let e of r){let{meta:r,body:a}=ac(e.rawContent);if(typeof r.slug==`string`&&r.slug.trim()&&i.add(r.slug.trim()),n&&e.id===n||r.dashboard!==`true`||r[`dashboard.active`]!==`true`)continue;let o={...r};delete o[`dashboard.active`],await t.update(e,`---\n${sc(o)}\n---\n${a}`)}return i}function r(e,t){let{meta:n,body:r}=ac(e),i=(typeof n.slug==`string`&&n.slug.trim()?kb(n.slug):kb(String(n.title??`New Dashboard`)))||`dashboard`,a=1,o=i;for(;t.has(o);)a+=1,o=`${i}-${a}`;if(n.slug===o)return{rawContent:e,slug:o,suffix:a};let s={...n,slug:o};return a>1&&n.title===`New Dashboard`&&(s.title=`${Ob} ${a}`),{rawContent:`---\n${sc(s)}\n---\n${r}`,slug:o,suffix:a}}return{async createDashboard(e=Ob){let i=await n(),a=r(cae(e),i),o=a.suffix>1&&e===`New Dashboard`?`${Ob} ${a.suffix}`:e,s=await t.create({title:o,rawContent:a.rawContent,type:`dashboard`,sourceId:`dashboards`});return sU(),s},async createDashboardFromScope(e){let i=await n(),a=r(xae(e),i),{meta:o}=ac(a.rawContent),s=typeof o.title==`string`&&o.title?o.title:Ob,c=await t.create({title:s,rawContent:a.rawContent,type:`dashboard`,sourceId:`dashboards`});return sU(),c},async cloneDashboard(e,r,i){await n();let{meta:a,body:o}=ac(r),s={...a,slug:e};i&&(s.title=i);let c=`---\n${sc(s)}\n---\n${o}`,l=await t.create({title:typeof s.title==`string`?s.title:e,rawContent:c,type:`dashboard`,sourceId:`dashboards`});return sU(),l},async deleteDashboard(e){await t.delete(e),sU()}}}var kU=OU({persistence:eR,journal:DU});function AU({itemsOverride:e,...t}){let n=Qe(),r=dt(),i=ZH(),{items:a,loading:o}=fU(),s=e??a,c=!e&&o,[l,u]=(0,K.useState)(!1),d=async()=>{u(!0);try{let e=await kU.createDashboard(),{meta:t}=ac(e.rawContent),n=typeof t.slug==`string`&&t.slug?t.slug:e.id;r(zH(n)),i()}finally{u(!1)}},f=n.pathname===`/dashboards`,p=s.filter(e=>e.editable),m=s.filter(e=>!e.editable),h=e=>{let t=zH(e);if(n.pathname===t)return!0;let r=/^\/dashboard\/([^/]+)\/?$/.exec(n.pathname);if(!r)return!1;try{return decodeURIComponent(r[1])===e}catch{return r[1]===e}};return(0,q.jsxs)(`div`,{className:`flex flex-col gap-3 px-2 py-3`,"data-testid":`dashboards-nav-panel`,children:[(0,q.jsx)(tU,{children:(0,q.jsxs)(rU,{current:f,onClick:()=>{r(RH()),i()},children:[(0,q.jsx)(ir,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:`Explorer`})]})}),c?(0,q.jsxs)(tU,{children:[(0,q.jsx)(nU,{children:`Dashboards`}),(0,q.jsx)(`div`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`Loading…`})]}):s.length===0?(0,q.jsxs)(tU,{children:[(0,q.jsx)(nU,{children:`Saved dashboards`}),(0,q.jsx)(`div`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No dashboards yet.`})]}):(0,q.jsxs)(q.Fragment,{children:[p.length>0&&(0,q.jsxs)(tU,{"data-testid":`dashboards-nav-saved`,children:[(0,q.jsx)(nU,{children:`Saved dashboards`}),p.map(e=>(0,q.jsxs)(rU,{current:h(e.slug),"data-testid":`dashboard-nav-item-${e.slug}`,onClick:()=>{r(zH(e.slug)),i()},children:[(0,q.jsx)(ft,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:e.title})]},e.slug))]}),m.length>0&&(0,q.jsxs)(tU,{"data-testid":`dashboards-nav-prebuilt`,children:[(0,q.jsx)(nU,{children:`Prebuilt`}),m.map(e=>(0,q.jsxs)(rU,{current:h(e.slug),"data-testid":`dashboard-nav-item-${e.slug}`,onClick:()=>{r(zH(e.slug)),i()},children:[(0,q.jsx)(Ir,{"data-slot":`icon`,"aria-hidden":`true`}),(0,q.jsx)(iU,{children:e.title})]},e.slug))]})]}),(0,q.jsx)(`div`,{className:`mt-1 border-t border-border/40 pt-2`,children:(0,q.jsxs)(`button`,{type:`button`,onClick:d,disabled:l,"data-testid":`dashboards-nav-new`,className:`flex w-full items-center gap-2 rounded-xl px-2 py-2 max-lg:min-h-11 text-sm font-medium text-muted-foreground transition-colors hover:bg-primary/10 hover:text-primary disabled:opacity-50`,children:[(0,q.jsx)(ti,{className:`size-4 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate`,children:`New dashboard`})]})})]})}function jU(e){return e.replace(/(^|[{,\s!])catalog:("[^"]*"|[\w][\w/-]*)/g,`$1notebook:$2`)}var MU=[{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`}],NU=MU.map(e=>e.id),PU=Object.fromEntries(MU.map(e=>[e.id,e.label]));function FU(e){return PU[e]??e}function IU(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 LU(e,t){let n=new Set(e);if(!t||t.length===0)return MU.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:FU(e)})),...MU.filter(e=>n.has(e.id)&&!i.has(e.id))]}function RU(e,t,n){if(!e)return n;let r=new Set(t);return e.find(e=>r.has(e))??n}function zU(e){if(!e)return{options:[],invalid:[]};let t=[],n=[],r=new Set;for(let i of e){if(!NU.includes(i)){n.includes(i)||n.push(i);continue}r.has(i)||(r.add(i),t.push(i))}return{options:t,invalid:n}}var BU=`/palette`,VU=new rE(`wodwiki.routeWql.v1`,FR?zR:void 0),HU=[...qh,...Jh],UU={notes:`note`,blocks:`block`,efforts:`effort`,collections:`notebooks`,feeds:`notebooks`};function WU(e){let t=e.startsWith(`/`)?e:`/${e}`;return YU[t]??t}function GU(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim())}function KU(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 qU={"/notebooks":`/catalogs`,"/notes":`/feeds`,"/sessions":`/results`,"/dashboards":`/dashboard`},JU={"/notes":`/collections`},YU={"/feeds":`/feeds@2`};function XU(e){return jU(e).replace(/^:(collections?|feeds?)(?![\w:])/,e=>e===`:collections`||e===`:feeds`?`:notebooks`:`:notebook`).replace(/(^|[{,\s])source:(collections|feeds)(?![\w:])/g,`$1source:notebooks`).replace(/(^|[{,\s])source:collection:/g,`$1source:notebook:`).replace(/(^|[{,\s])type:(feed|collection)(?![\w:])/g,`$1type:note`)}function ZU(e,t=VU){let n=WU(e),r=qU[n],i=t.get(n,{alias:r});if(i==null&&r&&(i=t.get(r,{alias:JU[n]})),!i)return{};let a=GU(i.typeOptions),o=GU(i.groupByOptions),s=a&&KU(a,HU,UU),c=o?zU(o):void 0;return{defaultWql:typeof i.defaultWql==`string`&&i.defaultWql.trim().length>0?XU(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 QU(e,t,n=VU){let r=WU(e),i={defaultWql:t.defaultWql?.trim()||void 0,typeOptions:GU(t.typeOptions),groupByOptions:GU(t.groupByOptions)};if(FR){try{await VR(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlConfig] server write failed:`,e),!1}return iW(),!0}return n.set(r,i),iW(),!0}async function $U(e,t=VU){let n=WU(e),r=qU[n];if(FR){try{await HR(r?[t.qualify(n),t.qualify(r)]:[t.qualify(n)])}catch(e){return console.error(`[routeWqlConfig] server delete failed:`,e),!1}return iW(),!0}return t.remove(n,r),iW(),!0}var eW=0,tW=new Set;function nW(e){return tW.add(e),()=>{tW.delete(e)}}function rW(){return eW}function iW(){eW+=1;for(let e of tW)e()}function aW(e){let t=(0,K.useSyncExternalStore)(nW,rW,rW);return(0,K.useMemo)(()=>ZU(e),[e,t])}function oW(e,t){let n=t??ZU(e.route);return!n.defaultWql&&!n.typeOptions&&!n.groupByOptions?e:{...e,defaultWql:n.defaultWql??e.defaultWql,scopeOptions:n.typeOptions?n.typeOptions.filter(e=>Jh.includes(e)):e.scopeOptions,groupByOptions:n.groupByOptions}}function sW(e){let t=aW(e?.route??``);return(0,K.useMemo)(()=>e?oW(e,t):void 0,[e,t])}var cW={bookmark:Lee,calendar:U,"clipboard-list":An,clock:xr,dumbbell:ci,flame:vt,folder:De,"flask-conical":En,heart:$t,library:qe,plus:ti,rss:sr,star:Tn,tag:Ee,activity:dn,wrench:Ct},lW=new rE(`wodwiki.routeWqlShortcuts.v1`,FR?zR:void 0);function uW(e,t){return{id:`all`,label:e,icon:t,wql:``}}var dW={"/journal":`All entries`,"/notebooks":`Subscribed notebooks`,"/notes":`All notes`,"/feeds":`All feeds`,"/pages":`All pages`,"/playgrounds":`All playgrounds`,"/efforts":`All Efforts`,"/equipment":`All Equipment`,"/sessions":`All Sessions`,"/tags":`All Tags`},fW={"/journal":`calendar`,"/notebooks":`library`,"/notes":`rss`,"/feeds":`rss`,"/pages":`clipboard-list`,"/playgrounds":`flask-conical`,"/efforts":`flame`,"/equipment":`dumbbell`,"/sessions":`clipboard-list`,"/tags":`tag`};function pW(e){let t=gW(e);return t===`/notebooks`?[uW(`Subscribed notebooks`,`library`),{id:`all-configured`,label:`All configured`,icon:`bookmark`,wql:`:notebook{subscribed:true,false}`},{id:`available`,label:`Available to subscribe`,icon:`plus`,wql:`:notebook{subscribed:false}`}]:t===`/sessions`?[uW(`All Sessions`,`clipboard-list`),{id:`recent-1d`,label:`Recent (last 1d)`,icon:`clock`,wql:`:session{} last 1d`},{id:`recent-7d`,label:`Last 7 days`,icon:`calendar`,wql:`:session{} last 7d`}]:[uW(dW[t]??`Landing link`,fW[t]??`bookmark`)]}function mW(e){return e.map(e=>({id:`tag-type-${e.name}`,label:e.label,icon:`tag`,wql:`:tag{type:${e.name}}`}))}function hW(e){let t=(0,K.useMemo)(()=>pW(e),[e]),[n,r]=(0,K.useState)([]);return(0,K.useEffect)(()=>{if(gW(e)!==`/tags`)return;let t=!0;return X.getAllTagTypes().then(e=>{t&&r(e)}).catch(()=>{t&&r([])}),()=>{t=!1}},[e]),(0,K.useMemo)(()=>gW(e)===`/tags`?[...t,...mW(n)]:t,[e,t,n])}function gW(e){return e.startsWith(`/`)?e:`/${e}`}var _W={"/notebooks":`/catalogs`,"/notes":`/feeds`},vW={"/feeds":`/feeds@2`};function yW(e){let t=gW(e);return vW[t]??t}function bW(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`||!cW[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:XU(e.wql.trim()),...typeof e.to==`string`?{to:e.to}:{}})))}return t}function xW(e,t=lW){let n=yW(e);return bW(t.get(n,{alias:_W[n]}))}function SW(e,t=lW,n=pW(e)){let r=yW(e),i=_W[r];if(t.getRaw(r)!=null||i!=null&&t.getRaw(i)!=null){let r=xW(e,t);return r.some(e=>e.id===`all`)?r:[n[0],...r]}return n}async function CW(e,t,n=lW){let r=yW(e),i=bW(t);if(FR){try{await VR(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlShortcuts] server write failed:`,e),!1}return OW(),!0}return n.set(r,i),n.getRaw(r)===JSON.stringify(i)&&(OW(),!0)}var wW=0,TW=new Set;function EW(e){return TW.add(e),()=>{TW.delete(e)}}function DW(){return wW}function OW(){wW++;for(let e of TW)e()}function kW(e,t=lW){return(0,K.useSyncExternalStore)(EW,DW),SW(e,t,hW(e))}function AW(e){return Fg(e)?A_({...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))}):A_(e)}function jW(e,t){return e.to?t.pathname===e.to||t.pathname.startsWith(`${e.to}/`):MW(e.wql,t.query)}function MW(e,t){if(!e.trim())return t.trim()===``;if(t.trim()===``)return!1;if(t===e)return!0;let n=Xg(t),r=Xg(e);return!n.error&&!r.error&&AW(n)===AW(r)}var NW=null,PW=new Set;function FW(e){NW=e;for(let e of PW)e()}function IW(e){return PW.add(e),()=>{PW.delete(e)}}function LW(){return NW}function RW(){return(0,K.useSyncExternalStore)(IW,LW)}function zW(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}}function BW(e){switch(e.kind){case`journal`:return bH(e.id);case`playground`:return yH(e.id);case`workout`:return e.category===`effort`?BH(e.id):e.category===`equipment`?PH(e.id):e.category?TH(e.category,e.id):SH(e.raw)}}var VW=/^(?:uuid-|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)/i;function HW(e){return typeof e==`string`&&e&&!VW.test(e)?e:void 0}function UW(e){return!!e.sourceId?.startsWith(`notebook:`)||e.sourcePath?.startsWith(`markdown/notebooks/`)===!0}function WW(e){return e.type===`dashboard`||e.sourceId===`dashboards`||e.sourcePath?.startsWith(`markdown/dashboards/`)===!0}function GW(e){return e.sourceId===`efforts`||e.sourcePath?.startsWith(`markdown/efforts/`)===!0}function KW(e){return e.sourceId===`equipment`||e.sourcePath?.startsWith(`markdown/equipment/`)===!0}function qW(e){return e.type===`tag`&&e.id.startsWith(`tag/`)}function JW(e){let t=/^tag\/([^/]+)\/(.+)$/.exec(e.id);return t?{type:t[1],label:t[2]}:void 0}function YW(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 XW(e){let t=e.sourceId;if(t?.startsWith(`notebook:`)){let e=t.slice(9);if(e&&e!==`_root`){let t=e.indexOf(`/`);return t===-1?{slug:e,item:``}:{slug:e.slice(0,t),item:e.slice(t+1)}}}let n=/^markdown\/notebooks\/([^/]+)\/(.+)\.md$/.exec(e.sourcePath??``);if(n)return{slug:n[1],item:n[2].toLowerCase()===`readme`?``:n[2]};let r=e.id;if(VW.test(r))return{slug:``,item:``};let[i,...a]=r.split(`/`);return{slug:i,item:a.join(`/`)}}function ZW(e){return e.sourceId===`playground`||e.type===`playground`||e.id.startsWith(`playground/`)}function QW(e){let t=e.slug??e.id;return t.startsWith(`playground/`)?t.slice(11):t}function $W(e){if(!e.startsWith(`remote:`))return;let t=e.slice(7),n=t.indexOf(`:`);return n>0?t.slice(0,n):void 0}function eG(e){let t=tG(e),n=Wy(e),r=t.notebookId??Uy(e),i=e.id.startsWith(`remote:`)||e.retention===`indexed`,a=i?$W(e.id):void 0,o=Ds(e,n,r),s=i?!1:t.editable??(o.editable&&Os(e,n,r));return{...t,noteType:e.type,notebookId:r,...e.notebookIds===void 0?{}:{notebookIds:e.notebookIds},feedId:t.feedId??e.feedSourceId??a??(n===`user`?`local`:`core`),editable:s,ownership:o,...e.public===void 0?{}:{isPublic:e.public},...i?{isRemotePreview:!0,editable:!1}:{},...e.seedChunkId?{seedChunkId:e.seedChunkId}:{}}}function tG(e){let t=e.id,n=e.title,r=e.tags&&e.tags.length>0?e.tags:void 0;if(e.type===`feed`&&t.startsWith(`feed/`)){let i=t.slice(5),a=e.tags??[];return{id:t,kind:`feed`,sourceNotebook:`feeds`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:e.sourcePath,detail:e.rawContent.split(`
|
|
792
792
|
`)[0]||void 0,feedId:i,subscribed:a.includes(`subscribed:true`),unpublishedChanges:a.includes(`status:unpublished`),updateAvailable:a.includes(`status:update-available`),editable:!1,...r?{tags:r}:{}}}if(e.type===`notebook`&&(t.startsWith(`notebook/`)||t.startsWith(`feed-notebook/`))){let i=e.notebookId?e.notebookId.replace(/^notebook\//,``):t.split(`/`).at(-1)??t,a=e.tags??[],o=a.find(e=>e.startsWith(`count:`)),s=o?Number(o.slice(6)):0,c=e.feedSourceId??`local`,l=js({slug:i,notebookId:e.notebookId??`notebook/${i}`,feedId:c});return{id:t,kind:`notebook`,sourceNotebook:i,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,notebookId:`notebook/${i}`,title:n,date:null,createdAt:e.createdAt,subtitle:`${c} · ${s} note${s===1?``:`s`}`,detail:e.rawContent||void 0,feedId:c,subscribed:a.includes(`subscribed:true`),isPublic:e.public===!0||a.includes(`visibility:public`),seedChunkId:e.seedChunkId??`notebook.${i}`,editable:l.canEdit,...r?{tags:r}:{}}}if(ZW(e))return{id:t,kind:`note`,sourceNotebook:`playground`,sourceNote:QW(e),sourceId:e.sourceId,title:Ww(n||QW(e)),date:null,createdAt:e.createdAt,...r?{tags:r}:{}};if(UW(e)){let{slug:i,item:a}=XW(e),o=!a,s=a.split(`/`),c=s.length>1&&/^\d{4}-\d{2}-\d{2}$/.test(s[0])?s[0]:null;return{id:t,kind:`note`,sourceNotebook:i,sourceNote:o?``:a,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:c??(e.date?pU(new Date(e.date)):null),createdAt:e.createdAt,subtitle:i,...r?{tags:r}:{}}}if(WW(e))return{id:t,kind:`dashboard`,sourceNotebook:`dashboards`,sourceNote:YW(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`dashboards`,...r?{tags:r}:{}};if(GW(e)){let i=YW(e,2)??t,a=e.sourcePath?.match(/^markdown\/efforts\/([^/]+)\//)?.[1];return{id:t,kind:`effort`,sourceNotebook:`efforts`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:a,effort:{slug:i},...r?{tags:r}:{}}}if(KW(e))return{id:t,kind:`equipment`,sourceNotebook:`equipment`,sourceNote:YW(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`equipment`,...r?{tags:r}:{}};if(qW(e)){let i=JW(e);return{id:t,kind:`tag`,sourceNotebook:`tags`,sourceNote:i?.label??n,title:n||i?.label||t,date:null,createdAt:e.createdAt,subtitle:(`tagType`in e&&typeof e.tagType==`string`?e.tagType:void 0)??i?.type,detail:e.rawContent||void 0,...r?{tags:r}:{}}}if(e.sourceId?.startsWith(`guides:`)){let i=e.sourceId.slice(7)||t;return{id:t,kind:`note`,sourceNotebook:`guides`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,pageSlug:HW(i.replace(/^\//,``).replace(/^page\//,``)),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:e.type===`journal`&&`date`in e&&typeof e.date==`number`&&Number.isFinite(e.date)?i=pU(new Date(e.date)):`targetDate`in e&&e.targetDate&&(typeof e.targetDate==`number`||typeof e.targetDate==`string`)?i=pU(new Date(e.targetDate)):e.createdAt&&(i=pU(new Date(e.createdAt))),{id:t,kind:`note`,sourceNotebook:`journal`,sourceNote:t,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?HW(e.slug):void 0,title:n,date:i,createdAt:e.createdAt,...r?{tags:r}:{}}}function nG(e){return{id:e.noteId,title:e.noteTitle,createdAt:e.createdAt,type:`note`,sourceId:e.sourceId,sourcePath:e.sourcePath,rawContent:``,sourceRevision:1,blocks:{}}}var rG=3,iG=120;function aG(e){return e.split(`
|
|
793
793
|
`).map(e=>e.trim()).filter(Boolean).slice(0,rG).map(e=>e.length>iG?`${e.slice(0,119)}…`:e)}function oG(e){let t=eG(nG(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,block:{blockId:e.blockId,dataType:e.dataType,preview:aG(e.rawContent)}}}function sG(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 cG(e){return ps(e)}function lG(e){if(!e||VW.test(e))return`Workout Session`;let t=zW(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?VW.test(t.id)?`Workout Session`:sG(t.id)||t.id:t.id&&!VW.test(t.id)?sG(t.id):VW.test(e)?`Workout Session`:e}function uG(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`,sourceNotebook:e.registrySource??`effort`,sourceNote: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}}}var dG=Mc.standard().extend({canonical:`pood`,dimension:`mass`,aliases:[`poods`,`pd`]});function fG(e){if(!e||!e.trim())return null;let t=dG.get(e.trim());return!t||t.dimension!==`mass`||t.canonical===`bw`?null:t.canonical===`lb`?`lbs`:t.canonical}function pG(e){if(typeof e.value==`number`)return Number.isFinite(e.value)?{val:e.value,rawUnit:typeof e.unit==`string`?e.unit:void 0}:null;if(e.value&&typeof e.value==`object`){let t=e.value,n=typeof t.amount==`number`?t.amount:Number(t.amount);return Number.isFinite(n)?{val:n,rawUnit:typeof t.unit==`string`&&t.unit?t.unit:typeof e.unit==`string`?e.unit:void 0}:null}let t=Number(e.value);return Number.isFinite(t)?{val:t,rawUnit:typeof e.unit==`string`?e.unit:void 0}:null}function mG(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.metadata?.canonicalKey==`string`?e.metadata.canonicalKey.toLowerCase():``,i=pG(e);if(!i)return null;let{val:a,rawUnit:o}=i,s=o?.trim();if(s?.toUpperCase()===`AU`||t===`sessionload`||t===`session-load`||n===`sessionload`||r===`sessionload`)return{kind:`sessionLoad`,val:a};if(t===`rep`||n===`reps`||n===`rep`)return{kind:`rep`,val:a};if(t===`volume`||t===`totalvolume`||n===`volume`||n===`totalvolume`||r===`totalvolume`){let e=s?fG(s):`lbs`;return e?{kind:`volume`,val:a,unit:e}:null}if(t===`weight`||t===`resistance`||t===`load`||n===`load`||n===`weight`||n===`resistance`){if(s){let e=fG(s);return e?{kind:`load`,val:a,unit:e}:null}return t===`weight`||t===`resistance`||n===`weight`||n===`resistance`?{kind:`load`,val:a,unit:`lbs`}:null}if(t===`distance`||n===`distance`)return{kind:`distance`,val:a};if(t===`tis`||n===`tis`)return{kind:`tis`,val:a};if(t===`elapsed`||n===`elapsed`||r===`elapsed`){let e=s?.toLowerCase();return{kind:`elapsed`,val:e===`s`||e===`sec`||e===`seconds`?a*1e3:a}}return t===`duration`||n===`duration`?{kind:`duration`,val:a}:null}function hG(e,t){if(e.effortSlug)return!0;let n=e.summaryCoverage?.scope;if(n===`effort`||n===`partition`)return!0;let r=t.metadata;return r?typeof r.effortSlug==`string`||typeof r.groupTags==`object`&&r.groupTags!==null:!1}function gG(e){return Number.isInteger(e)?e.toLocaleString():Number(e.toFixed(1)).toLocaleString()}function _G(e){let t=1/0,n=-1/0,r=0,i=0,a,o,s,c,l=0,u=0,d=new Set,f=new Set(ub(e.events));for(let p of e.events){let e=f.has(p);if(e&&(u++,p.timeSpan?.started!=null&&(p.timeSpan.started<t&&(t=p.timeSpan.started),p.timeSpan.ended!=null&&p.timeSpan.ended>n&&(n=p.timeSpan.ended))),p.effortSlug&&d.add(p.effortSlug),Array.isArray(p.metrics)){let t,n,u=0;for(let i of p.metrics){let a=mG(i);a&&(a.kind===`sessionLoad`?a.val>0&&(c=a.val):a.kind===`tis`?a.val>l&&(l=a.val):p.outputType===`analytics`?a.kind===`volume`&&a.val>0&&!hG(p,i)?o={val:a.val,unit:a.unit}:a.kind===`elapsed`&&a.val>0&&!hG(p,i)&&(s=a.val):e&&(a.kind===`rep`?(r+=a.val,u+=a.val):a.kind===`volume`&&a.val>0?t={val:a.val,unit:a.unit}:a.kind===`load`&&a.val>0&&(n={val:a.val,unit:a.unit})))}e&&(t?(i+=t.val,a??=t.unit):n&&(i+=u>0?u*n.val:n.val,a??=n.unit))}}let p=typeof e.durationMs==`number`&&Number.isFinite(e.durationMs)&&e.durationMs>0?e.durationMs:void 0,m=Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,h=p??s??m,g=typeof e.summary?.totalVolume==`number`&&Number.isFinite(e.summary.totalVolume)&&e.summary.totalVolume>0?{val:e.summary.totalVolume,unit:e.summary.volumeUnit??`lbs`}:void 0,_=o??g??(i>0?{val:i,unit:a??`lbs`}:void 0),v=e.summary?.rpe,y=e.summary?.prCount;return{elapsedMs:e.summary?.elapsedMs??h,reps:r>0?r:void 0,loadLbs:_?.val,volumeUnit:_?.unit,sessionLoadAu:c,tis:l>0?l:void 0,rpe:v,prCount:y,segmentCount:u>0?u:void 0,effortSlugs:Array.from(d)}}function vG(e,t){let n=_G(e),r=[];n.elapsedMs!=null&&r.push(cG(n.elapsedMs)),n.tis!=null&&r.push(`TIS Score: ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${gG(n.loadLbs)} ${n.volumeUnit??`lbs`}`),n.sessionLoadAu!=null&&r.push(`Load: ${gG(n.sessionLoadAu)} AU`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`),n.rpe!=null&&r.push(`RPE ${n.rpe}/10`),n.prCount!=null&&n.prCount>0&&r.push(`${n.prCount} PR`);let i=n.effortSlugs.map(sG),a=pU(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;if(e.timestamp){let t=new Date(e.timestamp).toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`});t&&t!==`Invalid Date`&&r.unshift(t)}let s=t?.noteTitle&&!VW.test(t.noteTitle)?t.noteTitle:lG(e.noteId);return{id:e.resultId,kind:`result`,sourceNotebook:`results`,sourceNote:e.resultId,title:s,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,volumeUnit:n.volumeUnit,sessionLoadAu:n.sessionLoadAu,tis:n.tis,rpe:n.rpe,prCount:n.prCount,segmentCount:n.segmentCount,events:e.events}}}function yG(e,t){let n=(e.sourceBlockKey??``).toLowerCase();if(n.startsWith(`waiting-to-start`))return`Start`;if(n.startsWith(`session-root`)||e.stackLevel===0)return`Session`;if(n.startsWith(`rest`))return`Rest`;if(Array.isArray(e.metrics)){for(let t of e.metrics)if((t.type??``).toLowerCase()===`current-round`){let e=typeof t.image==`string`?t.image.trim():``;if(/^completed\b/i.test(e))return e;let n=typeof t.value==`number`?t.value:Number(t.value);if(Number.isFinite(n)&&n>0)return`Round ${n}`}for(let t of e.metrics){let e=(t.type??``).toLowerCase();if(e===`effort`||e===`action`||e===`label`){let e=typeof t.value==`string`?t.value.trim():typeof t.image==`string`?t.image.trim():``;if(!e)continue;let n=e.toLowerCase();if(n===`ready to start`)return`Start`;if(n===`session`||n===`session completed`)return`Session`;if(n!==`completed`&&n!==`statement`)return e}}}return t===0?`Start`:`Segment`}function bG(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o,s,c;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=mG(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`||e.kind===`volume`?(i=e.val,a=e.unit):e.kind===`sessionLoad`?o=e.val:e.kind===`distance`?s=e.val:e.kind===`tis`?c=e.val:e.kind===`duration`&&!n&&(n=e.val))}let l=e.outputType===`segment`?`segment`:`event`,u=t?.index??0,d=e.effortSlug?sG(e.effortSlug):e.outputType===`segment`?yG(e,n):`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${u+1}`,f=[];n!=null&&f.push(cG(n));let p=a??`lbs`;r!=null&&i!=null?f.push(`${r} reps @ ${i} ${p}`):r==null?i!=null&&f.push(`${i} ${p}`):f.push(`${r} reps`),o!=null&&i==null&&f.push(`Load: ${gG(o)} AU`),s!=null&&f.push(`${s}m`),c!=null&&f.push(`TIS Score: ${c.toFixed(1)}`);let m=pU(new Date(e.timestamp));return{id:e.id,kind:l,sourceNotebook:`results`,sourceNote:e.id,title:d,date:m,blockContentId:e.blockContentId,subtitle:f.join(` • `),detail:e.effortSlug?sG(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,volumeUnit:a,sessionLoadAu:o,distanceMeters:s,tis:c,metrics:e.metrics}}}function xG(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(bG(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(bG(i,{index:e++}))}return t}return e.runs.map(e=>vG(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function SG(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function CG(e){if(!e.startsWith(`remote:`))return;let t=e.slice(7),n=t.indexOf(`:`);if(n<=0)return;let r=t.slice(0,n),i=t.slice(n+1);return i?{feedId:r,uuid:i}:void 0}function wG(e,t){if(!t.isRemotePreview&&!t.id.startsWith(`remote:`))return e;let n=CG(t.id),r=t.feedId??t.ownership?.feedSourceId??n?.feedId,i=n?.uuid;if(!r&&!i)return e;let a=new URLSearchParams;r&&a.set(`feed`,r),i&&a.set(`remote`,i);let o=a.toString();return o?e.includes(`?`)?`${e}&${o}`:`${e}?${o}`:e}function TG(e){let t=(()=>{switch(e.kind){case`note`:{if(e.sourceNotebook===`guides`)return e.pageSlug?`/page/${SG(e.pageSlug)}`:`/${SG(e.sourceNote.replace(/^\//,``))}`;if(e.sourceNotebook===`playground`)return`/playground/${encodeURIComponent(e.sourceNote)}`;let t=/^markdown\/dashboards\/(.+)\.md$/.exec(e.sourcePath??``);if(t?.[1])return`/dashboard/${SG(t[1])}`;let n=/^markdown\/efforts\/[^/]+\/(.+)\.md$/.exec(e.sourcePath??``);if(n?.[1])return`/effort/${SG(n[1])}`;let r=e.sourceId??``,i=e.sourcePath??``;return r.startsWith(`notebook:`)||i.startsWith(`markdown/notebooks/`)?e.sourceNote?`/notebook/${encodeURIComponent(e.sourceNotebook)}/${SG(e.sourceNote)}`:`/notebook/${encodeURIComponent(e.sourceNotebook)}`:e.pageSlug?`/page/${SG(e.pageSlug)}`:SH(e.id)}case`dashboard`:return e.sourceNotebook===`dashboards`&&e.sourceNote?`/dashboard/${SG(e.sourceNote)}`:SH(e.id);case`equipment`:{let t=e.sourceNote??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/${SG(n)}`:SH(e.id)}case`tag`:{let t=JW(e),n=t?.type??`general`,r=t?.label??e.sourceNote??e.id;return`/t/${encodeURIComponent(n)}/${encodeURIComponent(r)}`}case`feed`:return e.sourceNote===`local`?`/notebooks?q=%3Anotebook%7Bfeed%3Alocal%2Csubscribed%3Atrue%2Cfalse%7D`:`/feed/${encodeURIComponent(e.sourceNote||e.id)}`;case`notebook`:{let t=`/notebook/${encodeURIComponent(e.sourceNotebook)}`;return e.feedId&&e.feedId!==`local`&&e.feedId!==`core`&&e.subscribed===!1?`${t}?feed=${encodeURIComponent(e.feedId)}`:t}case`effort`:return`/effort/${encodeURIComponent(e.effort?.slug??e.id)}`;case`result`:return AH(e.id);case`segment`:case`event`:return AH(e.execution?.resultId??(e.sourceNotebook===`results`?e.sourceNote:e.id));default:return`/`}})(),n=e.kind===`note`||e.kind===`dashboard`||e.kind===`effort`||e.kind===`equipment`?wG(t,e):t;return e.block?`${n}#${encodeURIComponent(e.block.blockId)}`:n}function EG(e){return e.sourceNotebook===`playground`||e.sourceId===`playground`}function DG(e){return e.kind===`note`&&!e.sourceNote?`/notebooks?q=${encodeURIComponent(`:notebook{notebook:${e.sourceNotebook}}`)}`:null}function OG(e){return e.blockContentId?LH({q:e.blockContentId}):null}function kG(e){return!!(e.kind===`note`||(e.kind===`result`||e.kind===`segment`)&&e.execution?.noteId)}function AG(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=>AG(e,t)),n.length>0&&(r.length>0?setTimeout(()=>{n.forEach(e=>AG(e,t))},0):n.forEach(e=>AG(e,t)));break}case`call`:e.handler();break;case`external`:window.open(e.href,`_blank`,`noopener,noreferrer`)}}function jG(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 MG(e,t){let n=e.pipeline.map(t=>jG(t,e.open));return{id:`btn-${t}`,label:e.label,action:n.length===1?n[0]:{type:`pipeline`,steps:n}}}function NG(e){let{action:t}=e;return t?t.type===`view-state`?t.state===`track`:t.type===`pipeline`&&t.steps.some(e=>e.type===`view-state`&&e.state===`track`):!1}var PG=`sticky top-0 z-10 bg-card`;function FG({title:e,defaultOpen:t=!1,collapsible:r=!0,children:i,count:a,className:o,sticky:s,trailing:c,bodyClassName:l,buttonClassName:u}){if(!r)return(0,q.jsxs)(`div`,{className:o,children:[(0,q.jsxs)(`div`,{className:ra(`group flex w-full items-center gap-1 px-2 py-3 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground/80`,s&&PG),children:[(0,q.jsx)(`div`,{className:`size-4 shrink-0`}),(0,q.jsx)(`span`,{children:e}),a!==void 0&&(0,q.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:a})]}),(0,q.jsx)(`div`,{className:ra(`flex flex-col gap-0.5`),children:i})]});let d=(0,q.jsxs)(Ci,{className:ra(`group flex h-auto max-lg:min-h-11 border-0 bg-transparent rounded-none 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`,c?`min-w-0 flex-1`:`w-full`,u,s&&!c&&PG),children:[(0,q.jsx)(n,{className:`size-4 shrink-0 fill-muted-foreground/50 transition-transform duration-300 group-data-[open]:rotate-90 group-hover:fill-primary`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:e}),a!==void 0&&(0,q.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:a})]});return(0,q.jsxs)(Li,{defaultOpen:t,className:o,children:[c?(0,q.jsxs)(`div`,{className:ra(`flex w-full items-center bg-card`,s&&PG),children:[d,c]}):d,(0,q.jsx)(mee,{className:ra(`flex flex-col gap-0.5`,l),children:i})]})}var Q={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`,TIMER_STACK_DRAWER_TOGGLE:`timer-stack-drawer-toggle`,TIMER_STACK_DRAWER:`timer-stack-drawer`,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`,EDITOR_TOKEN_STRIP:`editor-token-strip`,EDITOR_INSPECTOR_POPOVER:`editor-inspector-popover`,EDITOR_INSPECTOR_DRAWER:`editor-inspector-drawer`,EDITOR_INSPECTOR_DRAWER_TOGGLE:`editor-inspector-drawer-toggle`,EDITOR_INSPECTOR_SCRUBBER:`editor-inspector-scrubber`,EDITOR_INSPECTOR_DIFF_BADGE:`editor-inspector-diff-badge`,EDITOR_BLOCK_SETTINGS_BTN:`editor-block-settings-btn`,EDITOR_LINT_QUICK_FIX:`editor-lint-quick-fix`,EDITOR_OVERFLOW_ACTIONS_BTN:`editor-overflow-actions-btn`,EDITOR_OVERFLOW_ACTIONS_MENU:`editor-overflow-actions-menu`,EDITOR_WIKI_PICKER_ITEM:`editor-wiki-picker-item`,EDITOR_DEFINE_EFFORT_BTN:`editor-define-effort-btn`,EDITOR_DEFINE_EQUIPMENT_BTN:`editor-define-equipment-btn`,EDITOR_DEFINE_ALIAS_BTN:`editor-define-alias-btn`,EDITOR_DEFINE_TAG_BTN:`editor-define-tag-btn`,EDITOR_TOKEN_DELETE_BTN:`editor-token-delete-btn`,EDITOR_TOKEN_PREV_BTN:`editor-token-prev-btn`,EDITOR_TOKEN_NEXT_BTN:`editor-token-next-btn`,EDITOR_SCRUBBER_TOGGLE_BTN:`editor-scrubber-toggle-btn`,EDITOR_BLOCK_TIMELINE_ROW:`editor-block-timeline-row`,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_ROOT:`efforts-root`,EFFORTS_SEARCH:`efforts-search`,EFFORTS_CREATE_BTN:`efforts-create-btn`,EFFORTS_EMPTY_STATE:`efforts-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`,EQUIPMENT_INLINE_BACKLINKS:`equipment-inline-backlinks`,COMMAND_PALETTE_TRIGGER:`command-palette-trigger`,COMMAND_PALETTE_INPUT:`command-palette-input`,COMMAND_PALETTE_RESULTS:`command-palette-results`,NAV_L1_HOME:`nav-l1-home`,NAV_L1_JOURNAL:`nav-l1-journal`,NAV_L1_LIBRARY:`nav-l1-library`,NAV_L1_DASHBOARDS:`nav-l1-dashboards`,NAV_L1_SEARCH:`nav-l1-search`,MOBILE_NAV_OPEN:`mobile-nav-open`,MOBILE_NAV_DRAWER:`mobile-nav-drawer`,MOBILE_NAV_CLOSE:`mobile-nav-close`,DRAWER_APPLY_BTN:`drawer-apply-btn`,INSPECTOR_DRAWER_RAIL_SPACER:`inspector-drawer-rail-spacer`,LIBRARY_ROW_OVERFLOW:`library-row-overflow`,LIBRARY_ACTION_OPEN:`action-open`,LIBRARY_ACTION_NOTEBOOK:`action-notebook`,LIBRARY_ACTION_ADD:`action-add`,LIBRARY_ACTION_RUN:`action-run`,LIBRARY_ACTION_COMPARE:`action-compare`,LIBRARY_PUBLISH_LOCAL_FEED:`row-publish-local-feed`,NEW_ENTRY_PRIMARY:`new-entry-primary`,STREAM_VIEW:`queriable-stream-view`,STREAM_FEED_ITEM:`stream-feed-item`,STREAM_QUERY_BAR:`stream-query-bar`,STREAM_QUERY_BAR_DOCK:`stream-query-bar-dock`,STREAM_QUERY_SUMMARY:`stream-query-summary`,STREAM_QUERY_STATUS:`stream-query-status`,STREAM_QUERY_ERROR:`stream-query-error`,SAVE_STREAM_QUERY:`save-stream-query`,WQL_COMPOSER_ROOT:`wql-composer-root`,WQL_COMPOSER:`wql-composer`,WQL_SCOPE_TOGGLE:`wql-scope-toggle`,WQL_SCOPE_CLOSE:`wql-scope-close`,WQL_SCOPE_MAP:`wql-scope-map`,WQL_ZONE_WHAT:`wql-zone-what`,WQL_ZONE_WHERE:`wql-zone-where`,WQL_ZONE_WHEN:`wql-zone-when`,WQL_ZONE_GROUP:`wql-zone-group`,WQL_ADD_FILTER_BTN:`wql-add-filter-btn`,WQL_FIELD_PICKER:`wql-field-picker`,WQL_FILTER_TYPEAHEAD:`wql-filter-typeahead`,WQL_TEXT_INPUT:`wql-text-input`,WQL_SEGMENT_NEXT:`wql-segment-next`,WQL_SEGMENT_PREVIOUS:`wql-segment-previous`,WQL_CLAUSE_EDITOR_DONE:`wql-clause-editor-done`,REMOTE_NOTEBOOK_PREVIEW_BANNER:`remote-notebook-preview-banner`,WIDGET_COMPOSER_SUBSET:`widget-composer-subset`,WIDGET_COMPOSER_WQL:`widget-composer-wql`,WIDGET_COMPOSER_APPLY:`widget-composer-apply`,PROPERTY_TABLE:`property-table`,LIBRARY_ROW_NOTEBOOK:`library-row-notebook`,NOTEBOOKS_CREATE_BUTTON:`notebooks-create-button`,ENTRY_CREATE_TITLE_INPUT:`entry-create-title-input`,ENTRY_CREATE_BODY_INPUT:`entry-create-body-input`,ENTRY_CREATE_DATE_INPUT:`entry-create-date-input`,ENTRY_CREATE_SUBMIT_BTN:`entry-create-submit-btn`,ENTRY_CREATE_CANCEL_BTN:`entry-create-cancel-btn`,NOTEBOOK_DIALOG_NAME_INPUT:`notebook-dialog-name-input`,NOTEBOOK_DIALOG_SAVE_BTN:`notebook-dialog-save-btn`,PLACEMENT_DIALOG:`placement-dialog`,PLACEMENT_DATE_INPUT:`placement-date-input`,PLACEMENT_SLUG_INPUT:`placement-slug-input`,PLACEMENT_ADD_BTN:`placement-add-btn`,PLACEMENT_MOVE_BTN:`placement-move-btn`,PLACEMENT_REMOVE_BTN:`placement-remove-btn`,PLACEMENT_CLONE_SUBMIT_BTN:`placement-clone-submit-btn`,PUBLICATION_PILL:`publication-pill`,PUBLICATION_PILL_POPOVER:`publication-pill-popover`,PROMOTION_PROVENANCE_ROW:`promotion-provenance-row`,PROMOTION_CLONE_READONLY_BTN:`promotion-clone-readonly-btn`,PROMOTION_NEW_NOTEBOOK_INPUT:`promotion-new-notebook-input`,PROMOTION_NEW_NOTEBOOK_SUBMIT:`promotion-new-notebook-submit`,PUBLICATION_NOTEBOOK_PUBLIC_TOGGLE:`publication-notebook-public-toggle`,PUBLICATION_EXPORT_REPO_ZIP_BTN:`publication-export-repo-zip-btn`,PROPERTY_OVERRIDE_SHEET:`property-override-sheet`,PROPERTY_OVERRIDE_EDITOR:`property-override-editor`,PROPERTY_OVERRIDE_SAVE_BTN:`property-override-save-btn`,PROPERTY_OVERRIDE_CANCEL_BTN:`property-override-cancel-btn`,TIMER_FULLSCREEN_OVERLAY:`timer-fullscreen-overlay`,TIMER_DETAIL_SURFACE:`timer-detail-surface`,SYNC_SUBSCRIBED_ONLY_TOGGLE:`sync-subscribed-only-toggle`,UNKNOWN_FEED_INTAKE_BANNER:`unknown-feed-intake-banner`,FEED_INTAKE_SUBSCRIBE:`feed-intake-subscribe`,FEED_INTAKE_ONCE:`feed-intake-once`,FEED_SUBSCRIPTION_INTAKE:`feed-subscription-intake`,REGISTERED_FEED_INTAKE_CARD:`registered-feed-intake-card`,REGISTERED_FEED_SUBSCRIBE_BTN:`registered-feed-subscribe-btn`,FEED_DETAIL_SUBSCRIBE_BUTTON:`feed-detail-subscribe-button`,HALTED_RUN_NOTICE:`halted-run-notice`,NOTEBOOK_NOT_FOUND:`notebook-not-found`,STREAM_QUERY_SYNTAX_HINT:`stream-query-syntax-hint`,DELETE_DASHBOARD_BUTTON:`delete-dashboard-button`,CONFIRM_DELETE_DASHBOARD:`confirm-delete-dashboard`,NOTE_DELETE_DIALOG:`note-delete-dialog`,NOTE_DELETE_CANCEL:`note-delete-cancel`,NOTE_DELETE_CONFIRM:`note-delete-confirm`,NOTE_LOADING_SETTLING:`note-loading-settling`,NOTEBOOK_DELETE_DIALOG:`notebook-delete-dialog`,TAG_LOADING_SETTLING:`tag-loading-settling`,TAG_NOT_FOUND:`tag-not-found`,TAG_NOT_FOUND_CREATE_BTN:`tag-not-found-create-btn`,EXPLORER_INVALID_URL_ALERT:`explorer-invalid-url-alert`,EXPLORER_FIND_ADVISORIES:`explorer-find-advisories`,RUNTIME_ERROR_BANNER:`runtime-error-banner`,CONDITIONS_NAV_RECENT:`conditions-nav-recent`,LOAD_ZIP_INTAKE:`load-zip-intake`,BUNDLE_FILE_INPUT:`bundle-file-input`,BUNDLE_IMPORT_ERROR:`bundle-import-error`,AGENT_CONFIRM_DIALOG:`agent-confirm-dialog`,AGENT_CONFIRM_APPROVE:`agent-confirm-approve`,AGENT_CONFIRM_CANCEL:`agent-confirm-cancel`,WEBMCP_DEBUG_INSPECTOR:`webmcp-debug-inspector`,PALETTE_MODE:`palette-mode`,PALETTE_COMPOSER:`palette-composer`,PALETTE_FIND_INPUT:`palette-find-input`,PALETTE_SCOPE_CHIP:`palette-scope-chip`,PALETTE_SCOPE_CLEAR:`palette-scope-clear`,PALETTE_MOBILE_VIEW_TOGGLE:`palette-mobile-view-toggle`,PALETTE_SETTINGS:`palette-settings`,PALETTE_SETTINGS_PANEL:`palette-settings-panel`,PALETTE_STALE:`palette-stale`,PALETTE_CANCEL:`palette-cancel`,PALETTE_APPLY_QUERY:`palette-apply-query`,tour:{HOME_TOUR:`home-tour`,HERO:`tour-hero`,HERO_RESET_SHARED:`tour-hero-reset-shared`,SECTION_EDITOR:`tour-section-editor`,EDITOR_RESET_EDITED:`tour-editor-reset-edited`,WHY_WATCH_AGAIN:`tour-why-watch-again`,WHY_VIDEO:`tour-why-video`,WHY_VIDEO_SKIP:`tour-why-video-skip`,SCROLL_HINT:`tour-scroll-hint`,SECTION_INSIGHTS:`tour-section-insights`,INSIGHTS_EMPTY:`tour-insights-empty`,INSIGHTS_RUN:`tour-insights-run`,INSIGHTS_RECORDED:`tour-insights-recorded`,INSIGHTS_AGAIN:`tour-insights-again`,INSIGHTS:`tour-insights`,INSIGHTS_TIMELINE:`tour-insights-timeline`,INSIGHTS_IMPATIENCE:`tour-insights-impatience`,INSIGHTS_REACTION:`tour-insights-reaction`,PANE_BACK_TO_EDITOR:`tour-pane-back-to-editor`,STICKY_PANE:`tour-sticky-pane`,SESSION_DASHBOARD:`tour-session-dashboard`,SESSION_DASHBOARD_SOURCE:`tour-session-dashboard-source`,WOD_BLOCK_REGION:`tour-wod-block-region`,RUN_BUTTON_REGION:`tour-run-button-region`,JUMP_SECTION:`tour-jump-section`,JUMP_FILTERS_TOGGLE:`jump-filters-toggle`,JUMP_FILTERS_PANEL:`jump-filters-panel`,LEARN:`tour-learn`,FOOTER:`tour-footer`,CHAPTER_PICKER:`tour-chapter-picker`,CAPTIONS:`tour-captions`,RING:`tour-ring`},OUTPUT_STATEMENTS_TABLE:`output-statements-table`,RESULTS_PAGE:`session-results-page`,RESULTS_SESSION_KPI_STRIP:`results-session-kpi-strip`,RESULTS_SOURCE_DRAWER_BTN:`results-source-drawer-btn`,RESULTS_SOURCE_DRAWER:`results-source-drawer`,RESULTS_MOBILE_BAR:`results-mobile-bar`,RESULTS_EMPTY_RECOVERY:`results-empty-recovery`,RESULTS_ADD_DASHBOARD_BTN:`results-add-dashboard-btn`,MOBILE_WHEEL_COMPOSER:`mobile-wheel-composer`,MOBILE_TYPING_BAR:`mobile-typing-bar`,ADD_DASHBOARD_SHEET:`add-to-dashboard-sheet`,ADD_DASHBOARD_STEP_NEXT:`add-dashboard-step-next`,ADD_DASHBOARD_STEP_BACK:`add-dashboard-step-back`,ADD_DASHBOARD_COMMIT:`add-dashboard-commit`,ADD_DASHBOARD_OPEN_STUDIO:`add-dashboard-open-studio`,ADD_DASHBOARD_CLONE_PREBUILT:`add-dashboard-clone-prebuilt`,ADD_DASHBOARD_MODE_EXISTING:`add-dashboard-mode-existing`,ADD_DASHBOARD_MODE_CLONE:`add-dashboard-mode-clone`,ADD_DASHBOARD_MODE_NEW:`add-dashboard-mode-new`,ADD_DASHBOARD_NEW_TITLE:`add-dashboard-new-title`,ADD_DASHBOARD_WQL_DISCLOSURE:`add-dashboard-wql-disclosure`,DASHBOARD_DEST_CLONE:`dashboard-dest-clone`,DASHBOARD_DEST_NEW:`dashboard-dest-new`,PAGES_SUB_ORPHANED_NOTES:`pages-sub-orphaned-notes`,STREAM_VIEW_POPOVER_TRIGGER:`stream-view-popover-trigger`,STREAM_VIEW_POPOVER_CONTENT:`stream-view-popover-content`,CALENDAR_OVERLAY_FILTER:`calendar-overlay-filter`,CALENDAR_PEEK_DRAWER:`calendar-peek-drawer`,CALENDAR_PEEK_CLOSE:`calendar-peek-close`,CALENDAR_MORE_POPOVER:`calendar-more-popover`,CALENDAR_UNDATED_TOGGLE:`calendar-undated-toggle`,NOTEBOOK_BATCH_SCHEDULE_BAR:`notebook-batch-schedule-bar`,NOTEBOOK_BATCH_SCHEDULE_SUBMIT:`notebook-batch-schedule-submit`,NOTE_SHARED_BANNER:`note-shared-banner`,NOTE_REVISIONS_NOTICE:`note-revisions-notice`,NOTE_SCHEDULES_TAB:`note-schedules-tab`,RUNNER_CONTEXT_PILL:`runner-context-pill`,SESSION_ATTRIBUTION_CARD:`session-attribution-card`,SESSION_SMART_MATCH_BANNER:`session-smart-match-banner`,DAY_SCHEDULED_SECTION:`day-scheduled-section`,DAY_LOGGED_SECTION:`day-logged-section`,L3_RIGHT_DRAWER:`l3-right-drawer`,L3_INLINE_RAIL:`l3-inline-rail`,L3_CONNECTIONS:`l3-connections`,L3_ACTIONS:`l3-actions`,L3_ACTIONS_PRIMARY:`l3-actions-primary`,L3_ACTIONS_GROUP_AUTHOR:`l3-actions-group-author`,L3_ACTIONS_GROUP_ORGANIZE:`l3-actions-group-organize`,L3_ACTIONS_GROUP_SHARE:`l3-actions-group-share`,L3_ACTIONS_DANGER:`l3-actions-danger`,L3_ANALYTICS_CONTROLS:`l3-analytics-controls`,L3_RANGE_OPTIONS:`l3-range-options`,L3_UNIT_OPTIONS:`l3-unit-options`,L3_DRAWER_DONE_BTN:`l3-drawer-done-btn`,L3_DRAWER_RESET_BTN:`l3-drawer-reset-btn`,PEEK_DRAWER_SLOT:`peek-drawer-slot`,PEEK_DRAWER_BACKDROP:`peek-drawer-backdrop`,ACTIONS_DOCK:`actions-dock`,ACTIONS_OVERFLOW:`actions-overflow`,ACTIONS_SHEET_L3:`actions-sheet-l3`,BOOT_IMPORT_PROGRESS:`boot-import-progress`,ENTITY_PEEK_DRAWER:`entity-peek-drawer`,ENTITY_PEEK_BACKDROP:`entity-peek-backdrop`,ENTITY_PEEK_CLOSE:`entity-peek-close`,ENTITY_PEEK_OPEN_FULL:`entity-peek-open-full`,ENTITY_PEEK_FILTER_NOTES:`entity-peek-filter-notes`,ENTITY_PEEK_VIEW_ALL_NOTES:`entity-peek-view-all-notes`,ENTITY_PEEK_CREATE_FORM:`entity-peek-create-form`,ENTITY_PEEK_CREATE_KIND:`entity-peek-create-kind`,ENTITY_PEEK_CREATE_LABEL:`entity-peek-create-label`,ENTITY_PEEK_CREATE_SLUG:`entity-peek-create-slug`,ENTITY_PEEK_CREATE_CATEGORY:`entity-peek-create-category`,ENTITY_PEEK_CREATE_SUBMIT:`entity-peek-create-submit`,CALENDAR_PEEK_BACKDROP:`calendar-peek-backdrop`,CALENDAR_DAY_HEADER:`calendar-day-header`,SCHEDULE_PEEK_DAY_CUE_INPUT:`schedule-peek-day-cue-input`,SCHEDULE_PEEK_DAY_CUE_SAVE:`schedule-peek-day-cue-save`,SCHEDULE_PEEK_FORK_BTN:`schedule-peek-fork-btn`,SCHEDULE_PEEK_BLOCK_SELECT:`schedule-peek-block-select`,SCHEDULE_PEEK_PLAN_FOR_DATE:`schedule-peek-plan-for-date`,SCHEDULE_PEEK_OPEN_DAY:`schedule-peek-open-day`,DAY_PLAN_CUE_INPUT:`day-plan-cue-input`,DAY_PLAN_CUE_SAVE:`day-plan-cue-save`,DAY_PLAN_FORK_BTN:`day-plan-fork-btn`,STREAM_FACET_FILTER_TRIGGER:`stream-facet-filter-trigger`,STREAM_FACET_FILTER_BADGE:`stream-facet-filter-badge`,STREAM_FACET_FILTER_POPOVER:`stream-facet-filter-popover`,STREAM_MOBILE_FACETS:`stream-mobile-facets`,STREAM_VIEW_ADD_ACTION:`stream-view-add-action`,STREAM_PAGE_HEADING:`stream-page-heading`,FACET_PILL_INCLUDE:`facet-pill-include`,FACET_PILL_EXCLUDE:`facet-pill-exclude`,FACET_PILL_OFF:`facet-pill-off`,PAGE_HEADER_PARENT_BREADCRUMB:`page-header-parent-breadcrumb`,DASHBOARD_EDIT_TOGGLE:`dashboard-edit-toggle`,EXPLORER_INLINE_BAR:`explorer-inline-bar`,EXPLORER_EXAMPLES_TRIGGER:`explorer-examples-trigger`,EXPLORER_EXAMPLES_POPOVER:`explorer-examples-popover`,EXPLORER_UNIT_KG:`explorer-unit-kg`,EXPLORER_UNIT_LB:`explorer-unit-lb`,EXPLORER_RUN_BTN:`explorer-run-btn`,EXPLORER_QUERY_SETTINGS_BTN:`explorer-query-settings-btn`,L3_EFFORT_OVERRIDE:`l3-effort-override`,L3_EFFORT_SHOW_RESOLVED:`l3-effort-show-resolved`,L3_EQUIPMENT_OVERRIDE:`l3-equipment-override`,L3_FEED_DOWNLOAD_OFFLINE:`l3-feed-download-offline`,L3_FEED_UNSUBSCRIBE:`feed-detail-unsubscribe-button`,L3_DASHBOARD_CLONE:`l3-dashboard-clone`,L3_DASHBOARD_DELETE:`l3-dashboard-delete`,L3_PLAYGROUND_MOVE_JOURNAL:`l3-playground-move-journal`},IG={tags:`tag`},LG={source:!0},RG={text:!0};function zG(e){return IG[e]??e}function BG(e){return!!RG[e]}function VG(e){switch(e){case`note`:return`note`;case`effort`:return`effort`;default:return null}}function HG(e){return e.wildcard?`${e.value}*`:e.value}function UG(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 WG(e,t,n){let r=[];for(let i of UG(e,t))i.values.forEach((e,t)=>{let a=HG(e);r.push({display:a,negate:i.negate,label:n?.get(i.negate?a:e.value),occurrence:i,valueIndex:t})});return r}function GG(e,t,n){if(t===`source`)return QG(e,n);let r=Xg(e);if(r.error||!Fg(r))return e;let i=UG(r,t).filter(e=>!e.negate);if(i.length>0&&!LG[t]){let r=i[i.length-1];return tK(e,t,r,[...r.values.map(HG),n].join(`|`))}if(i.length>0)return tK(e,t,i[i.length-1],n);let a=vA(e,nK(t,zG(t),``),n);return a.valid?a.wql:e}function KG(e,t,n){let r=n.occurrence.values.filter((e,t)=>t!==n.valueIndex).map(HG).join(`|`);return tK(e,t,n.occurrence,r||null)}function qG(e,t,n){let r=Xg(e);if(r.error||!Fg(r))return`off`;if(t===`source`&&eK(r)===n)return`include`;let i=UG(r,t);return i.some(e=>!e.negate&&e.values.some(e=>HG(e)===n))?`include`:i.some(e=>e.negate&&e.values.some(e=>HG(e)===n))?`exclude`:`off`}function JG(e,t,n,r){return qG(e,t,n)===r?e:r===`off`?YG(e,t,n,`both`):r===`include`?GG(YG(e,t,n,`negative`),t,n):XG(YG(e,t,n,`positive`),t,n)}function YG(e,t,n,r){let i=e;for(;;){let e=Xg(i);if(e.error||!Fg(e))return i;if(t===`source`&&r!==`negative`&&eK(e)===n){let e=QG(i,null);if(e===i)return i;i=e;continue}let a=UG(e,t).find(e=>(r===`both`||r===(e.negate?`negative`:`positive`))&&e.values.some(e=>HG(e)===n));if(!a)return i;let o=a.values.findIndex(e=>HG(e)===n),s=KG(i,t,{display:n,negate:a.negate,occurrence:a,valueIndex:o});if(s===i)return i;i=s}}function XG(e,t,n){let r=Xg(e);if(r.error||!Fg(r))return e;let i=UG(r,t).filter(e=>e.negate);if(i.length>0){let r=i[i.length-1];return r.values.some(e=>HG(e)===n)?e:tK(e,t,r,[...r.values.map(HG),n].join(`|`))}let a=vA(e,{...nK(t,zG(t),``),negate:!0},n);return a.valid?a.wql:e}function ZG(e,t){let n=t.trim(),r=e,i=!1;for(;;){let e=Xg(r);if(e.error||!Fg(e))return r;let t=UG(e,`text`).filter(e=>!e.negate);if(t.length===0){if(!n||i)return r;let e=vA(r,nK(`text`,zG(`text`),``),n);return e.valid?e.wql:r}if(!n){let e=tK(r,`text`,t[0],null);if(e===r)return r;r=e;continue}if(!i){let e=tK(r,`text`,t[0],n);if(e===r)return r;r=e,i=!0;continue}if(t.length===1)return r;let a=tK(r,`text`,t[1],null);if(a===r)return r;r=a}}function QG(e,t){let n=Xg(e);if(n.error||!Fg(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=Yh.filter(t=>e.startsWith(`:${t}`)).sort((e,t)=>t.length-e.length)[0],o=a?Xh[a]:void 0;if(!t){if(!o)return A_({...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 A_({...n,sourceScope:void 0,filters:t})}let s=t===`journal`?`:journal`:t===`notebooks`?`:notebooks`:t===`playground`?`:playground`:`:note{source:${t}}`,c=Xg(s.startsWith(`:note`)?s:`${s}{}`);if(c.error||!Fg(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 A_({...n,sourceScope:void 0,filters:u})}function $G(e,t,n){let r=Xg(e);if(r.error||!Fg(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 A_({...r,groupBy:a.length>0?a:void 0})}function eK(e){return e.filters.find(e=>e.key===`source`&&!e.negate)?null:e.sourceScope?.length===1?e.sourceScope[0]:null}function tK(e,t,n,r){let i=vA(e,{...nK(t,zG(t),n.values.map(HG).join(`|`)),filterIndex:n.filterIndex,negate:n.negate},r);return i.valid?i.wql:e}function nK(e,t,n){return{id:`nav-${e}`,type:t,...Hk(t),value:n}}function rK(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=zh.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:notebook`:case`block:notebook`:(r.notebookId||r.sourceNotebook)&&i(r.notebookId??r.sourceNotebook);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.sourceNotebook??r.id)??n.tagMembership.get(r.id)??[];for(let t of e)(a===`tags`||t.type===a)&&i(t.label)}else if(o){let e=n.effortMembership.get(r.sourceNotebook??r.id)??n.effortMembership.get(r.id)??[];for(let t of e)i(t)}}if(e===`note`&&t===`source`)return Jh.map(e=>({value:e,count:n.entries.filter(t=>qy({id:t.id,sourceId:t.sourceId,type:t.noteType},e)).length})).filter(e=>e.count>0);if(e===`block`&&t===`source`)return Jh.map(e=>({value:e,count:n.entries.filter(t=>qy({id:t.id,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.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 iK=e=>e.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1)})),aK={source:{enabled:!1,expectedValues:iK(Jh)},page:{enabled:!1,expectedValues:[{value:`true`,label:`Pages`},{value:`false`,label:`Non-pages`}]},intensity:{expectedValues:iK(Gh)},discipline:{expectedValues:iK(_v)}};function oK(e){return aK[e]??{}}var sK=[],cK=e=>new URLSearchParams(e.search).get(`q`)??``;async function lK(){let[e,t]=await Promise.all([X.getNoteTagLabelsBatch(),X.getAllNotes()]);for(let n of t){let t=e.get(n.id),r=By(n.sourceId);if(!r||!t?.length)continue;let i=e.get(r);if(i)for(let e of t)i.some(t=>t.label===e.label)||i.push(e);else e.set(r,t.map(({label:e,type:t})=>({label:e,type:t})))}return e}function uK(e,t,n){let r=new URLSearchParams(e.search);r.set(`q`,n),t(`${e.pathname}?${r.toString()}`)}function dK({query:e,onQueryChange:t,className:n,heading:r=`Filters`}={}){let i=Qe(),a=dt(),o=RW(),s=e===void 0?cK(i):e,c=sW(hH(i.pathname)),l=s&&!Xg(s).error?s:c.defaultWql,u=(0,K.useMemo)(()=>Xg(l),[l]),d=(0,K.useMemo)(()=>!u.error&&Fg(u)?u:null,[u]),f=o&&o.pathname===i.pathname&&o.query===l?o.entries:null,[p,m]=(0,K.useState)(null);(0,K.useEffect)(()=>{o&&o.pathname===i.pathname&&m(o)},[o,i.pathname]);let h=f===null&&p!==null&&p.pathname===i.pathname,g=f??(h?p.entries:sK),_=d?VG(d.target):null,v=!!d&&!!_&&UG(d,_).length>0,y=(0,K.useMemo)(()=>d?vg(d.target,`find`).filter(e=>e!==_||v):[],[d,_,v]),b=y.some(e=>e===`tags`||zh.includes(e)),x=y.includes(`effort`),[S,C]=(0,K.useState)({tags:null,efforts:null});(0,K.useEffect)(()=>{if(!b&&!x||g.length===0)return;let e=!1;return Promise.all([b?lK():null,x?X.getEffortSlugsByNoteBatch():null]).then(([t,n])=>{e||C({tags:t,efforts:n})}).catch(()=>{e||C({tags:null,efforts:null})}),()=>{e=!0}},[b,x,g]);let w=(0,K.useMemo)(()=>({entries:g,tagMembership:S.tags,effortMembership:S.efforts}),[g,S]),T=(0,K.useRef)(new Map),E=T.current.get(i.pathname);E||(E=new Map,T.current.set(i.pathname,E));let D=f!==null||p!==null,O=t??(e=>uK(i,a,e)),k=d?eK(d):null,A=(0,K.useMemo)(()=>y.filter(e=>oK(e).enabled!==!1).sort((e,t)=>(oK(e).order??0)-(oK(t).order??0)),[y]);return d?(0,q.jsxs)(`div`,{className:ra(`flex flex-col gap-1`,n),"aria-busy":h||void 0,"data-testid":`l3-filters`,children:[r!==null&&(0,q.jsx)(`div`,{className:`px-1 text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground`,children:r}),A.map(e=>(0,q.jsx)(`div`,{"data-testid":`conditions-section-${e}`,children:(0,q.jsx)(mK,{query:l,parsed:d,entryKey:e,facetContext:w,labels:fK(d.target,e,g),headScope:e===`source`?k:null,pending:h,hasEverPublished:D,routeKnownOptions:E,onApply:O})},e))]}):null}function fK(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.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 pK=[{state:`include`,label:`Include`,testIdPrefix:Q.FACET_PILL_INCLUDE},{state:`exclude`,label:`Exclude`,testIdPrefix:Q.FACET_PILL_EXCLUDE},{state:`off`,label:`Off`,testIdPrefix:Q.FACET_PILL_OFF}];function mK({query:e,parsed:t,entryKey:n,facetContext:r,labels:i,headScope:a,pending:o,hasEverPublished:s,routeKnownOptions:c,onApply:l}){let u=Qe(),d=oK(n);if(d.enabled===!1)return null;let f=Hk(zG(n)),p=BG(n)||gK[n]!==void 0,m=WG(t,n,i),h=n===`text`?UG(t,`text`).filter(e=>!e.negate).map(e=>e.values.map(e=>e.value).join(`|`)).join(`|`):null,g=rK(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:qG(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`)||u.pathname.startsWith(`/day`),E=d.hideZero||n===`effort`||T&&(n===`tags`||zh.includes(n))?x.filter(e=>e.count!==null&&e.count>0||e.state!==`off`):x;return E.length===0&&!p?null:(0,q.jsxs)(FG,{title:d.label??f.label,count:E.length,defaultOpen:x.some(e=>e.state!==`off`)||p,sticky:!0,buttonClassName:`gap-1.5 py-2 max-lg:min-h-11 text-xs font-semibold normal-case tracking-normal text-foreground [&>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.5 [&>span:last-child]:bg-transparent [&>span:last-child]:text-[11px] [&>span:last-child]:font-semibold [&>span:last-child]:text-muted-foreground`,bodyClassName:`px-2 pb-1`,children:[(0,q.jsx)(`ul`,{className:`flex flex-col gap-0.5`,children:E.map(t=>(0,q.jsx)(hK,{query:e,entryKey:n,row:t,pending:o,onApply:l},t.value))}),p&&(0,q.jsx)(_K,{entryKey:n,placeholder:f.placeholder,pending:o,currentText:h??void 0,onTextChange:t=>l(ZG(e,t)),onApply:t=>l(JG(e,n,t,`include`))})]})}function hK({query:e,entryKey:t,row:n,pending:r,onApply:i}){let a=n.count===0&&n.state===`off`;return(0,q.jsx)(`li`,{"data-testid":`conditions-row-${t}:${n.value}`,className:ra(`rounded-md px-1 py-0.5`,r&&`opacity-70`),children:(0,q.jsxs)(`div`,{className:`flex min-h-9 max-lg:min-h-11 flex-wrap items-center gap-1.5`,children:[(0,q.jsx)(`span`,{className:ra(`min-w-0 flex-1 truncate text-xs leading-4`,a?`text-muted-foreground`:`font-medium text-foreground`),children:n.label}),n.count!==null&&(0,q.jsx)(`span`,{className:`shrink-0 text-[11px] leading-4 tabular-nums text-muted-foreground`,children:n.count}),(0,q.jsx)(`div`,{role:`group`,"aria-label":`Filter state for ${n.label}`,className:`inline-flex shrink-0 items-center rounded-md border border-border/70 bg-muted/40 p-0.5`,children:pK.map(a=>{let o=n.state===a.state;return(0,q.jsx)(`button`,{type:`button`,"data-testid":`${a.testIdPrefix}-${t}:${n.value}`,"data-state":o?`active`:`inactive`,"aria-pressed":o,"aria-label":`${a.label} ${n.label}`,disabled:r,onClick:()=>{let r=a.state===`off`||o?`off`:a.state;i(JG(e,t,n.value,r))},className:ra(`inline-flex cursor-pointer items-center justify-center rounded px-2 py-0.5 text-[11px] font-semibold max-lg:min-h-11 max-lg:px-2.5 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default`,o&&a.state===`include`&&`bg-primary text-primary-foreground shadow-xs`,o&&a.state===`exclude`&&`bg-destructive text-destructive-foreground shadow-xs`,o&&a.state===`off`&&`bg-background text-foreground shadow-xs`,!o&&`text-muted-foreground hover:bg-muted hover:text-foreground`),children:a.label},a.state)})})]})})}var gK={note:!0,block:!0,result:!0};function _K({entryKey:e,placeholder:t,pending:n,currentText:r,onTextChange:i,onApply:a}){let[o,s]=(0,K.useState)(``);return e===`text`?(0,q.jsx)(`div`,{className:`px-1 py-1.5`,children:(0,q.jsx)(`input`,{value:r??``,onChange:e=>i?.(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-text`,className:`h-9 max-lg:min-h-11 w-full min-w-0 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})}):(0,q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=o.trim();t&&(a(t),s(``))},className:`flex items-center gap-1.5 px-1 py-1.5`,children:[(0,q.jsx)(`input`,{value:o,onChange:e=>s(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-${e}`,disabled:n,className:`h-9 max-lg:min-h-11 min-w-0 flex-1 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),(0,q.jsx)(`button`,{type:`submit`,"aria-label":`Add ${t}`,"data-testid":`conditions-add-${e}`,disabled:n||!o.trim(),className:`flex size-9 max-lg:min-h-11 max-lg:min-w-11 shrink-0 items-center justify-center rounded-md border border-border 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,q.jsx)(ti,{"aria-hidden":`true`,className:`size-3.5`})})]})}var vK=e=>new URLSearchParams(e.search).get(`q`)??``,yK=`wodwiki.recentVisitedHrefs:v1`,bK=20,xK=[/^\/notebook\//,/^\/note\//,/^\/effort\//,/^\/equipment\//,/^\/dashboard\//,/^\/feed\//];function SK(e){if(xK.some(t=>t.test(e)))try{let t=[e,...wK().filter(t=>t!==e)].slice(0,bK);localStorage.setItem(yK,JSON.stringify(t))}catch{}}function CK(e){try{let t=wK(),n=t.filter(t=>t!==e);n.length!==t.length&&localStorage.setItem(yK,JSON.stringify(n))}catch{}}function wK(){try{let e=JSON.parse(localStorage.getItem(yK)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function TK(e){return function(t){let n=Qe(),r=dt(),i=sW(e.profile),a=vK(n),o=a&&!Xg(a).error?a:i.defaultWql,s=e=>uK(n,r,e),c=ZH(),l=RW(),u=l&&l.pathname===n.pathname&&l.query===o?l.entries:[],d=new Map(wK().map((e,t)=>[e,t])),f=[...u].sort((e,t)=>{let n=d.get(TG(e)),r=d.get(TG(t));return n!==void 0&&r!==void 0?n-r:n===void 0?r===void 0?0:1:-1}).slice(0,5);(0,K.useEffect)(()=>{SK(n.pathname)},[n.pathname]);let p=kW(e.route),m=hW(e.route),h={pathname:n.pathname,query:vK(n)},g=p.find(e=>e.id===`all`)??null,v=p.filter(e=>e.to===void 0&&e.id!==`all`),y=g?.wql??``,b=g?.label??e.landingLabel,x=g?cW[g.icon]:e.icon,S=!!e.extraChildren?.some(e=>e.isActive?.(n)),C=h.query&&!S&&!Xg(h.query).error&&!p.some(e=>jW(e,h))?o:null,[w,T]=(0,K.useState)(!1),[E,D]=(0,K.useState)(null),[O,k]=(0,K.useState)(null),A=e=>{k(null),D({mode:`create`,label:``,icon:`bookmark`,wql:e})},j=e=>{k(null),D({mode:`edit`,targetId:e.id,label:e.label,icon:e.icon,wql:e.wql,fixedRoute:e.to})},M=async(t,n)=>{let r=SW(e.route,void 0,m),i=v.findIndex(e=>e.id===t),a=i+n;if(i<0||a<0||a>=v.length)return;let o=v[i].id,s=v[a].id,c=r.findIndex(e=>e.id===o),l=r.findIndex(e=>e.id===s);if(c<0||l<0)return;let u=[...r],d=u[c];u[c]=u[l],u[l]=d,await CW(e.route,u)},N=async t=>{if(t.id===`all`||t.to)return;let n=jW(t,h),i=SW(e.route,void 0,m).filter(e=>e.id!==t.id);await CW(e.route,i)&&(E?.targetId===t.id&&D(null),n&&(y?s(y):r(e.route)))},P=E?.label.trim()??``,F=E?.wql.trim()??``,I=E?.mode===`edit`&&E.targetId===`all`,ee=!!E?.fixedRoute,L=!I&&!ee,R=!ee&&F?xA(F).error??null:null,z=!!E&&P.length>0&&(!L||F.length>0)&&!R,B=async t=>{if(t.preventDefault(),!E||!z)return;let n=SW(e.route,void 0,m),i=E.targetId?n.find(e=>e.id===E.targetId)??null:null,a=i?jW(i,h):!1,c={id:i?.id??crypto.randomUUID(),label:P,icon:E.icon,wql:ee?i?.wql??``:F,...i?.to?{to:i.to}:{}},l=i?n.map(e=>e.id===i.id?c:e):[...n,c];if(!await CW(e.route,l)){k(`Couldn’t save — storage is unavailable.`);return}k(null),D(null),i&&a&&!c.to?c.wql?s(c.wql):r(e.route):!i&&c.wql&&c.wql!==o&&s(c.wql)},V=()=>E?(0,q.jsxs)(`form`,{onSubmit:B,"data-testid":`conditions-nav-inline-editor`,className:`my-1.5 flex flex-col gap-2 rounded-lg border border-border bg-card p-2.5 shadow-xs`,noValidate:!0,children:[(0,q.jsxs)(`div`,{className:`space-y-1`,children:[(0,q.jsx)(`label`,{htmlFor:`conditions-inline-shortcut-label`,className:`block text-[11px] font-semibold text-muted-foreground`,children:`Label`}),(0,q.jsx)(`input`,{id:`conditions-inline-shortcut-label`,type:`text`,value:E.label,onChange:e=>D(t=>t&&{...t,label:e.target.value}),placeholder:`e.g. Strength this month`,"aria-label":`Shortcut label`,"data-testid":`conditions-nav-editor-label`,autoFocus:!0,className:`w-full max-lg:min-h-11 rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40`})]}),!ee&&(0,q.jsxs)(`div`,{className:`space-y-1`,children:[(0,q.jsx)(`label`,{htmlFor:`conditions-inline-shortcut-wql`,className:`block text-[11px] font-semibold text-muted-foreground`,children:`Query (WQL)`}),(0,q.jsx)(`textarea`,{id:`conditions-inline-shortcut-wql`,rows:2,value:E.wql,onChange:e=>D(t=>t&&{...t,wql:e.target.value}),placeholder:L?`:note{...}`:`Empty — plain route landing`,"aria-label":`Shortcut query`,"data-testid":`conditions-nav-editor-wql`,"aria-invalid":R?!0:void 0,className:`w-full max-lg:min-h-11 rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40`}),R&&(0,q.jsxs)(`p`,{role:`alert`,"data-testid":`conditions-nav-editor-error`,className:`text-[11px] text-destructive`,children:[`Couldn't parse — `,R]})]}),(0,q.jsxs)(`fieldset`,{className:`space-y-1`,children:[(0,q.jsx)(`legend`,{className:`text-[11px] font-semibold text-muted-foreground`,children:`Icon`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:Object.entries(cW).map(([e,t])=>(0,q.jsx)(`button`,{type:`button`,title:e,"aria-label":`Icon ${e}`,"aria-pressed":E.icon===e,"data-testid":`conditions-nav-editor-icon-${e}`,onClick:()=>D(t=>t&&{...t,icon:e}),className:E.icon===e?`grid size-7 max-lg:min-h-11 max-lg:min-w-11 place-items-center rounded-md border border-primary bg-primary/10 text-primary`:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 place-items-center rounded-md border border-border text-muted-foreground hover:text-foreground`,children:(0,q.jsx)(t,{className:`size-3.5`,"aria-hidden":`true`})},e))})]}),O&&(0,q.jsx)(`p`,{role:`alert`,className:`text-[11px] text-destructive`,children:O}),(0,q.jsxs)(`div`,{className:`flex items-center justify-end gap-1.5 pt-0.5`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>{D(null),k(null)},"data-testid":`conditions-nav-editor-cancel`,className:`max-lg:min-h-11 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:`Cancel`}),(0,q.jsx)(`button`,{type:`submit`,disabled:!z,"data-testid":`conditions-nav-editor-save`,className:`max-lg:min-h-11 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50`,children:`Save`})]})]}):null,H=g??{id:`all`,label:e.landingLabel,icon:`bookmark`,wql:``};return(0,q.jsxs)(`div`,{className:`-mx-4 flex flex-col gap-1 py-3`,"data-testid":`conditions-nav-panel`,children:[(0,q.jsxs)(tU,{className:`px-6`,children:[(0,q.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-1 px-2`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-medium text-muted-foreground`,children:`Saved views`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>A(C??o),"aria-label":`Add saved link`,title:`Add saved link`,"data-testid":`conditions-nav-shortcut-add`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,q.jsx)(ti,{className:`size-3.5`,"aria-hidden":`true`})}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{T(e=>{let t=!e;return t||(D(null),k(null)),t})},"aria-label":w?`Done editing saved links`:`Edit saved links`,"aria-pressed":w,title:w?`Done`:`Edit saved links`,"data-testid":`conditions-nav-edit-toggle`,className:`inline-flex h-7 max-lg:min-h-11 items-center gap-1 rounded-md px-2 text-xs font-medium transition-colors ${w?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`}`,children:[w?(0,q.jsx)(zr,{className:`size-3.5`,"aria-hidden":`true`}):(0,q.jsx)(Nn,{className:`size-3`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:w?`Done`:`Edit`})]})]})]}),E?.mode===`create`&&V(),w?(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,"data-testid":`conditions-nav-manage-list`,children:[(0,q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1 rounded-lg px-2 py-1 text-sm text-foreground`,children:[x&&(0,q.jsx)(x,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-xs font-medium`,children:b}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>j(H),"aria-label":`Edit ${b}`,title:`Edit ${b}`,"data-testid":`conditions-nav-shortcut-edit-all`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground`,children:(0,q.jsx)(Nn,{className:`size-3.5`,"aria-hidden":`true`})})]}),E?.mode===`edit`&&E.targetId===`all`&&V()]}),v.map((e,t)=>{let n=cW[e.icon];return(0,q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-0.5 rounded-lg px-2 py-1 text-sm text-foreground`,"data-testid":`conditions-nav-manage-row-${e.id}`,children:[(0,q.jsx)(n,{className:`mr-1.5 size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-xs font-medium`,children:e.label}),v.length>1&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,disabled:t===0,onClick:()=>void M(e.id,-1),"aria-label":`Move ${e.label} up`,title:`Move up`,"data-testid":`conditions-nav-shortcut-up-${e.id}`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground disabled:opacity-30`,children:(0,q.jsx)(It,{className:`size-3.5`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,disabled:t===v.length-1,onClick:()=>void M(e.id,1),"aria-label":`Move ${e.label} down`,title:`Move down`,"data-testid":`conditions-nav-shortcut-down-${e.id}`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground disabled:opacity-30`,children:(0,q.jsx)(rt,{className:`size-3.5`,"aria-hidden":`true`})})]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>j(e),"aria-label":`Edit ${e.label}`,title:`Edit ${e.label}`,"data-testid":`conditions-nav-shortcut-edit-${e.id}`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground`,children:(0,q.jsx)(Nn,{className:`size-3.5`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>void N(e),"aria-label":`Delete ${e.label}`,title:`Delete ${e.label}`,"data-testid":`conditions-nav-shortcut-delete-${e.id}`,className:`grid size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,children:(0,q.jsx)(Me,{className:`size-3.5`,"aria-hidden":`true`})})]}),E?.mode===`edit`&&E.targetId===e.id&&V()]},`manage-${e.id}`)})]}):(0,q.jsxs)(q.Fragment,{children:[C?(0,q.jsxs)(`div`,{className:`flex items-center gap-1`,"data-testid":`conditions-nav-custom`,children:[(0,q.jsxs)(rU,{current:!0,className:`min-w-0 flex-1`,title:C,"aria-label":`Custom query: ${C}`,onClick:()=>{s(C),c()},children:[x&&(0,q.jsx)(x,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:`Custom`})]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>A(C),"aria-label":`Save shortcut`,title:`Save shortcut`,"data-testid":`conditions-nav-custom-save`,className:`grid size-8 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,q.jsx)(_,{className:`size-4`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>{y?s(y):r(e.route),c()},"aria-label":`Clear query`,title:`Clear to all entries`,"data-testid":`conditions-nav-custom-clear`,className:`grid size-8 max-lg:min-h-11 max-lg:min-w-11 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,q.jsx)(ze,{className:`size-4`,"aria-hidden":`true`})})]}):(0,q.jsxs)(rU,{onClick:()=>{y?s(y):r(e.route),c()},current:y&&g?jW(g,h):e.familyActive(n)&&vK(n).trim()===``,children:[x&&(0,q.jsx)(x,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:b})]}),v.map(t=>{let n=cW[t.icon];return(0,q.jsxs)(rU,{onClick:()=>{t.wql?s(t.wql):r(e.route),c()},current:jW(t,h),"data-testid":`nav-shortcut-${t.id}`,children:[(0,q.jsx)(n,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:t.label})]},`shortcut-${t.id}`)}),(e.extraChildren??[]).map(e=>{let t=e.action.type===`route`?e.action.to:null,i=t?p.find(e=>e.to===t):null,a=i?cW[i.icon]:null;return(0,q.jsxs)(rU,{onClick:()=>{e.action&&(AG(e.action,{navigate:(e,t)=>{r(e,{replace:t?.replace})},setQueryParam:()=>{}}),c())},current:e.isActive?.(n)??!1,"data-testid":i?`nav-shortcut-${i.id}`:e.id,children:[a?(0,q.jsx)(a,{"data-slot":`icon`}):e.icon&&(0,q.jsx)(e.icon,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:i?.label??e.label})]},e.id)})]})]}),f.length>0&&(0,q.jsxs)(tU,{className:`px-6`,"data-testid":`conditions-nav-recent`,children:[(0,q.jsx)(nU,{children:`Recent`}),f.map(e=>{let t=e.execution?.timestamp?new Date(e.execution.timestamp).toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`}):null;return(0,q.jsxs)(rU,{href:TG(e),onClick:c,"data-testid":`conditions-nav-recent-link`,children:[(0,q.jsx)(iU,{children:e.title}),t&&(0,q.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground tabular-nums shrink-0`,children:t})]},`${e.id}:${e.block?.blockId??``}`)})]})]})}}var EK=e=>YK(e.pathname,`/journal`,`/day`),DK=e=>YK(e.pathname,`/playgrounds`,`/playground`),OK={id:`journal-all-notes`,label:`All`,level:2,icon:W,action:{type:`route`,to:`/journal?q=%3Anote%7B!source%3Aplayground%7D`},isActive:e=>e.pathname===Z.journal&&new URLSearchParams(e.search).get(`q`)===`:note{!source:playground}`},kK=[{id:`notebooks-view-playgrounds`,label:`Playgrounds`,level:2,icon:En,action:{type:`route`,to:Z.playgrounds},isActive:DK},{id:`notebooks-configure-sources`,label:`Configure sources`,level:2,icon:ui,action:{type:`route`,to:Z.settingsSync},isActive:e=>YK(e.pathname,Z.settingsSync)}],AK=TK({landingLabel:`Subscribed notebooks`,icon:qe,route:Z.notebooks,profile:tH,extraChildren:kK,familyActive:e=>YK(e.pathname,`/notebooks`,`/notebook`,`/playgrounds`,`/playground`)}),jK=TK({landingLabel:`All entries`,icon:U,route:Z.journal,profile:eH,extraChildren:[OK],familyActive:EK}),MK=TK({landingLabel:`All playgrounds`,icon:En,route:Z.playgrounds,profile:lH,extraChildren:kK,familyActive:DK});function NK(e){let t=Qe();return EK(t)?(0,q.jsx)(jK,{...e}):DK(t)?(0,q.jsx)(MK,{...e}):(0,q.jsx)(AK,{...e})}var PK=`:note{!notebook:*}`;function FK(e){return e.pathname===Z.notes&&new URLSearchParams(e.search).get(`q`)?.trim()===PK}function IK(e=[]){return[{id:`pages-sub-all`,label:`All Pages`,level:2,icon:o,action:{type:`route`,to:Z.pages},isActive:e=>e.pathname===Z.pages},{id:`pages-sub-notes`,label:`Notes`,level:2,icon:sr,action:{type:`route`,to:Z.notes},isActive:e=>e.pathname===`/notes`&&!FK(e)||e.pathname.startsWith(`/note/`)&&!e.pathname.startsWith(`/notebook`)},{id:`pages-sub-orphaned-notes`,label:`Orphaned notes`,level:2,icon:Ri,action:{type:`route`,to:`${Z.notes}?q=${encodeURIComponent(PK)}`},isActive:FK},...GK(e)]}function LK(e=[]){let t=IK(e),n=t.filter(e=>e.id!==`pages-sub-all`),r=t.map(e=>e.id===`pages-sub-notes`?{...e,isActive:()=>!1}:e),i=t.filter(e=>e.id!==`pages-sub-notes`),a=TK({landingLabel:`All pages`,icon:o,route:Z.pages,profile:iH,extraChildren:n,familyActive:e=>YK(e.pathname,`/pages`,`/page`)}),s=TK({landingLabel:`All notes`,icon:sr,route:Z.notes,profile:nH,extraChildren:i,familyActive:e=>e.pathname===`/notes`&&!FK(e)||e.pathname.startsWith(`/note/`)&&!e.pathname.startsWith(`/notebook`)}),c=TK({landingLabel:`All notes`,icon:sr,route:Z.notes,profile:nH,extraChildren:r,familyActive:e=>e.pathname===`/notes`&&!FK(e)});return function(e){let t=Qe();return FK(t)?(0,q.jsx)(c,{...e}):t.pathname===`/notes`||t.pathname.startsWith(`/note/`)&&!t.pathname.startsWith(`/notebook`)?(0,q.jsx)(s,{...e}):(0,q.jsx)(a,{...e})}}var RK=`wodwiki.unpinnedGuides.v1`,zK=new rE;function BK(e){return!(zK.get(RK)??[]).includes(e)}function VK(e,t){let n=new Set(zK.get(RK)??[]);t?n.delete(e):n.add(e),zK.set(RK,Array.from(n))}function $(...e){return Kn(ra(e))}var HK=`https://www.buymeacoffee.com/sergeigolos`,UK=({className:e,...t})=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 884 1279`,fill:`currentColor`,className:e,"aria-hidden":`true`,...t,children:[(0,q.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,q.jsx)(`path`,{d:`M803.896 388.891L802.916 389.166L803.896 388.891Z`,fill:`#0D0C22`}),(0,q.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,q.jsx)(`path`,{d:`M791.113 297.529H791.244V297.447L791.113 297.529Z`,fill:`#0D0C22`}),(0,q.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,q.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,q.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,q.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,q.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,q.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,q.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,q.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,q.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,q.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`})]}),WK={"/page/guide-start":0,"/page/guide-protocols":1,"/page/guide-structure":2,"/page/guide-metrics":3,"/page/guide-clock":4,"/page/guide-wql":5,"/page/guide-dashboards":6,"/page/guide-sessions":7,"/page/guide-metrics-summaries":8};function GK(e){return e.filter(e=>!e.route.startsWith(`/notebook`)).filter(e=>e.page.frontmatter?.type===`guide`).filter(e=>BK(e.route)).sort((e,t)=>(WK[e.route]??99)-(WK[t.route]??99)).map(e=>({id:`guide-${e.route}`,label:e.page.sections[0]?.heading??`Untitled`,level:2,icon:mt,action:{type:`route`,to:e.route},isActive:t=>t.pathname===e.route,pinned:!0,onTogglePin:()=>{VK(e.route,!1)}}))}function KK(e){return[{id:`home-landing`,label:`Home`,level:2,icon:Ce,action:{type:`route`,to:Z.home},isActive:e=>e.pathname===`/`||e.pathname===``||e.pathname===Z.home},{id:`home-all-pages`,label:`All pages`,level:2,icon:o,action:{type:`route`,to:Z.pages},isActive:e=>e.pathname===Z.pages},...GK(e)]}var qK=e=>e.replace(/^\//,``).replace(/\/$/,``),JK=e=>{let t=qK(e);return t.charAt(0).toUpperCase()+t.slice(1)},YK=(e,...t)=>t.some(t=>e===t||e.startsWith(`${t}/`));function XK(e){return{id:qK(e.route),label:JK(e.route),level:1,icon:e.icon,action:{type:`route`,to:e.route},isActive:t=>e.familyActive(t),applyFooter:!0,panel:TK({landingLabel:e.landingLabel,icon:e.icon,route:e.route,profile:e.profile,extraChildren:e.extraChildren,familyActive:e.familyActive})}}function ZK(e,t=[]){let n=KK(t),r=LK(t);return[{id:`home`,label:`Home`,level:1,icon:Ce,action:{type:`route`,to:Z.home},isActive:e=>e.pathname===`/`||e.pathname===``||e.pathname===Z.home||e.pathname===Z.aiFirst||e.pathname.startsWith(`/ai-first/`),children:n},{id:qK(Z.journal),label:JK(Z.journal),level:1,icon:U,action:{type:`route`,to:Z.journal},isActive:e=>YK(e.pathname,`/journal`,`/day`),applyFooter:!0,panel:jK},{id:qK(Z.notebooks),label:JK(Z.notebooks),level:1,icon:qe,action:{type:`route`,to:Z.notebooks},isActive:e=>YK(e.pathname,`/notebooks`,`/notebook`,`/playgrounds`,`/playground`),applyFooter:!0,panel:NK},{id:qK(Z.pages),label:JK(Z.pages),level:1,icon:o,action:{type:`route`,to:Z.pages},isActive:e=>YK(e.pathname,`/pages`,`/page`,`/canvas`,`/notes`,`/note`),applyFooter:!0,panel:r},XK({landingLabel:`All Efforts`,icon:vt,route:Z.efforts,profile:aH,familyActive:e=>WH(e.pathname)}),XK({landingLabel:`All Equipment`,icon:ci,route:Z.equipment,profile:oH,familyActive:e=>GH(e.pathname)}),XK({landingLabel:`All Tags`,icon:Ee,route:Z.tags,profile:sH,familyActive:e=>YK(e.pathname,`/tags`,`/t`)}),{id:qK(Z.dashboards),label:JK(Z.dashboards),level:1,icon:Ge,action:{type:`route`,to:Z.dashboards},isActive:e=>e.pathname===Z.dashboards||e.pathname.startsWith(`/dashboard/`),panel:AU},XK({landingLabel:`All Sessions`,icon:An,route:Z.sessions,profile:cH,familyActive:e=>YK(e.pathname,`/sessions`,`/session`,`/results`)}),{id:`settings`,label:`Settings`,level:1,icon:ui,action:{type:`route`,to:Z.settingsAppearance},isActive:e=>YK(e.pathname,`/settings`,`/feeds`,`/feed`),children:[{id:`settings-profile`,label:`Profile`,level:2,icon:Zt,action:{type:`route`,to:Z.settingsProfile},isActive:e=>e.pathname===Z.settingsProfile},{id:`settings-feeds`,label:`Feeds & Sources`,level:2,icon:sr,action:{type:`route`,to:Z.feeds},isActive:e=>YK(e.pathname,`/feeds`,`/feed`)},{id:`settings-appearance`,label:`Appearance`,level:2,icon:kee,action:{type:`route`,to:Z.settingsAppearance},isActive:e=>e.pathname===Z.settings||e.pathname===Z.settingsAppearance},{id:`settings-tags`,label:`Tag Types`,level:2,icon:Ee,action:{type:`route`,to:Z.settingsTags},isActive:e=>e.pathname===Z.settingsTags},{id:`settings-sound-profiles`,label:`Sound Profiles`,level:2,icon:v,action:{type:`route`,to:Z.settingsSoundProfiles},isActive:e=>e.pathname===Z.settingsSoundProfiles},{id:`settings-sync`,label:`Sync`,level:2,icon:Cr,action:{type:`route`,to:Z.settingsSync},isActive:e=>e.pathname===Z.settingsSync},{id:`settings-storage`,label:`Storage`,level:2,icon:Kr,action:{type:`route`,to:Z.settingsStorage},isActive:e=>e.pathname===Z.settingsStorage},{id:`settings-system`,label:`System`,level:2,icon:fr,action:{type:`route`,to:Z.settingsSystem},isActive:e=>e.pathname===Z.settingsSystem}]},{id:`buy-me-a-coffee`,label:`Buy Me a Coffee`,level:1,icon:UK,action:{type:`external`,href:HK}}]}ZK(()=>{});var QK={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 $K(e){return e.proseChunks.filter(e=>e.kind===`prose`).map(e=>e.text).join(``)}function eq(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 tq(e){return e.toLowerCase().replace(/[^\w\s-]/g,``).replace(/\s+/g,`-`).replace(/^-+|-+$/g,``)}function nq(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 rq(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 iq(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 aq(e){let t=e.split(`
|
|
794
794
|
`),n=rq(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:iq(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 oq(e){let t=e.split(`
|
|
@@ -809,7 +809,7 @@ ${t??`A WOD Wiki workout feed compiled from authored Markdown notes and optional
|
|
|
809
809
|
`)}}function yq(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 bq(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=aq(r),c.push(null);else if(t===`command`)a.push(oq(r)),c.push(null);else if(t===`button`){let e=sq(r);o.push(e),c.push(e)}else t===`example`&&s.push(cq(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(...yq(e.slice(d,r.start))),u.push({kind:`button`,button:i}),d=r.end):l.has(r.type)&&(u.push(...yq(e.slice(d,r.start))),d=r.end)}return u.push(...yq(e.slice(d))),{proseChunks:u,view:i,commands:a,buttons:o,examples:s}}function xq(e,t=`/`){let{meta:n,body:r}=ac(e);if(String(n.template??``)!==`canvas`)return null;let{quests:i,body:a}=uq(r),{scroll:o,namedScrolls:s,body:c}=vq(a),{chapters:l}=pq(c),u=String(n.route??t),d=[],f=null,p=e=>{let{proseChunks:t,view:n,commands:r,buttons:i,examples:a}=bq(e.lines.join(`
|
|
810
810
|
`)),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||tq(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:$K({proseChunks:t}),proseChunks:t,view:n,commands:r,buttons:i,examples:a})},m=!1;for(let e of c.split(`
|
|
811
811
|
`)){/^`{3,}/.test(e)&&(m=!m);let t=m?null:nq(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 Sq(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 Cq(e,t){let n=Sq(t);for(let t of e)if(t.route===n)return t.page;return null}function wq(e){return[Sq(e)]}function Tq(e,t){for(let n of wq(t)){let t=Cq(e,n);if(t!==null)return t}return null}function Eq(e){let t=[];for(let[n,r]of Object.entries(e))if(n.match(/^markdown\/canvas\/(.+\.md)$/)){let e=xq(r);e&&e.route!==Z.home&&t.push({route:e.route,page:e})}return t}function Dq(e,t){return Tq(e,t)}function Oq(){let e=HP();return(0,K.useMemo)(()=>e?Eq(e):[],[e])}function kq(e){let t=Oq();return(0,K.useMemo)(()=>Dq(t,e),[t,e])}function Aq({className:e,...t}){return(0,q.jsx)(`nav`,{...t,className:ra(e,`flex flex-1 items-center gap-2 sm:gap-4 py-2.5 min-w-0`)})}var jq=(0,K.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=ra(`group relative flex min-w-0 min-h-11 min-w-11 items-center justify-center gap-3 rounded-lg p-2 text-left text-base/6 font-medium text-foreground sm:text-sm/5 sm:justify-start`,`[&>[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`,`hover:bg-muted/50 hover:[&>[data-slot=icon]]:fill-foreground`,`active:bg-muted/50 active:[&>[data-slot=icon]]:fill-foreground`,`dark:hover:bg-white/5 dark:hover:[&>[data-slot=icon]]:fill-foreground`,`dark:active:bg-white/5 dark:active:[&>[data-slot=icon]]:fill-foreground`),o=r,s=r;return(0,q.jsxs)(`span`,{className:ra(t,`relative`),children:[e&&(0,q.jsx)(_e.span,{layoutId:`current-indicator`,className:`absolute inset-x-2 -bottom-2.5 h-0.5 rounded-full bg-foreground`}),typeof r.href==`string`?(0,q.jsx)(JH,{...o,className:a,"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n}):(0,q.jsx)(`button`,{type:`button`,...s,className:ra(`cursor-default`,a),"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:n})]})});function Mq({size:e=32,className:t,...n}){let r=!n[`aria-label`]&&!n[`aria-labelledby`];return(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,width:e,height:e,"aria-hidden":r?!0:void 0,role:r?void 0:`img`,className:t,...n,children:[(0,q.jsx)(`rect`,{x:`0`,y:`0`,width:`32`,height:`32`,rx:`8`,fill:`#49698d`}),(0,q.jsx)(`rect`,{x:`0.5`,y:`0.5`,width:`31`,height:`31`,rx:`7.5`,fill:`none`,stroke:`#fcfbf8`,strokeOpacity:`0.16`,strokeWidth:`1`}),(0,q.jsxs)(`g`,{transform:`translate(3.2 3.2) scale(0.8)`,children:[(0,q.jsx)(`path`,{d:`M10.5 6.5H7a1.5 1.5 0 0 0-1.5 1.5v16A1.5 1.5 0 0 0 7 25.5h3.5`,fill:`none`,stroke:`#fcfbf8`,strokeWidth:`2.75`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,q.jsx)(`path`,{d:`M21.5 6.5H25a1.5 1.5 0 0 1 1.5 1.5v16a1.5 1.5 0 0 1-1.5 1.5h-3.5`,fill:`none`,stroke:`#fcfbf8`,strokeWidth:`2.75`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,q.jsx)(`path`,{d:`M12.5 10.6a1.1 1.1 0 0 1 1.66-.95l7.9 4.86a1.15 1.15 0 0 1 0 1.98l-7.9 4.86a1.1 1.1 0 0 1-1.66-.95V10.6Z`,fill:`#d6e4f0`})]})]})}var Nq=class{async getAllEfforts(){let e=SP();return e.isInitialized()||await vP(e),[...e.list()]}},Pq=vS(YP,{coalesce:!0,effortStore:new Nq});Pq.eventStore,Pq.noteStore,Pq.blockStore;var Fq=new wy,Iq={events:[],notes:[]},Lq={events:[],notes:[]};Fq.set(`@session`,Iq),Fq.set(`@today`,Lq);function Rq(){let{runtime:e,activeNoteId:t}=Bz.getState(),n=e?.getOutputStatements()??[];if(Iq.notes=[],n.length===0)return Iq.events=[],Iq;let r=t??``;return Iq.events=jy(n.map(Fh),{noteId:r,resultId:`live:${r||`session`}`,origin:`playground`}),Iq}function zq(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 ny(e.date??e.createdAt,r)}async function Bq(e,t){let n=ny(e.instant,e.timeZone),r=cy(n,e.timeZone),i=cy(ry(n,1),e.timeZone),[a,o,s,c,l]=await Promise.all([X.getEventsByTimeRange(r,i),X.getAllNotes(),X.getAllPageNotes(),X.getAllPages(),YP.readonly(`schedule_items`).getAllFromIndex(`by-date`,n).catch(()=>[])]),u=a.filter(e=>e.timestamp>=r&&e.timestamp<i),d=new Map(c.map(e=>[e.id,e])),f=new Set(l.map(e=>e.noteId)),p=new Map;for(let e of s){let t=p.get(e.noteId);t?t.push(e):p.set(e.noteId,[e])}let m=[];for(let t of o)(f.has(t.id)||zq(t,p.get(t.id)??[],d,e.timeZone)===n)&&m.push(t);t===Uq&&(Lq.events=u,Lq.notes=m,Rq())}var Vq=null,Hq=null,Uq=0,Wq=!1,Gq=new Set;function Kq(){for(let e of Gq)e()}function qq(e,t){Hq=t;let n=++Uq;return Vq=Bq(e,n),Vq.then(()=>{n===Uq&&Jq()},()=>{n===Uq&&Jq()}),Vq}function Jq(){Wq=!0,Kq()}function Yq(){let e=$v(),t=ny(e.instant,e.timeZone);return!Vq||Hq!==t?qq(e,t):Vq}function Xq(){Wq=!1;let e=$v();return qq(e,ny(e.instant,e.timeZone))}function Zq(){return Wq}function Qq(e){return Gq.add(e),()=>{Gq.delete(e)}}async function $q(){await Promise.all([uR(),ER()])}function eJ(e){if(typeof e==`string`)return/@(?:today|session)\b/i.test(e);if(`source`in e&&e.source?.kind===`dataset`){let t=e.source.name.toLowerCase();return t===`@today`||t===`@session`}return`raw`in e&&typeof e.raw==`string`&&/@(?:today|session)\b/i.test(e.raw)}var tJ=class extends Sb{async runQuery(e,t){return eJ(e)?await Promise.all([$q(),Yq()]):await $q(),super.runQuery(e,t)}async runPipeline(e,t){return eJ(e)?await Promise.all([$q(),Yq()]):await $q(),super.runPipeline(e,t)}async runFind(e,t){return eJ(e)?await Promise.all([$q(),Yq()]):await $q(),super.runFind(e,t)}async runRows(e,t){return eJ(e)?await Promise.all([$q(),Yq()]):await $q(),super.runRows(e,t)}async run(e,t){return eJ(e)?await Promise.all([$q(),Yq()]):await $q(),super.run(e,t)}},nJ=null,rJ=0;async function iJ(e){let t=++rJ,n=await yoe(YP,e);return t===rJ&&(nJ=n),n}function aJ(){rJ+=1,nJ=null}function oJ(){return new tJ(vS(YP,{coalesce:!0,effortStore:new Nq,feedCatalogStore:BL,datasetStore:{getDataset:e=>e===`@session`?Rq()??nJ?.get(`@session`):nJ?.get(e)??Fq.getDataset(e)},isNotebookSubscribed:(e,t)=>HI(e,t)}))}var sJ=oJ(),cJ=3,lJ=120,uJ=/^(`{3,})(time|wod|whiteboard|log)(?::([\w-]+))?\s*$/i;function dJ(e){if(!e)return[];let t=[],n=e.length,r=0;for(;r<n&&t.length<cJ;){let i=e.indexOf(`
|
|
812
|
-
`,r),a=i===-1?n:i,o=e.slice(r,a).trim();if(o&&t.push(o.length>lJ?`${o.slice(0,119)}…`:o),i===-1)break;r=i+1}return t}function fJ(e,t){if(e.length<t)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)!==96)return!1;return!0}function pJ(e){let{rawContent:t,blocks:n,sourceRevision:r}=e;if(typeof t!=`string`||!n||typeof n!=`object`||Array.isArray(n)||!Number.isSafeInteger(r)||r<1)return;let i;for(let[e,a]of Object.entries(n)){if(!a||!e||a.id!==e||!Number.isSafeInteger(a.version)||a.version<1||a.sourceRevision!==r||!Number.isSafeInteger(a.from)||!Number.isSafeInteger(a.to)||a.from<0||a.to<a.from||a.to>t.length)return;a.kind===`wod`&&(!i||a.from<i.from)&&(i=a)}if(!i)return;if(i.from>0){let e=t.charCodeAt(i.from-1);if(e!==10&&e!==13)return}let a=t.slice(i.from,i.to),o=-1,s=-1;for(let e=0;e<a.length;e++){let t=a.charCodeAt(e);if(t===13){o=e,s=a.charCodeAt(e+1)===10?e+2:e+1;break}if(t===10){o=e,s=e+1;break}}if(o===-1||s>a.length)return;let c=uJ.exec(a.slice(0,o).trim());if(!c)return;let l=c[1].length,u=c[2].toLowerCase()===`log`?`log`:`time`,d=c[3];if(i.dialect!==void 0&&i.dialect!==u||i.sport!==void 0&&i.sport!==d)return;let f=-1;for(let e=a.length-1;e>=s-1;e--){let t=a.charCodeAt(e);if(t===10||t===13){f=e;break}}if(f===-1)return;let p=f+1;if(!fJ(a.slice(p).trim(),l))return;let m=s;for(;m<p;){let e=m;for(;e<p;){let t=a.charCodeAt(e);if(t===10||t===13)break;e++}if(fJ(a.slice(m,e).trim(),l))return;m=a.charCodeAt(e)===13&&a.charCodeAt(e+1)===10?e+2:e+1}let h=a.slice(s,p),g=os(h);return{blockId:i.id,blockVersion:i.version,blockContentId:g,content:h}}function mJ(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,sourceNotebook:`results`,sourceNote:i??r??`${t}:${n}`,title:a?sG(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function hJ(e){let t=e.parsed.family===`aggregate`?e.parsed.metric:`metric`;return e.series.map(e=>{let n=e.points.map(t=>`${t.value}${e.unit?` ${e.unit}`:``}`).join(` • `);return{id:`aggregate:${t}:${e.key}`,kind:`result`,sourceNotebook:`results`,sourceNote:e.label,title:`${t}: ${n}`,subtitle:e.label,date:null}})}function gJ(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function _J(e){return typeof e==`object`&&!!e&&`runFind`in e}var vJ=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){_J(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver),this.noteTitleResolver||=async e=>{try{let t=await X.getNote(e);return t?MT(t.title)||NT(t.rawContent??``):void 0}catch{return}}}get service(){return this.customService??sJ}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,n,r){if(t&&r)for(let t of e){let e=r[t.id];e&&e.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.map(e=>e.label)),t.typedTags=e.map(e=>({label:e.label,type:e.type})))}let i=new Set;for(let r of e)if(!(r.kind===`feed`||r.kind===`notebook`||r.isRemotePreview)){if(n&&Object.prototype.hasOwnProperty.call(n,r.id)){let e=n[r.id];r.placements=e;let t=us(e);r.pageId??=t.pageId,t.pageSlug&&(r.pageSlug=t.pageSlug);continue}(r.kind===`note`||r.sourceNotebook===`journal`)&&i.add(r.id),t&&(!r.title||!r.tags||r.tags.length===0)&&i.add(r.id)}if(i.size===0)return;let a=await X.getDetailBatches([...i]);for(let t of e){if(t.kind===`feed`||t.kind===`notebook`||t.isRemotePreview||!i.has(t.id))continue;let e=a.get(t.id);if(!e)continue;let n=ls(e.links??[],e.pages??[]);t.placements=n;let r=us(n);t.pageId??=r.pageId,r.pageSlug&&(t.pageSlug=r.pageSlug)}if(t)for(let t of e){let e=a.get(t.id);!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,n){let r=typeof e==`string`?Xg(e):e;if(!r||r.error)return[];if(Fg(r)){if(r.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(r):await this.service.runFind(r),n=new Map(e.notes.map(e=>[e.id,e])),i=(e.efforts??[]).map(e=>e.ownerNoteId&&n.has(e.ownerNoteId)?eG(n.get(e.ownerNoteId)):uG(e));return gJ(t,e.stages,i),i}if(r.target===`block`){let e=await this.service.runFind(r),n=e.blocks.map(oG);return await this.hydrateEntries(n,!0),gJ(t,e.stages,n),n}if(r.target===`session`){let e=await this.service.runFind(r);t?.(e.stages);let n;if(this.noteTitleResolver&&e.runs){n=new Map;for(let t of e.runs)if(!n.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&n.set(t.noteId,e)}}let i=xG(e,{noteTitles:n});return gJ(t,e.stages,i),i}if(r.target===`segment`||r.target===`event`){let e=r.target,n=await this.service.runFind(r),i=(n.table?.rows??[]).map((t,n)=>mJ(t,e,n));return gJ(t,n.stages,i),i}let e=await this.service.runFind(r,n?.notebookPlane?{notebookPlane:n.notebookPlane}:void 0),i=e.notes.map(eG);if(this.noteTagsResolver?(await this.hydrateEntries(i,!1,e.placements,e.typedTags),await Promise.all(i.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(i,!0,e.placements,e.typedTags),gJ(t,e.stages,i),this.noteBlockInfo)for(let t=0;t<i.length;t++){let n=i[t],r=e.notes[t];n.excerpt=dJ(r.rawContent);let a=pJ(r);a&&(n.wodBlock=a,n.blockContentId=a.blockContentId)}return i}if(r.family===`aggregate`){if(!this.service.runQuery)return[];let e=await this.service.runQuery(r.raw),n=hJ(e);return t?.({selected:e.stages?.selected??n.length,matched:n.length}),n}return[]}};async function yJ(e,t=vJ,n){return t.query(e,n)}function bJ(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function xJ(e){try{let t=(await yJ(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 SJ(e){let t=bJ(e),n=(0,K.useRef)(e);n.current=e;let[r,i]=(0,K.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,K.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`?xJ(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),!e||!e.some(e=>e.kind===`wql`)?e??[]:r}function CJ(){let[e]=V(`h`,{shallow:!0}),[t]=V(`s`,{shallow:!0}),{navState:n}=NV(),r=n.activeL3Id??``;return e||t||r||``}function wJ({entry:e,active:t,onActivate:n,onRunAction:r,onFilter:i}){let a=e.onRun,o=e.filterTo,s=e.filterLabel??`Filter notes by ${e.label}`,c=e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,l=(0,q.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:$(`flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-1.5 max-lg:min-h-11 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,!a&&!o&&`w-full`,e.muted?`text-xs`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[e.icon&&(0,q.jsx)(e.icon,{"aria-hidden":`true`,className:`size-4 shrink-0`}),e.timestamp&&(0,q.jsx)(`span`,{className:`shrink-0 font-mono text-xs tabular-nums text-muted-foreground`,children:e.timestamp}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,q.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-xs uppercase tracking-wide text-muted-foreground`,children:e.badge})]});return!a&&!o?l:(0,q.jsxs)(`div`,{className:`group flex w-full items-center gap-0.5`,children:[l,o&&(0,q.jsx)(`button`,{type:`button`,"aria-label":s,title:s,"data-testid":`menu-filter-${e.id}`,onClick:()=>i(o),className:`flex size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 items-center justify-center rounded-md text-foreground/75 transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,children:(0,q.jsx)(p,{"aria-hidden":`true`,className:`size-3.5`})}),a&&(0,q.jsx)(`button`,{type:`button`,"aria-label":c,title:c,onClick:()=>r(e),className:`flex size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 items-center justify-center rounded text-primary opacity-70 lg:opacity-0 transition-all group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 hover:bg-primary/10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,children:e.runIcon===`link`?(0,q.jsx)(Vn,{"aria-hidden":`true`,className:`size-3.5`}):e.runIcon===`stop`?(0,q.jsx)(ue,{"aria-hidden":`true`,className:`size-3.5`}):e.runIcon===`edit`?(0,q.jsx)(ke,{"aria-hidden":`true`,className:`size-3.5`}):(0,q.jsx)(re,{"aria-hidden":`true`,className:`size-3.5`})})]})}function TJ({entries:e,activeId:t,onSection:n,onSelect:r}){let i=dt(),{scrollToSection:a}=NV(),o=ZH(),s=e=>{if(o(),n)return n(e);if(e.onSelect)return e.onSelect();if(r)return r(e);if(e.onRun)return e.onRun();if(e.to)return i(e.to);if(e.sectionId)return a(e.sectionId)},c=e=>{o(),e.onRun?.()},l=e=>{o(),i(e)};return(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,q.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,q.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,q.jsx)(TJ,{entries:e.entries,activeId:t,onSection:n,onSelect:r})]},e.id):e.kind===`wql`?null:e.kind===`widget`?(0,q.jsx)(`div`,{className:`px-1 py-1`,children:e.render()},e.id):(0,q.jsx)(wJ,{entry:e,active:t!=null&&e.sectionId===t,onActivate:s,onRunAction:c,onFilter:l},e.id))})}function EJ(){let e=dt(),{scrollToSection:t}=NV();return{navigate:(t,n)=>{e(t,{replace:n?.replace})},setQueryParam:(e,t)=>{},scrollToSection:t}}function DJ(){let e=EJ(),t=ZH();return n=>{t(),AG(n.action,e)}}function OJ(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 kJ({items:e}){let{navState:t}=NV(),n=Qe(),r=DJ();return(0,q.jsx)(tU,{children:e.map(e=>{let i=OJ(e,t,n);return e.children&&e.children.length>0?(0,q.jsx)(FG,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>OJ(e,t,n)),collapsible:e.id!==`syntax-group`,buttonClassName:`text-xs font-bold tracking-[0.14em] text-muted-foreground`,children:e.children.map(e=>{let i=OJ(e,t,n);return(0,q.jsxs)(rU,{onClick:()=>r(e),current:i,children:[e.icon&&(0,q.jsx)(e.icon,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:e.label})]},e.id)})},e.id):(0,q.jsxs)(`div`,{className:`group relative flex items-center`,children:[(0,q.jsxs)(rU,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:$(`flex-1`,e.disabled&&`opacity-60`),children:[e.icon&&(0,q.jsx)(e.icon,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:e.disabled?`+`:e.label})]}),e.onTogglePin&&(0,q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),e.onTogglePin?.()},title:e.pinned?`Unpin from sidebar`:`Pin to sidebar`,"aria-label":e.pinned?`Unpin ${e.label}`:`Pin ${e.label}`,className:`opacity-0 group-hover:opacity-100 focus-visible:opacity-100 p-1 max-lg:min-h-11 max-lg:min-w-11 flex items-center justify-center text-muted-foreground hover:text-foreground transition-opacity`,children:(0,q.jsx)(iee,{className:`size-3.5`})})]},e.id)})})}function AJ({navSpec:e}){let{tree:t,navState:n,dispatch:r}=NV(),i=SJ(e),a=(t??[]).find(e=>e?.id===n.activeL1Id)??null;return(0,q.jsxs)(QH,{"aria-label":a?`${a.label} places`:`Workspace`,children:[(0,q.jsx)($H,{children:(0,q.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:a?.label??`Wod Wiki`})}),(0,q.jsxs)(eU,{children:[(()=>{if(!a)return null;if(a.panel){let e=a.panel;return(0,q.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,q.jsx)(e,{item:a,navState:n,dispatch:r})})}return a.children&&a.children.length>0?(0,q.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,q.jsx)(kJ,{items:a.children})}):null})(),i.length>0&&(0,q.jsx)(`div`,{className:`pt-1`,children:(0,q.jsx)(TJ,{entries:i})})]})]})}var jJ=`0.63.2266`,MJ={version:jJ,gitSha:`9fdbf971bf74`,builtAt:`2026-11-24T03:15:59.446Z`},NJ=`https://github.com/bitcobblers/wod-wiki/releases`;function PJ(e){return/-pr\.\d+$/.test(e)?NJ:`${NJ}/tag/v${e}`}function FJ({onSearch:e,onCreate:t,variant:n=`rail`}){let{tree:r,navState:i,dispatch:a}=NV(),o=dt(),s=Qe(),c=ZH(),l={navigate:(e,t)=>{o(e,{replace:t?.replace})},setQueryParam:()=>{},scrollToSection:()=>{}},u=n===`mobile-list`,d=(r??[]).find(e=>e?.id===`home`),f=d?OJ(d,i,s):s.pathname===`/`||s.pathname===``,p=(r??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`home`&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),m=s.pathname.startsWith(`/settings/profile`),h=s.pathname.startsWith(`/settings`),g=`pointer-events-none absolute left-full top-1/2 -translate-y-1/2 z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,_=e=>$(`flex w-full min-h-11 items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[13px] transition-colors`,e?`bg-primary/10 font-semibold text-primary`:`font-medium text-muted-foreground hover:bg-muted/60 hover:text-foreground`);return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a({type:`SET_ACTIVE_L1`,id:`home`}),o(`/`)},title:`Wod Wiki home`,"aria-label":`Wod Wiki home`,"aria-current":f?`page`:void 0,"data-testid":Q.NAV_L1_HOME,className:u?$(_(f),`mb-1.5 shrink-0`):$(`group relative mb-3 grid size-9 shrink-0 place-items-center rounded-lg transition-colors`,f?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&f&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(Mq,{size:u?24:32,className:$(`shrink-0 shadow-sm shadow-black/15`,u?`size-6 rounded-[6px]`:`size-8 rounded-[8px]`)}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Home`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Wod Wiki home`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Wod Wiki home`})]})]}),(0,q.jsx)(`nav`,{"aria-label":`Primary`,className:u?`flex w-full flex-col gap-0.5`:`flex w-full flex-col items-center gap-1.5`,children:p.map(e=>{let t=e.icon,n=OJ(e,i,s);return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{let t=!!(e.panel||e.children&&e.children.length>0);(!u||!t||n)&&c(),a({type:`SET_ACTIVE_L1`,id:e.id}),AG(e.action,l)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,"data-testid":`nav-l1-${e.id}`,className:u?_(n):$(`group 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:[!u&&n&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(t,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:e.label}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:e.label})]})]},e.id)})}),(0,q.jsx)(`div`,{className:`flex-1 min-h-2`}),(0,q.jsxs)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,"data-testid":Q.NAV_L1_SEARCH,className:u?_(!1):`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,q.jsx)(hi,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Search`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Search`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Search (⌘/)`})]})]}),(0,q.jsxs)(`a`,{href:HK,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:u?_(!1):`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,q.jsx)(UK,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Buy Me a Coffee`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Buy Me a Coffee`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Buy Me a Coffee`})]})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),o(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":m?`page`:void 0,"data-testid":`nav-profile`,className:u?$(_(m),`mt-0.5`):$(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,m?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&m&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(Zt,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Profile`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Profile`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Profile`})]})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),o(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":h?`page`:void 0,"data-testid":`nav-settings`,className:u?$(_(h),`mt-0.5`):$(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,h?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&h&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(ui,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Settings`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Settings`}),(0,q.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 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`Settings (v`,jJ,`)`]})]})]})]})}function IJ({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,q.jsx)(`nav`,{className:$(`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,q.jsx)(`button`,{onClick:()=>AG(e.action,r),className:$(`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 LJ=class e{now;name=`tick`;timestamp;data;static _counter=0;constructor(t,n=of){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this.data=t}},RJ=20,zJ=e=>{let[t,n]=(0,K.useState)(`idle`),[r,i]=(0,K.useState)(0),[a,o]=(0,K.useState)(0),[s,c]=(0,K.useState)(null),l=(0,K.useRef)(null),u=(0,K.useRef)(`idle`),d=(0,K.useRef)(0),f=(0,K.useRef)(null),p=(0,K.useRef)(!1),m=(0,K.useCallback)(()=>e?.nowProvider?.nowMs()??of.nowMs(),[e]),h=(0,K.useCallback)(()=>e?.nowProvider?.now()??of.now(),[e]),g=(0,K.useCallback)(()=>u.current===`running`&&f.current!==null?d.current+Math.max(0,m()-f.current):d.current,[m]),_=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null);let e=g();d.current=e,f.current=null,u.current=`idle`,i(e),n(`idle`)},[g]),v=(0,K.useCallback)(()=>{if(e)try{let t=new LJ(void 0,e.nowProvider);e.handle(t),o(e=>e+1)}catch{_(),u.current=`error`,n(`error`)}},[e,_]);(0,K.useEffect)(()=>{if(e)return e.subscribeToStack(e=>{if(e.blocks.length===0&&u.current!==`completed`){l.current&&=(clearInterval(l.current),null);let e=g();d.current=e,f.current=null,u.current=`completed`,i(e),n(`completed`)}})},[e,g]),(0,K.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]);let y=(0,K.useCallback)(()=>{if(!e){console.warn(`useRuntimeExecution: Cannot start execution without a runtime`);return}if(u.current===`running`){console.warn(`useRuntimeExecution: Runtime is already running`);return}u.current===`paused`&&e.handle({name:`timer:resume`,timestamp:h(),data:{}});let t=m();f.current=t,p.current||(p.current=!0,c(t)),u.current=`running`,n(`running`),l.current=setInterval(v,RJ)},[e,h,m,v]),b=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null);let t=g();d.current=t,f.current=null,i(t),e&&e.handle({name:`timer:pause`,timestamp:h(),data:{}}),u.current=`paused`,n(`paused`)},[e,g,h]),x=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),d.current=0,f.current=null,p.current=!1,u.current=`idle`,i(0),o(0),n(`idle`),c(null)},[]),S=(0,K.useCallback)(()=>{!e||u.current===`running`||(u.current=`paused`,n(`paused`),v())},[e,v]);return(0,K.useEffect)(()=>{if(t!==`running`)return;let e=setInterval(()=>{i(g())},100);return()=>clearInterval(e)},[t,g]),(0,K.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]),(0,K.useEffect)(()=>{x()},[e,x]),(0,K.useMemo)(()=>({status:t,elapsedTime:r,getElapsedTime:g,stepCount:a,startTime:s,start:y,pause:b,stop:_,reset:x,step:S}),[t,r,g,a,s,y,b,_,x,S])};function BJ(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,K.useState)(r);return(0,K.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 VJ(e){return BJ(e,`round`)}function HJ(e){return BJ(e,`display`)}function UJ(e){let t=VJ(e),n=HJ(e);return(0,K.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 WJ=(0,K.createContext)(void 0),GJ=({runtime:e,children:t})=>(0,q.jsx)(WJ.Provider,{value:e,children:t});function KJ(){let e=(0,K.useContext)(WJ);if(!e)throw Error(`useScriptRuntime must be used within ScriptRuntimeProvider`);return e}function qJ(){return(0,K.useContext)(WJ)??null}function JJ(e){let t=KJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(()=>n?.getOutputStatements?.()??[]);return(0,K.useEffect)(()=>{if(!n){i([]);return}return i(n.getOutputStatements()),n.subscribeToOutput?.(()=>{i(n.getOutputStatements())})},[n]),(0,K.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 YJ(){let e=KJ(),[t,n]=(0,K.useState)({type:`initial`,blocks:e.stack.blocks,depth:e.stack.count,clockTime:e.clock.currentDate});return(0,K.useEffect)(()=>e.subscribeToStack(e=>{n(e)}),[e]),t}function XJ(){return YJ().blocks}function ZJ(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.useMemo)(()=>{for(let t of e){let e=t.getMemoryByTag(`metric:next`);if(e.length===0)continue;let n=Qo.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 QJ(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.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 $J(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.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 eY(e){let t=KJ(),n=(0,K.useMemo)(()=>t.stack.blocks.find(t=>t.key.toString()===e),[t,e]),[r,i]=(0,K.useState)(()=>n?.getMemoryByTag(`time`)[0]?.metrics[0]?.value);(0,K.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,K.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,K.useMemo)(()=>r?.spans??[],[r]),o=a.length>0&&a[a.length-1].ended===void 0,[s,c]=(0,K.useState)(Of()),l=(0,K.useMemo)(()=>a.length===0?0:oh(a,s),[a,s]);return(0,K.useEffect)(()=>{if(!o)return;let e,t=()=>{c(Of()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[o]),{elapsed:l,isRunning:o,timeSpans:a}}function tY(e={}){let t=qJ(),n=e.runtime===void 0?t:e.runtime,r=e.active??!0,[i,a]=(0,K.useState)({revision:0,skipFlash:!1,skipFlashKey:0});(0,K.useEffect)(()=>{if(!(!n||!r))return fh(n,({skipFlash:e,skipFlashKey:t})=>{a(n=>({revision:n.revision+1,skipFlash:e,skipFlashKey:t}))})},[n,r]);let[o,s]=(0,K.useState)(()=>Of()),c=(0,K.useMemo)(()=>(i.revision,gh(n,{nowMs:o,executionStatus:e.executionStatus,canNextOverride:e.canNextOverride,skipFlash:i.skipFlash,skipFlashKey:i.skipFlashKey})),[n,i.revision,i.skipFlash,i.skipFlashKey,o,e.executionStatus,e.canNextOverride]);return(0,K.useEffect)(()=>{if(!r||!c.isRunning||c.isPaused||typeof requestAnimationFrame!=`function`)return;let e=0,t=!0,n=()=>{t&&(s(Of()),e=requestAnimationFrame(n))};return e=requestAnimationFrame(n),()=>{t=!1,cancelAnimationFrame(e)}},[r,c.isRunning,c.isPaused]),c}function nY(e){let t=qJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(0);return(0,K.useEffect)(()=>{if(!n){i(0);return}return n.subscribeToOutput?.(()=>{i(e=>e+1)})},[n]),(0,K.useMemo)(()=>Ch(n),[n,r])}function rY(e){let t=qJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(0);return(0,K.useEffect)(()=>{if(!n)return;let e=n.subscribeToStack(()=>i(e=>e+1)),t=n.subscribeToOutput?.(()=>i(e=>e+1));return()=>{e(),t?.()}},[n]),(0,K.useMemo)(()=>Eh(n),[n,r])}var iY=(0,K.createContext)(void 0),aY=(0,K.createContext)(null),oY=({factory:e,children:t})=>{let[n,r]=(0,K.useState)(null),[i,a]=(0,K.useState)(null),[o,s]=(0,K.useState)(!1),[c,l]=(0,K.useState)(null),u=(0,K.useRef)(e);u.current=e;let d=(0,K.useRef)(null),f=(0,K.useRef)(null),p=(0,K.useRef)(!1),m=(0,K.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),Bz.getState().setSubscriptionManager(null),Bz.getState().setRuntime(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,K.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 ah(i);e.add(new ih({id:`local`})),f.current=e,a(e),Bz.getState().setRuntime(i),Bz.getState().setSubscriptionManager(e)}else f.current=null,a(null),Bz.getState().setRuntime(null),Bz.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,K.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,q.jsx)(iY.Provider,{value:g,children:(0,q.jsx)(aY.Provider,{value:i,children:t})})};function sY({factory:e,children:t}){return(0,q.jsx)(oY,{factory:e,children:t})}var cY=`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`,lY=`flex flex-col flex-1 min-w-0 min-h-screen lg:rounded-[2.5rem]`,uY=1023;function dY(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function fY(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);if(r===null)return null;let i=t[r],{meta:a,body:o}=ac(i),s=new Set([`search`,`template`,`route`,`type`,`title`,`description`,`subtitle`,`section`,`order`]);return Object.keys(a).some(e=>!s.has(e.trim().toLowerCase()))?i:o};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i;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(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function pY(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function mY(e){let t=new Map,n=null;for(let r of e)pY(r)&&(n=r),t.set(r.id,n);return t}function hY(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${uY}px)`).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${uY}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function gY(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})}function _Y({onOpen:e}){let t=ZH();return(0,q.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{t(),e()},"data-testid":`query-settings-trigger`,className:`w-full max-lg:min-h-11 justify-start gap-2 rounded-lg text-xs`,children:[(0,q.jsx)(Vi,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate`,children:`Query settings`})]})}var vY=[4,8,16],yY=`sum:totalVolume{}`;function bY(e){let t=Number.parseInt(e??``,10);return vY.includes(t)?t:16}function xY(e={}){let{defaultQuery:t=yY,runOnLanding:n=!1}=e,[r,i]=be(),a=r.get(`q`)??``,o=bY(r.get(`weeks`)),s=a?!!Xg(a).error:!1,[c,l]=(0,K.useState)(()=>a||t),[u,d]=(0,K.useState)(()=>s?a:null),[f,p]=(0,K.useState)(()=>a&&!s?a:n?t:``),m=(0,K.useRef)(c);m.current=c;let h=(0,K.useRef)(f);h.current=f;let g=(0,K.useRef)(r);g.current=r;let _=(0,K.useRef)(!0),v=(0,K.useRef)(a);v.current=a;let y=(0,K.useRef)(a);(0,K.useEffect)(()=>{if(a===y.current||(y.current=a,m.current===a))return;_.current=!0;let e=a?!!Xg(a).error:!1;l(a||t),e?(d(a),p(e=>e||(n?t:``))):(d(null),p(a||(n?t:``)))},[a,t,n]);let b=(0,K.useRef)(t);return(0,K.useEffect)(()=>{t!==b.current&&(b.current=t,!a&&(d(null),l(t),p(n?t:``)))},[t,a,n]),{draft:c,setDraft:(0,K.useCallback)(e=>{if(e!==m.current){if(e.trim().length>0&&!Xg(e).error){d(null);let t=new URLSearchParams(g.current);t.set(`q`,e),i(t,{replace:!_.current}),_.current=!1}l(e)}},[i]),submitted:f,invalidUrlQuery:u,revertDraft:(0,K.useCallback)(()=>{let e=h.current||t;d(null),l(e);let n=new URLSearchParams(g.current);h.current?n.set(`q`,h.current):n.delete(`q`),i(n,{replace:!0}),_.current=!0},[t,i]),submit:(0,K.useCallback)(e=>{let t=e??m.current;if(t.trim().length===0||Xg(t).error)return;if(d(null),_.current&&v.current===t){p(t);return}let n=new URLSearchParams(g.current);n.set(`q`,t),i(n,{replace:!0}),_.current=!0,p(t)},[i]),weeks:o,setWeeks:(0,K.useCallback)(e=>{let t=new URLSearchParams(g.current);t.set(`weeks`,String(e)),i(t,{replace:!0})},[i])}}var SY=4;function CY(e){return!e||e.length===0?!1:e.some(e=>e.kind===`wql`||e.kind!==`section`||CY(e.entries))}function wY(e,t){let n=PV();return!!(CY(e)||n?.l3Items&&n.l3Items.length>0||CY(n?.l3Connections)||n?.l3Actions&&n.l3Actions.length>0||n?.analyticsControls||t)}function TY({controls:e}){let{unit:t,setUnit:n}=fk(),r=e.showRange!==!1,i=e.showUnits!==!1,a=e.weeks!==void 0&&e.onWeeksChange!==void 0;return(0,q.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":Q.L3_ANALYTICS_CONTROLS,children:[e.onOpenQuerySettings&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`This page`}),(0,q.jsx)(_Y,{onOpen:e.onOpenQuerySettings})]}),r&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date range`}),a?(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":Q.L3_RANGE_OPTIONS,children:vY.map(t=>{let n=e.weeks===t;return(0,q.jsxs)(`button`,{type:`button`,"aria-pressed":n,onClick:()=>e.onWeeksChange?.(t),"data-testid":`l3-range-${t}w`,className:$(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 max-lg:min-h-11 text-xs transition-colors`,n?`bg-primary/10 font-semibold text-primary`:`text-foreground/85 hover:bg-muted/60 hover:text-foreground`),children:[(0,q.jsx)(`span`,{className:`w-3.5 text-primary`,children:n?(0,q.jsx)(zr,{className:`size-3.5`,"aria-hidden":`true`}):null}),(0,q.jsxs)(`span`,{children:[`Past `,t,` weeks`]})]},t)})}):(0,q.jsx)(rk,{})]}),i&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:[`Units`,e.unitForced?` — pinned by query`:``]}),(0,q.jsx)(`div`,{className:`grid grid-cols-2 gap-1`,"data-testid":Q.L3_UNIT_OPTIONS,children:[`kg`,`lb`].map(r=>{let i=t===r;return(0,q.jsx)(`button`,{type:`button`,disabled:!!e.unitForced,"aria-pressed":i,onClick:()=>n(r),"data-testid":`l3-unit-${r}`,className:$(`flex min-h-8 max-lg:min-h-11 items-center justify-center rounded-md border px-2 py-1 text-xs font-medium transition-colors`,e.unitForced?`border-transparent text-muted-foreground/75 opacity-70 cursor-not-allowed`:i?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`),children:r},r)})})]})]})}function EY({action:e,variant:t=`default`}){let n=ZH(),r=e.icon;return(0,q.jsxs)(`button`,{type:`button`,disabled:e.disabled,"data-testid":e.testId,onClick:()=>{e.disabled||(n(),e.onRun())},className:$(`flex w-full items-center gap-2 rounded-lg transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`,t===`primary`&&`justify-center bg-primary px-3 py-2 min-h-9 max-lg:min-h-11 text-sm font-semibold text-primary-foreground shadow-sm hover:bg-primary/90`,t==="default"&&`px-2 py-1.5 max-lg:min-h-11 text-left text-[13px] text-foreground/85 hover:bg-muted/60 hover:text-foreground`,t===`danger`&&`px-2 py-1.5 max-lg:min-h-11 text-left text-[13px] font-medium text-destructive hover:bg-destructive/10 hover:text-destructive`,e.disabled&&(t===`primary`?`cursor-not-allowed opacity-50`:t===`danger`?`cursor-not-allowed text-destructive/50 hover:bg-transparent`:`cursor-not-allowed text-muted-foreground/60 hover:bg-transparent`)),children:[r&&(0,q.jsx)(r,{"aria-hidden":`true`,className:`size-4 shrink-0`}),(0,q.jsx)(`span`,{className:$(`min-w-0 truncate`,t!==`primary`&&`flex-1`),title:e.label,children:e.label})]})}function DY({bucket:e}){let t=e.items.length+ +!!e.extraNode;return(0,q.jsxs)(`details`,{"data-testid":e.testId,className:`group rounded-lg border border-border/40 bg-muted/20`,children:[(0,q.jsxs)(`summary`,{className:`flex min-h-9 max-lg:min-h-11 cursor-pointer list-none items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-semibold text-foreground/85 select-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden`,children:[(0,q.jsx)(ee,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 group-open:rotate-90`}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}),(0,q.jsx)(`span`,{className:`shrink-0 text-xs font-medium tabular-nums text-muted-foreground`,children:t})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-0.5 px-1 pb-1.5 pt-0.5`,children:[e.items.map(e=>(0,q.jsx)(EY,{action:e},e.id)),e.extraNode&&(0,q.jsx)(`div`,{className:`pt-0.5`,children:e.extraNode})]})]})}function OY({actions:e,pageAction:t}){let n=(0,K.useMemo)(()=>e.filter(e=>e.group===`primary`),[e]),r=(0,K.useMemo)(()=>e.filter(e=>e.group===`author`),[e]),i=(0,K.useMemo)(()=>e.filter(e=>e.group===`organize`||e.group===void 0),[e]),a=(0,K.useMemo)(()=>e.filter(e=>e.group===`share`),[e]),o=(0,K.useMemo)(()=>e.filter(e=>e.group===`danger`),[e]),s=r.length+i.length+a.length,c=s>=SY,l=(0,K.useMemo)(()=>{let e=[];return r.length>0&&e.push({id:`author`,label:`Author`,testId:Q.L3_ACTIONS_GROUP_AUTHOR,items:r}),i.length>0&&e.push({id:`organize`,label:`Organize`,testId:Q.L3_ACTIONS_GROUP_ORGANIZE,items:i}),(a.length>0||c&&t)&&e.push({id:`share`,label:`Share & Export`,testId:Q.L3_ACTIONS_GROUP_SHARE,items:a,extraNode:c?t:void 0}),e},[r,i,a,c,t]);return(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[n.length>0&&(0,q.jsx)(`div`,{"data-testid":Q.L3_ACTIONS_PRIMARY,className:`flex flex-col gap-1.5 pb-1`,children:n.map(e=>(0,q.jsx)(EY,{action:e,variant:`primary`},e.id))}),c?(0,q.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:l.map(e=>(0,q.jsx)(DY,{bucket:e},e.id))}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:[...r,...i,...a].map(e=>(0,q.jsx)(EY,{action:e},e.id))}),t&&(0,q.jsx)(`div`,{className:$(s>0&&`pt-1`),children:t})]}),o.length>0&&(0,q.jsx)(`div`,{"data-testid":Q.L3_ACTIONS_DANGER,className:`mt-1 flex flex-col gap-0.5 border-t border-destructive/25 pt-2`,children:o.map(e=>(0,q.jsx)(EY,{action:e,variant:`danger`},e.id))})]})}function kY({spec:e,pageAction:t}){let{l3Items:n,l3Connections:r,l3Actions:i=[],analyticsControls:a}=NV(),o=SJ(e),s=SJ(r),c=(0,K.useMemo)(()=>gY(n),[n]),l=CJ(),u=!!a,d=CY(o),f=c.length>0,p=CY(s),m=d||f||p,h=i.length>0||!!t;return!u&&!m&&!h?null:(0,q.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[u&&(0,q.jsx)(`div`,{className:$(`flex flex-col gap-4`,(m||h)&&`pb-3 border-b border-border/50`),children:a&&(0,q.jsx)(TY,{controls:a})}),d&&(0,q.jsx)(TJ,{entries:o,activeId:l}),f&&(0,q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,q.jsx)(TJ,{entries:c,activeId:l})]}),p&&(0,q.jsxs)(`div`,{"data-testid":Q.L3_CONNECTIONS,className:$(`flex flex-col gap-1`,(f||d)&&`pt-3 border-t border-border/50`),children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Connections`}),(0,q.jsx)(TJ,{entries:s,activeId:l})]}),h&&(0,q.jsxs)(`div`,{"data-testid":Q.L3_ACTIONS,className:$(`flex flex-col gap-1`,m&&`pt-3 border-t border-border/50`),children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Actions`}),(0,q.jsx)(OY,{actions:i,pageAction:t})]})]})}var AY=`(min-width: 1520px)`;function jY(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(AY).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(AY);if(t(e.matches),typeof e.addEventListener!=`function`)return;let n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var MY=(0,K.createContext)(null);function NY({value:e,children:t}){return(0,q.jsx)(MY.Provider,{value:e,children:t})}function PY(){let e=(0,K.useContext)(MY),{dispatch:t,analyticsControls:n,l3Items:r,l3Connections:i,l3Actions:a=[],secondarySpec:o}=NV();return e||{railHasContent:!!(CY(o)||r&&r.length>0||CY(i)||a&&a.length>0||n),hasAppliedFilters:!1,openRightDrawer:()=>t({type:`SET_RIGHT_DRAWER`,open:!0})}}function FY(){let{railHasContent:e,hasAppliedFilters:t,openRightDrawer:n}=PY(),r=jY(),i=hY();return!e||r||i?null:(0,q.jsxs)(J,{type:`button`,variant:`ghost`,size:`icon`,onClick:n,"aria-label":`Page options`,title:`Page options (⌘.)`,"data-testid":`l3-drawer-trigger`,className:`relative hidden lg:inline-flex 2xl:hidden text-muted-foreground hover:text-foreground`,children:[(0,q.jsx)(Vi,{className:`size-4`,"aria-hidden":`true`}),t&&(0,q.jsx)(`span`,{"data-testid":`header-filters-active`,className:`absolute top-1.5 right-1.5 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Page options`})]})}function IY({id:e,parent:t,title:n,subtitle:r,titleAccessory:i,actions:a,queryBar:o,subheader:s,titleTestId:c,className:l}){let{railHasContent:u}=PY(),d=!!(a||u);return(0,q.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:$(`max-lg:hidden lg:sticky lg:top-0 z-30 border-b border-border/50 bg-background/95 backdrop-blur-md transition-colors`,l),children:[(0,q.jsxs)(`div`,{className:$(`sph-row flex min-h-[54px] justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,o?`items-start`:`items-center`),children:[(t||n)&&(0,q.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[t&&(0,q.jsxs)(M,{to:t.to,"data-testid":Q.PAGE_HEADER_PARENT_BREADCRUMB,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 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground shrink-0 no-underline`,children:[(0,q.jsx)(j,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate max-w-[140px]`,children:t.label})]}),n&&(0,q.jsxs)(q.Fragment,{children:[!t&&(0,q.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(`h1`,{"data-testid":c,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:n}),r&&(0,q.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:r})]}),i]})]})]}),o&&(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:o}),d&&(0,q.jsxs)(`div`,{className:`sph-actions flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:[a,(0,q.jsx)(FY,{})]})]}),s&&(0,q.jsx)(`div`,{className:`bg-background/40`,children:s})]})}function LY({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,K.useRef)(``),u=(0,K.useRef)(i),d=(0,K.useRef)(a),f=(0,K.useRef)(null),p=(0,K.useRef)(1);(0,K.useEffect)(()=>{u.current=i},[i]),(0,K.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,K.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,K.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,K.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,K.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 RY({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]=V(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,K.useState)(c?.[0]?.id??``);if(LY({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}),LY({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,q.jsxs)(`div`,{className:$(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,q.jsx)(IJ,{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,q.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,q.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,q.jsx)(sY,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,q.jsx)(`div`,{className:$(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,q.jsxs)(`div`,{className:$(lY,cY),children:[(0,q.jsx)(IY,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,q.jsx)(`div`,{className:`flex-1`,children:i})]})})}var zY=`[data-page-sticky-boundary="true"]`,BY=0;function VY(e,t=BY){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(zY)).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 HY(e,t=BY){let[n,r]=(0,K.useState)(e);return(0,K.useEffect)(()=>{let n=0,i=()=>r(VY(e,t)),a=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(i)};i(),window.addEventListener(`scroll`,a,{passive:!0}),window.addEventListener(`resize`,i);let o=typeof ResizeObserver>`u`?void 0:new ResizeObserver(i);document.querySelectorAll(zY).forEach(e=>o?.observe(e));let s=typeof MutationObserver>`u`?void 0:new MutationObserver(()=>{document.querySelectorAll(zY).forEach(e=>o?.observe(e)),i()});return typeof document<`u`&&document.body&&s?.observe(document.body,{childList:!0,subtree:!0}),()=>{s?.disconnect(),o?.disconnect(),cancelAnimationFrame(n),window.removeEventListener(`scroll`,a),window.removeEventListener(`resize`,i)}},[e,t]),n}function UY({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,q.jsxs)(`div`,{"data-testid":a,className:$(`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,q.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,q.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var WY=(0,K.createContext)(null),GY=(0,K.createContext)(null);function KY({children:e}){let[t,n]=(0,K.useState)(null);return(0,q.jsx)(GY.Provider,{value:n,children:(0,q.jsx)(WY.Provider,{value:t,children:e})})}function qY({className:e}){let t=(0,K.useContext)(GY);return(0,q.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function JY(){return(0,K.useContext)(WY)}function YY({editor:e,parent:t,title:n,subtitle:r,titleAccessory:i,titleTestId:a,actions:o,timerOverlay:s,reviewOverlay:c,isTimerOpen:l=!1,isReviewOpen:u=!1,onCloseTimer:d,onCloseReview:f,className:p}){return(0,q.jsxs)(`div`,{className:$(`relative flex w-full min-h-screen justify-start items-start`,p),children:[(0,q.jsxs)(`div`,{className:$(lY,cY),children:[(0,q.jsx)(IY,{parent:t,title:n,subtitle:r,titleAccessory:i,titleTestId:a,actions:o}),(0,q.jsx)(`div`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),l&&s&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,q.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,q.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,q.jsx)(`button`,{onClick:d,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,q.jsx)(`div`,{className:`flex-1 min-h-0`,children:s})]})}),u&&c&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,q.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,q.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,q.jsx)(`button`,{onClick:f,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,q.jsx)(`div`,{className:`flex-1 min-h-0`,children:c})]})})]})}var XY=`wodwiki:fabAlignment`,ZY=[{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 QY(){try{return $Y(localStorage.getItem(XY))}catch{return}}function $Y(e){return e===`right`||e===`left`?e:void 0}var eX=typeof window>`u`?void 0:QY();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===XY&&(eX=$Y(e.newValue))});function tX(e){eX=e;try{e===`right`?localStorage.removeItem(XY):localStorage.setItem(XY,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:XY,newValue:e}))}function nX(){let[e,t]=(0,K.useState)(()=>eX??`right`);return(0,K.useEffect)(()=>{let e=e=>{e.key===XY&&t($Y(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,tX]}function rX({onOpen:e}){return(0,q.jsxs)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,title:`Search`,"data-testid":`search-fab`,className:$(`size-12 rounded-full flex items-center justify-center`,`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:[(0,q.jsx)(hi,{className:`size-6`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Search`})]})}var iX=(0,K.createContext)(null),aX=(0,K.createContext)(!1),oX=(0,K.createContext)(null),sX=(0,K.createContext)(null);function cX(){return(0,K.useContext)(iX)!==null}function lX({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,K.useContext)(iX),o=(0,K.useContext)(aX),s=hY(),c=(0,K.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=K.Children.toArray(n).length>0,f=(0,K.useMemo)(()=>(0,q.jsx)(aX.Provider,{value:!0,children:n}),[n]),p=l||u,m=(0,K.useRef)(null);return m.current={id:c,primary:e,navbar:t,children:f,hasContent:d,label:r??`Page options`,fallback:i},(0,K.useEffect)(()=>{if(p)return a.register(m.current),()=>a.unregister(c)},[p,a,c]),(0,K.useEffect)(()=>{p&&a.register(m.current)},[p,a,e,t,f,d,r,i]),i||a&&s&&!o?null:(0,q.jsx)(aX.Provider,{value:!0,children:(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function uX({onSearch:e,renderDock:t=!0,secondarySpec:n,pageAction:r,children:i}){let[a,o]=(0,K.useState)([]),s=(0,K.useCallback)(e=>o(t=>{let n=t.findIndex(t=>t.id===e.id);if(n===-1)return[...t,e];let r=t[n];if(r.primary===e.primary&&r.navbar===e.navbar&&r.children===e.children&&r.hasContent===e.hasContent&&r.label===e.label&&r.fallback===e.fallback)return t;let i=[...t];return i[n]=e,i}),[]),c=(0,K.useCallback)(e=>o(t=>t.filter(t=>t.id!==e)),[]),l=(0,K.useMemo)(()=>({register:s,unregister:c}),[s,c]),u=(0,K.useMemo)(()=>{for(let e=a.length-1;e>=0;--e)if(!a[e].fallback)return a[e].navbar??null;return null},[a]),d=(0,K.useMemo)(()=>({registrations:a,onSearch:e,secondarySpec:n,pageAction:r}),[a,e,n,r]);return(0,q.jsx)(iX.Provider,{value:l,children:(0,q.jsx)(oX.Provider,{value:u,children:(0,q.jsxs)(sX.Provider,{value:d,children:[i,t&&(0,q.jsx)(mX,{registrations:a,onSearch:e,secondarySpec:n,pageAction:r})]})})})}function dX(){let e=(0,K.useContext)(sX);return e?(0,q.jsx)(mX,{registrations:e.registrations,onSearch:e.onSearch,secondarySpec:e.secondarySpec,pageAction:e.pageAction}):null}function fX(){let e=(0,K.useContext)(oX);return e?(0,q.jsx)(q.Fragment,{children:e}):null}function pX(e){return`[data-testid="${e}"]`}function mX({registrations:e,onSearch:t,secondarySpec:n,pageAction:r}){let i=hY(),[a]=nX(),o=Wj(),s=PV(),c=wY(n,r),l=!!s?.navState?.rightDrawerOpen,u=!!(s?.navState?.inspectorDrawerOpen||s?.peekTarget),d=s?.dispatch,f=s?.analyticsControls?.onReset,[p,m]=(0,K.useState)(!1),[g,_]=(0,K.useState)(!1),v=p||l,y=(0,K.useCallback)(()=>{m(!1),l&&d?.({type:`SET_RIGHT_DRAWER`,open:!1})},[l,d]),b=(0,K.useCallback)(()=>{v?y():m(!0)},[v,y]),x=(0,K.useId)(),S=(0,K.useRef)(null),C=(0,K.useRef)(null),w=(0,K.useRef)(null),T=(0,K.useRef)(null),E=(0,K.useRef)(v);E.current=v;let D=(0,K.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),O=(0,K.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]),k=(0,K.useCallback)(()=>{if(typeof document>`u`||!i){_(e=>e&&!1);return}if(u){m(e=>e&&!1),_(e=>e||!0);return}if(document.querySelector(`${pX(Q.MOBILE_WHEEL_COMPOSER)}, ${pX(Q.MOBILE_TYPING_BAR)}`)){m(e=>e&&!1),_(e=>e||!0);return}let e=window.visualViewport;if(e&&window.innerHeight-(e.height+e.offsetTop)>100){m(e=>e&&!1),_(e=>e||!0);return}let t=document.querySelector(pX(Q.RESULTS_MOBILE_BAR));if(t&&!t.hidden){let e=window.getComputedStyle(t);if(e.display!==`none`&&e.visibility!==`hidden`){m(e=>e&&!1),_(e=>e||!0);return}}if(!E.current&&S.current){let e=S.current.getBoundingClientRect();if(e.width>0&&e.height>0){let t=document.querySelectorAll(`.cm-frontmatter-preview input`);for(let n of t){let t=n.getBoundingClientRect();if(t.width<=4||t.height<=4||t.bottom<=0||t.top>=window.innerHeight||t.right<=0||t.left>=window.innerWidth)continue;let r=window.getComputedStyle(n);if(r.display!==`none`&&r.visibility!==`hidden`&&t.left<e.right+4&&e.left-4<t.right&&t.top<e.bottom+4&&e.top-4<t.bottom){_(e=>e||!0);return}}}}_(e=>e&&!1)},[i,u]);(0,K.useLayoutEffect)(()=>{k()},[k,a,v,D,O,t,o.height,c]),(0,K.useEffect)(()=>{if(!i||typeof document>`u`||!document.body)return;k();let e=new MutationObserver(e=>{S.current&&e.every(e=>S.current.contains(e.target))||k()});e.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`hidden`,`style`,`class`]});let t=new MutationObserver(()=>{k()});t.observe(document.documentElement,{attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`scroll`,k,{passive:!0,capture:!0}),window.addEventListener(`resize`,k,{passive:!0});let n=window.visualViewport;return n?.addEventListener(`resize`,k),n?.addEventListener(`scroll`,k),()=>{e.disconnect(),t.disconnect(),window.removeEventListener(`scroll`,k,{capture:!0}),window.removeEventListener(`resize`,k),n?.removeEventListener(`resize`,k),n?.removeEventListener(`scroll`,k)}},[i,k]),(0,K.useLayoutEffect)(()=>{v&&C.current?.focus({preventScroll:!0})},[v]);let A=!!(D?.hasContent||O?.hasContent||c),j=D?.hasContent?D.label:O?.hasContent?O.label:`Page options`;if(!i||!t&&!D&&!O&&!c)return null;let M=o.height===null?`100dvh`:`${o.height}px`;return(0,q.jsxs)(`div`,{ref:S,"data-testid":Q.ACTIONS_DOCK,"aria-hidden":g||void 0,className:$(`fixed z-40 lg:hidden flex flex-col gap-2 w-auto`,`transition-opacity duration-150 ease-out`,a===`left`?`left-4 items-start`:`right-4 items-end`,g&&`invisible pointer-events-none`),style:{bottom:`calc(1rem + var(--thumb-dock-lift, 0px) + env(safe-area-inset-bottom, 0px))`,maxHeight:`calc(${M} - 2rem - var(--thumb-dock-lift, 0px) - env(safe-area-inset-bottom, 0px))`},children:[v&&A&&(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 bg-black/20 dark:bg-black/35 cursor-default`,onClick:y}),(0,q.jsx)(`div`,{id:x,ref:C,role:v&&A?`dialog`:void 0,"aria-modal":v&&A?!0:void 0,"aria-label":v&&A?j:void 0,tabIndex:-1,hidden:!v||!A,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),y())},className:$(v&&A?`flex`:`hidden`,`relative z-40 min-h-0 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/10 outline-none`,c?`w-72`:`w-60`,`[&_button]:min-h-11 [&_button]:min-w-11 [&_summary]:min-h-11`),style:{maxHeight:`calc(${M} - 8rem - var(--thumb-dock-lift, 0px) - env(safe-area-inset-bottom, 0px))`},children:(0,q.jsxs)(XH,{close:y,children:[c&&(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/50 pb-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground truncate`,children:j}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[f&&(0,q.jsx)(`button`,{type:`button`,onClick:f,"data-testid":Q.L3_DRAWER_RESET_BTN,className:`inline-flex min-h-11 items-center justify-center rounded-lg px-2.5 text-xs font-medium text-muted-foreground hover:bg-muted/60 hover:text-foreground transition-colors`,children:`Reset`}),(0,q.jsx)(`button`,{type:`button`,onClick:y,"data-testid":Q.L3_DRAWER_DONE_BTN,className:`inline-flex min-h-11 items-center justify-center rounded-lg bg-primary/10 px-3 text-xs font-semibold text-primary hover:bg-primary/15 transition-colors`,children:`Done`})]})]}),D?.hasContent&&(0,q.jsx)(`div`,{ref:w,className:`contents`,children:D.children}),v&&c&&(0,q.jsxs)(q.Fragment,{children:[D?.hasContent&&(0,q.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,q.jsx)(`div`,{"data-testid":Q.ACTIONS_SHEET_L3,className:`-mx-3 -my-2 flex flex-col`,children:(0,q.jsx)(kY,{spec:n,pageAction:r})})]}),O?.hasContent&&(0,q.jsxs)(q.Fragment,{children:[(D?.hasContent||c)&&(0,q.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,q.jsx)(`div`,{ref:T,className:`contents`,children:O.children})]})]})}),(t||D?.primary)&&(0,q.jsxs)(`div`,{className:$(`relative z-40 flex shrink-0 flex-col gap-2`,a===`left`?`items-start`:`items-end`),children:[t&&(0,q.jsx)(rX,{onOpen:()=>{y(),t()}}),D?.primary&&(0,q.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:D.primary})]}),A&&(0,q.jsxs)(`button`,{type:`button`,onClick:b,"aria-label":j,title:j,"aria-expanded":v,"aria-controls":x,"data-testid":Q.ACTIONS_OVERFLOW,className:$(`relative z-40 flex size-12 shrink-0 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:[v?(0,q.jsx)(h,{className:`size-6`}):(0,q.jsx)(hn,{className:`size-6`}),(0,q.jsx)(`span`,{className:`sr-only`,children:j})]})]})}var hX=null,gX=new Set;function _X(e){hX=e;for(let e of gX)e();return()=>{if(hX===e){hX=null;for(let e of gX)e()}}}function vX(){return hX}function yX(e){return gX.add(e),()=>{gX.delete(e)}}function bX(){return(0,K.useSyncExternalStore)(yX,vX,()=>null)}var xX=null,SX=new Set;function CX(e){xX=e;for(let e of SX)e();return()=>{if(xX===e){xX=null;for(let e of SX)e()}}}function wX(){return xX}function TX(e){return SX.add(e),()=>{SX.delete(e)}}function EX(){return(0,K.useSyncExternalStore)(TX,wX,()=>null)}var DX=null,OX=new Set;function kX(e){DX=e;for(let e of OX)e();return()=>{if(DX===e){DX=null;for(let e of OX)e()}}}function AX(){return DX}function jX(e){return OX.add(e),()=>{OX.delete(e)}}function MX(){return(0,K.useSyncExternalStore)(jX,AX,()=>null)}var NX=null,PX=new Set;function FX(e){NX=e;for(let e of PX)e();return()=>{if(NX===e){NX=null;for(let e of PX)e()}}}function IX(){return NX}function LX(e){return PX.add(e),()=>{PX.delete(e)}}function RX(){return(0,K.useSyncExternalStore)(LX,IX,()=>null)}var zX=[],BX=null,VX=null,HX=null,UX=new Set;function WX(){let e=zX.length>0?zX[zX.length-1]:null;if(!e&&!BX&&!VX)HX=null;else{let t=BX,n=VX;HX={getTarget:()=>(e?e.getTarget():t)??null,openPeek:t=>{if(e)e.openPeek(t);else throw Error(`No Entity Peek host is registered to open new targets.`)},closePeek:()=>{n?.(),e?.closePeek()}}}for(let e of UX)e()}function GX(e){return zX.push(e),WX(),()=>{let t=zX.lastIndexOf(e);t!==-1&&(zX.splice(t,1),WX())}}function KX(e,t){return BX=e,VX=e?t:null,WX(),()=>{BX===e&&(BX=null,VX=null,WX())}}function qX(){return HX}function JX(e){return UX.add(e),()=>{UX.delete(e)}}function YX(){return(0,K.useSyncExternalStore)(JX,qX,()=>null)}var XX=0,ZX=new Set;function QX(e){if(!e)return()=>{};XX+=1;for(let e of ZX)e();let t=!1;return()=>{if(!t){t=!0,XX=Math.max(0,XX-1);for(let e of ZX)e()}}}function $X(){return XX>0}function eZ(e){return ZX.add(e),()=>{ZX.delete(e)}}function tZ(){return(0,K.useSyncExternalStore)(eZ,$X,()=>!1)}function nZ(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 e.phase}}function rZ(e){if(!e||e.phase===`checking`||e.phase===`finished`)return null;let t=[];return typeof e.completedRecords==`number`&&typeof e.totalRecords==`number`&&t.push(`${e.completedRecords} / ${e.totalRecords} records`),e.totalChunks>0&&t.push(`${e.completedChunks} / ${e.totalChunks} notebooks`),t.length>0?t.join(` · `):null}var iZ=[`samples-movement`,`samples-results`],aZ=`wodwiki.seedSubscriptions`,oZ=`wodwiki.seedAutoSync`;function sZ(e){try{let t=typeof localStorage<`u`?localStorage.getItem(e):null;if(!t)return new Set;let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?new Set:new Set(Object.keys(n))}catch{return new Set}}function cZ(e){let t=new Set(e.map(e=>e.id)),n=QF()??{},r=new Set([...sZ(aZ),...Object.keys(n)]),i=new Set([...sZ(oZ),...Object.keys(tI()??{}),...Object.entries(n).filter(([,e])=>e.autoSync!==void 0).map(([e])=>e)]),a=rI()??{},o=[];for(let e of iZ)t.has(e)&&(r.has(e)||(VI(e,!0),!a[e]&&!n[e]?.offlinePolicy&&XI(e,`index-only`),o.push(e)),i.has(e)||JI(e,!0));return o}var lZ=`idle`,uZ=null,dZ=!1,fZ=0,pZ=null,mZ=!1,hZ=new Set,gZ=null,_Z=null;function vZ(){for(let e of hZ)e()}function yZ(e){typeof document>`u`||(document.documentElement.dataset.feedState=e)}function bZ(e){typeof document>`u`||(e===null?delete document.documentElement.dataset.feedOutcome:document.documentElement.dataset.feedOutcome=e)}function xZ(e){typeof document>`u`||(e?document.documentElement.dataset.feedImportPending=`true`:delete document.documentElement.dataset.feedImportPending)}yZ(lZ);function SZ(e){lZ!==e&&(lZ=e,yZ(e),vZ())}function CZ(e){if(dZ===e)return;let t=dZ||fZ>0;dZ=e;let n=dZ||fZ>0;xZ(n),t!==n&&vZ()}function wZ(e){let t=dZ||fZ>0;fZ+=1,e!==void 0&&(pZ=e),xZ(dZ||fZ>0),(!t||e!==void 0)&&vZ()}function TZ(){if(fZ===0)return;let e=dZ||fZ>0;fZ=Math.max(0,fZ-1),fZ===0&&(pZ=null);let t=dZ||fZ>0;xZ(t),(e!==t||fZ===0)&&vZ()}function EZ(){return pZ}function DZ(){return(0,K.useSyncExternalStore)(LZ,EZ)}function OZ(){gZ&&=(clearTimeout(gZ),null),_Z&&=(_Z.close(),null)}function kZ(e){uZ=e,vZ()}function AZ(){OZ(),bZ(null);let e=uZ!==null,t=!dZ;if(uZ=null,dZ=!0,xZ(!0),lZ===`preparing`){(e||t)&&vZ();return}SZ(`preparing`)}function jZ(){lZ===`preparing`&&!dZ&&fZ===0&&SZ(`ready`)}function MZ(e){let t=lZ,n=dZ||fZ>0;dZ=!1,lZ=e;let r=dZ||fZ>0;xZ(r),yZ(e),(t!==e||n!==r)&&vZ()}function NZ(e){switch(bZ(e),e){case`busy`:if(lZ!==`preparing`&&!dZ)return;typeof BroadcastChannel<`u`&&!_Z&&(_Z=new BroadcastChannel(mx),_Z.onmessage=e=>{e.data?.kind===`seed-imported`&&(OZ(),mZ=!1,MZ(`ready`))}),gZ=setTimeout(()=>{aV({onProgress:kZ}).then(NZ)},IB);break;case`error`:OZ(),mZ?SZ(`error`):MZ(`error`);break;default:if(OZ(),mZ)return;MZ(`ready`)}}function PZ(){return lZ===`idle`?`ready`:lZ}function FZ(){return dZ||fZ>0}function IZ(){return uZ}function LZ(e){return hZ.add(e),()=>hZ.delete(e)}function RZ(){return(0,K.useSyncExternalStore)(LZ,PZ)}function zZ(){return(0,K.useSyncExternalStore)(LZ,FZ)}function BZ(){return(0,K.useSyncExternalStore)(LZ,IZ)}var VZ=null;function HZ(e={}){return FE(`feedStart`),(e.isEnabled??VB)()&&CZ(!0),VZ??=WZ(e).finally(()=>{FE(`feedSettled`)}),VZ}async function UZ(e,t){for(let n of e)if(!(n.id===`core`||!BI(n.id)||!qI(n.id)))try{let e=await t.getSeedMeta(bx(n.id));if(!e||e.seedVersion<=0)return!0}catch{return!0}return!1}async function WZ(e){let t=t=>{kZ(t),e.onProgress?.(t)},n=e.storage??NI();n.storageInstance&&await ZF(n.storageInstance).catch(e=>console.error(`[feedSync] registry hydration failed`,e));let r=e.sources??HB();await vV(e).catch(e=>console.error(`[feedSync] notebook vocabulary migration failed`,e)),await gV(e).catch(e=>console.error(`[feedSync] checkpoint adoption failed`,e)),await Mue(r,n).catch(e=>console.error(`[feedSync] subscription migration failed`,e)),cZ(r);let i;try{i=await n.getSeedMeta(bx(`core`))}catch{i=void 0}let a=(e.isEnabled??VB)(),o=!i||i.seedVersion<=0,s=!o&&await UZ(r,n);if(a&&(o||s)?(mZ=!0,AZ()):NZ(`current`),await _V(e).catch(e=>console.error(`[feedSync] feed provenance repair failed`,e)),o){try{let n=await aV({...e,sources:r,onProgress:t,onFirstPaint:()=>jZ()});n!==`busy`&&n!==`error`&&r.some(e=>e.id!==`core`&&BI(e.id))&&await aV({...e,sources:r.filter(e=>e.id!==`core`),onProgress:t}).catch(e=>console.error(`[feedSync] background boot sync failed`,e)),mZ=!1,NZ(n)}finally{mZ&&(mZ=!1,CZ(!1))}return}let c=`current`;try{c=await aV({...e,sources:r,onProgress:t}).catch(e=>(console.error(`[feedSync] background boot sync failed`,e),`error`))}finally{mZ&&(mZ=!1,NZ(c===`error`?`current`:c))}}function GZ(){let[e,t]=(0,K.useState)(null);return(0,K.useEffect)(()=>{let e=!1,n=()=>{pV().then(n=>{e||t(!n.libraryImported)}).catch(()=>{e||t(!0)})};n();let r=DE(()=>n()),i=$B(()=>n()),a=null;if(typeof BroadcastChannel<`u`)try{a=new BroadcastChannel(mx),a.onmessage=()=>n()}catch{}return()=>{e=!0,r(),i(),a?.close()}},[]),e}var KZ=`(min-width: 1520px)`;function qZ(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(KZ).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(KZ);if(t(e.matches),typeof e.addEventListener!=`function`)return;let n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function JZ(){return(0,q.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,q.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 YZ(){return(0,q.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,q.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 XZ({open:e,close:t,onSearch:n,children:r}){let i=(0,K.useRef)(null);return(0,q.jsxs)(Fr,{side:`start`,open:e,onOpenChange:e=>{e||t()},children:[(0,q.jsx)(We,{className:`bg-black/30 dark:bg-black/30 transition-none data-[closed]:hidden lg:hidden`}),(0,q.jsxs)(lt,{initialFocus:()=>i.current,"data-testid":Q.MOBILE_NAV_DRAWER,className:`w-full max-w-none h-dvh max-h-dvh p-0 gap-0 rounded-none border-0 bg-card transition-none data-[closed]:hidden lg:hidden`,children:[(0,q.jsx)(ve,{className:`sr-only`,children:`Navigation`}),(0,q.jsx)(XH,{close:t,children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,q.jsx)(`div`,{className:`flex h-full w-[156px] sm:w-44 shrink-0 flex-col overflow-y-auto border-r border-zinc-950/5 bg-background/72 px-2 py-3 dark:border-white/5`,children:(0,q.jsx)(FJ,{variant:`mobile-list`,onSearch:()=>{t(),n?.()}})}),(0,q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-end px-3 pt-3`,children:(0,q.jsx)(Xe,{render:(0,q.jsx)(jq,{"aria-label":`Close navigation`,title:`Close navigation`,"data-testid":Q.MOBILE_NAV_CLOSE}),children:(0,q.jsx)(YZ,{})})}),(0,q.jsx)(`div`,{ref:i,tabIndex:-1,className:`flex min-h-0 flex-1 flex-col outline-none`,children:r})]})]})})]})]})}function ZZ({open:e,close:t,showControlsFooter:n=!1,onReset:r,children:i}){let a=(0,K.useRef)(null);return(0,q.jsxs)(Fr,{side:`end`,open:e,onOpenChange:e=>{e||t()},children:[(0,q.jsx)(We,{className:`bg-black/25 dark:bg-black/40 transition-none data-[closed]:hidden 2xl:hidden`}),(0,q.jsx)(lt,{initialFocus:()=>a.current,"data-testid":Q.L3_RIGHT_DRAWER,"aria-label":`Page options panel`,className:`w-full lg:w-80 max-w-none h-dvh max-h-dvh p-0 gap-0 rounded-none border-0 lg:border-l lg:border-border/60 bg-card lg:shadow-2xl flex flex-col transition-none data-[closed]:hidden 2xl:hidden`,children:(0,q.jsxs)(XH,{close:t,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border/40 px-4 py-2.5`,children:[(0,q.jsx)(ve,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Page options`}),(0,q.jsx)(Xe,{render:(0,q.jsx)(jq,{"aria-label":`Close page options`,title:`Close page options`}),children:(0,q.jsx)(YZ,{})})]}),(0,q.jsx)(`div`,{ref:a,tabIndex:-1,className:`flex min-h-0 flex-1 flex-col overflow-y-auto outline-none`,children:i}),n&&(0,q.jsxs)(`div`,{className:`shrink-0 flex items-center gap-2 border-t border-border/50 bg-card p-3`,children:[r&&(0,q.jsx)(`button`,{type:`button`,onClick:r,"data-testid":Q.L3_DRAWER_RESET_BTN,className:`h-10 max-lg:h-11 flex-1 rounded-lg border border-border bg-background px-3 text-sm font-medium text-foreground hover:bg-muted transition-colors`,children:`Reset`}),(0,q.jsx)(`button`,{type:`button`,onClick:t,"data-testid":Q.L3_DRAWER_DONE_BTN,className:`h-10 max-lg:h-11 flex-1 rounded-lg bg-primary px-3 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Done`})]})]})})]})}function QZ({navbar:e,sidebar:t,onSearch:n,secondary:r,pageAction:i,peekSlot:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,K.useState)(!1),u=qZ(),d=hY(),{navState:f,dispatch:p,peekTarget:m,closePeek:h,analyticsControls:g}=NV(),_=Qe().pathname===`/`||!!o,v=!!f?.rightDrawerOpen,y=!!(f?.inspectorDrawerOpen||m),b=!!(m&&a),x=(0,K.useCallback)(e=>p({type:`SET_RIGHT_DRAWER`,open:e}),[p]),S=(0,K.useCallback)(()=>x(!0),[x]),C=(0,K.useCallback)(()=>x(!1),[x]),w=wY(r,i),T=(0,K.useMemo)(()=>({railHasContent:w,hasAppliedFilters:!1,openRightDrawer:S}),[w,S]);(0,K.useEffect)(()=>{if(!c&&!v&&!m)return;let e=()=>{l(!1),x(!1),h?.()};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[c,v,m,x,h]),(0,K.useEffect)(()=>{if(!w)return;let e=e=>{if(!e.defaultPrevented&&(e.metaKey||e.ctrlKey)&&e.key===`.`&&!e.shiftKey&&!e.altKey){if(window.innerWidth>=1520)return;e.preventDefault(),x(!v)}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[w,v,x]),(0,K.useEffect)(()=>{if(!b)return;let e=e=>{e.defaultPrevented||e.key===`Escape`&&(e.preventDefault(),h?.())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[b,h]);let E=u&&w&&!y,D=!u&&!d&&v;return(0,q.jsx)(NY,{value:T,children:(0,q.jsx)(KY,{children:(0,q.jsx)(uX,{onSearch:n,renderDock:!1,secondarySpec:r,pageAction:i,children:(0,q.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,q.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,q.jsxs)(`div`,{"data-shell-nav":`desktop`,className:`hidden lg:flex`,children:[(0,q.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,q.jsx)(FJ,{onSearch:n??(()=>{})})}),(0,q.jsx)(`div`,{className:$(`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,q.jsx)(XZ,{open:c,close:()=>l(!1),onSearch:n,children:t}),(0,q.jsxs)(`div`,{className:$(`flex flex-1 flex-col min-w-0 2xl:max-w-none`,_||y?`xl:max-w-none`:`xl:max-w-[984px]`),children:[(0,q.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,q.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,q.jsxs)(jq,{onClick:()=>l(!0),"aria-label":`Open navigation`,title:`Open navigation`,"data-testid":Q.MOBILE_NAV_OPEN,children:[(0,q.jsx)(JZ,{}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Open navigation`})]})}),(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:e})]}),(0,q.jsxs)($Z,{children:[(0,q.jsx)(`div`,{className:`grow w-full max-lg:pb-[calc(12rem+var(--thumb-dock-lift,0px)+env(safe-area-inset-bottom,0px))] lg:overflow-visible`,children:s}),(0,q.jsx)(tQ,{}),(0,q.jsx)(dX,{})]})]}),E&&(0,q.jsx)(`aside`,{"aria-label":`Page outline and actions`,"data-testid":Q.L3_INLINE_RAIL,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,q.jsx)(kY,{spec:r,pageAction:i})}),y&&(0,q.jsx)(`div`,{"aria-hidden":`true`,"data-testid":Q.INSPECTOR_DRAWER_RAIL_SPACER,className:`hidden xl:block w-[340px] shrink-0`}),b&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":`Close peek drawer`,"data-testid":Q.PEEK_DRAWER_BACKDROP,onClick:()=>h?.(),className:`xl:hidden fixed inset-0 z-[29] bg-black/25 dark:bg-black/40 cursor-default`}),(0,q.jsx)(`div`,{"data-testid":Q.PEEK_DRAWER_SLOT,className:`fixed right-0 top-0 bottom-0 z-30 flex w-[340px] max-w-[92vw] flex-col overflow-hidden max-xl:shadow-2xl xl:shadow-none`,children:a})]}),D&&(0,q.jsx)(ZZ,{open:v,close:C,showControlsFooter:!!g,onReset:g?.onReset,children:(0,q.jsx)(kY,{spec:r,pageAction:i})})]})})})})})}function $Z({children:e}){let t=Qe(),n=tZ(),r=RZ(),i=zZ(),a=DZ(),o=BZ(),s=n||r===`preparing`||i,c=i&&t.pathname!==`/`,l=c?rZ(o):null;return(0,q.jsxs)(`main`,{"aria-busy":s,"data-agent-status":s?`loading`:`ready`,className:`flex flex-1 flex-col lg:min-w-0`,children:[e,c&&(0,q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"data-testid":Q.BOOT_IMPORT_PROGRESS,className:`pointer-events-none fixed z-30 max-lg:bottom-[calc(0.75rem+var(--thumb-dock-lift,0px)+env(safe-area-inset-bottom,0px))] max-lg:left-3 max-lg:right-auto max-lg:max-w-[calc(100vw-5.5rem)] lg:bottom-4 lg:right-4 lg:left-auto flex items-center gap-2 rounded-lg border border-border bg-card/95 px-3 py-1.5 text-xs text-foreground shadow-sm`,children:[(0,q.jsx)(`span`,{className:`truncate`,children:a??(o?nZ(o):`Importing library…`)}),l&&(0,q.jsx)(`span`,{className:`text-muted-foreground shrink-0`,children:l})]})]})}var eQ=17;function tQ(){let e=(0,K.useRef)(null),[t,n]=(0,K.useState)(0);(0,K.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()},[]);let r=t>0?t+eQ:0;return(0,K.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${r}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[r]),(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:$(`lg:hidden fixed inset-x-0 bottom-0 z-30`,r>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,q.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,q.jsx)(qY,{className:`flex w-full min-w-0`})})}),(0,q.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:r}})]})}function nQ(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function rQ(e){return String(lc(ac(e).meta,`search`)??``).toLowerCase()===`hidden`}function iQ(e){let t=lc(ac(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 aQ(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=lc(ac(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():wP(r),category:nQ(n),content:i,date:iQ(i),searchHidden:rQ(i)}})}function oQ(){let e=HP();return(0,K.useMemo)(()=>e?aQ(e):[],[e])}var sQ={};function cQ(e,t){let{canvasPage:n,workoutItems:r,selectWorkout:i}=t;if(e===`/`)return[];if(n){let t=/^\/notebook\//.test(e),a=t?e.split(`/`).pop()??null:null,o=[],s=e.startsWith(`/page/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=$K(e).split(`
|
|
812
|
+
`,r),a=i===-1?n:i,o=e.slice(r,a).trim();if(o&&t.push(o.length>lJ?`${o.slice(0,119)}…`:o),i===-1)break;r=i+1}return t}function fJ(e,t){if(e.length<t)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)!==96)return!1;return!0}function pJ(e){let{rawContent:t,blocks:n,sourceRevision:r}=e;if(typeof t!=`string`||!n||typeof n!=`object`||Array.isArray(n)||!Number.isSafeInteger(r)||r<1)return;let i;for(let[e,a]of Object.entries(n)){if(!a||!e||a.id!==e||!Number.isSafeInteger(a.version)||a.version<1||a.sourceRevision!==r||!Number.isSafeInteger(a.from)||!Number.isSafeInteger(a.to)||a.from<0||a.to<a.from||a.to>t.length)return;a.kind===`wod`&&(!i||a.from<i.from)&&(i=a)}if(!i)return;if(i.from>0){let e=t.charCodeAt(i.from-1);if(e!==10&&e!==13)return}let a=t.slice(i.from,i.to),o=-1,s=-1;for(let e=0;e<a.length;e++){let t=a.charCodeAt(e);if(t===13){o=e,s=a.charCodeAt(e+1)===10?e+2:e+1;break}if(t===10){o=e,s=e+1;break}}if(o===-1||s>a.length)return;let c=uJ.exec(a.slice(0,o).trim());if(!c)return;let l=c[1].length,u=c[2].toLowerCase()===`log`?`log`:`time`,d=c[3];if(i.dialect!==void 0&&i.dialect!==u||i.sport!==void 0&&i.sport!==d)return;let f=-1;for(let e=a.length-1;e>=s-1;e--){let t=a.charCodeAt(e);if(t===10||t===13){f=e;break}}if(f===-1)return;let p=f+1;if(!fJ(a.slice(p).trim(),l))return;let m=s;for(;m<p;){let e=m;for(;e<p;){let t=a.charCodeAt(e);if(t===10||t===13)break;e++}if(fJ(a.slice(m,e).trim(),l))return;m=a.charCodeAt(e)===13&&a.charCodeAt(e+1)===10?e+2:e+1}let h=a.slice(s,p),g=os(h);return{blockId:i.id,blockVersion:i.version,blockContentId:g,content:h}}function mJ(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,sourceNotebook:`results`,sourceNote:i??r??`${t}:${n}`,title:a?sG(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function hJ(e){let t=e.parsed.family===`aggregate`?e.parsed.metric:`metric`;return e.series.map(e=>{let n=e.points.map(t=>`${t.value}${e.unit?` ${e.unit}`:``}`).join(` • `);return{id:`aggregate:${t}:${e.key}`,kind:`result`,sourceNotebook:`results`,sourceNote:e.label,title:`${t}: ${n}`,subtitle:e.label,date:null}})}function gJ(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function _J(e){return typeof e==`object`&&!!e&&`runFind`in e}var vJ=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){_J(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver),this.noteTitleResolver||=async e=>{try{let t=await X.getNote(e);return t?MT(t.title)||NT(t.rawContent??``):void 0}catch{return}}}get service(){return this.customService??sJ}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,n,r){if(t&&r)for(let t of e){let e=r[t.id];e&&e.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.map(e=>e.label)),t.typedTags=e.map(e=>({label:e.label,type:e.type})))}let i=new Set;for(let r of e)if(!(r.kind===`feed`||r.kind===`notebook`||r.isRemotePreview)){if(n&&Object.prototype.hasOwnProperty.call(n,r.id)){let e=n[r.id];r.placements=e;let t=us(e);r.pageId??=t.pageId,t.pageSlug&&(r.pageSlug=t.pageSlug);continue}(r.kind===`note`||r.sourceNotebook===`journal`)&&i.add(r.id),t&&(!r.title||!r.tags||r.tags.length===0)&&i.add(r.id)}if(i.size===0)return;let a=await X.getDetailBatches([...i]);for(let t of e){if(t.kind===`feed`||t.kind===`notebook`||t.isRemotePreview||!i.has(t.id))continue;let e=a.get(t.id);if(!e)continue;let n=ls(e.links??[],e.pages??[]);t.placements=n;let r=us(n);t.pageId??=r.pageId,r.pageSlug&&(t.pageSlug=r.pageSlug)}if(t)for(let t of e){let e=a.get(t.id);!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,n){let r=typeof e==`string`?Xg(e):e;if(!r||r.error)return[];if(Fg(r)){if(r.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(r):await this.service.runFind(r),n=new Map(e.notes.map(e=>[e.id,e])),i=(e.efforts??[]).map(e=>e.ownerNoteId&&n.has(e.ownerNoteId)?eG(n.get(e.ownerNoteId)):uG(e));return gJ(t,e.stages,i),i}if(r.target===`block`){let e=await this.service.runFind(r),n=e.blocks.map(oG);return await this.hydrateEntries(n,!0),gJ(t,e.stages,n),n}if(r.target===`session`){let e=await this.service.runFind(r);t?.(e.stages);let n;if(this.noteTitleResolver&&e.runs){n=new Map;for(let t of e.runs)if(!n.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&n.set(t.noteId,e)}}let i=xG(e,{noteTitles:n});return gJ(t,e.stages,i),i}if(r.target===`segment`||r.target===`event`){let e=r.target,n=await this.service.runFind(r),i=(n.table?.rows??[]).map((t,n)=>mJ(t,e,n));return gJ(t,n.stages,i),i}let e=await this.service.runFind(r,n?.notebookPlane?{notebookPlane:n.notebookPlane}:void 0),i=e.notes.map(eG);if(this.noteTagsResolver?(await this.hydrateEntries(i,!1,e.placements,e.typedTags),await Promise.all(i.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(i,!0,e.placements,e.typedTags),gJ(t,e.stages,i),this.noteBlockInfo)for(let t=0;t<i.length;t++){let n=i[t],r=e.notes[t];n.excerpt=dJ(r.rawContent);let a=pJ(r);a&&(n.wodBlock=a,n.blockContentId=a.blockContentId)}return i}if(r.family===`aggregate`){if(!this.service.runQuery)return[];let e=await this.service.runQuery(r.raw),n=hJ(e);return t?.({selected:e.stages?.selected??n.length,matched:n.length}),n}return[]}};async function yJ(e,t=vJ,n){return t.query(e,n)}function bJ(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function xJ(e){try{let t=(await yJ(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 SJ(e){let t=bJ(e),n=(0,K.useRef)(e);n.current=e;let[r,i]=(0,K.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,K.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`?xJ(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),!e||!e.some(e=>e.kind===`wql`)?e??[]:r}function CJ(){let[e]=V(`h`,{shallow:!0}),[t]=V(`s`,{shallow:!0}),{navState:n}=NV(),r=n.activeL3Id??``;return e||t||r||``}function wJ({entry:e,active:t,onActivate:n,onRunAction:r,onFilter:i}){let a=e.onRun,o=e.filterTo,s=e.filterLabel??`Filter notes by ${e.label}`,c=e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,l=(0,q.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:$(`flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-1.5 max-lg:min-h-11 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,!a&&!o&&`w-full`,e.muted?`text-xs`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[e.icon&&(0,q.jsx)(e.icon,{"aria-hidden":`true`,className:`size-4 shrink-0`}),e.timestamp&&(0,q.jsx)(`span`,{className:`shrink-0 font-mono text-xs tabular-nums text-muted-foreground`,children:e.timestamp}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,q.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-xs uppercase tracking-wide text-muted-foreground`,children:e.badge})]});return!a&&!o?l:(0,q.jsxs)(`div`,{className:`group flex w-full items-center gap-0.5`,children:[l,o&&(0,q.jsx)(`button`,{type:`button`,"aria-label":s,title:s,"data-testid":`menu-filter-${e.id}`,onClick:()=>i(o),className:`flex size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 items-center justify-center rounded-md text-foreground/75 transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,children:(0,q.jsx)(p,{"aria-hidden":`true`,className:`size-3.5`})}),a&&(0,q.jsx)(`button`,{type:`button`,"aria-label":c,title:c,onClick:()=>r(e),className:`flex size-7 max-lg:min-h-11 max-lg:min-w-11 shrink-0 items-center justify-center rounded text-primary opacity-70 lg:opacity-0 transition-all group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 hover:bg-primary/10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary`,children:e.runIcon===`link`?(0,q.jsx)(Vn,{"aria-hidden":`true`,className:`size-3.5`}):e.runIcon===`stop`?(0,q.jsx)(ue,{"aria-hidden":`true`,className:`size-3.5`}):e.runIcon===`edit`?(0,q.jsx)(ke,{"aria-hidden":`true`,className:`size-3.5`}):(0,q.jsx)(re,{"aria-hidden":`true`,className:`size-3.5`})})]})}function TJ({entries:e,activeId:t,onSection:n,onSelect:r}){let i=dt(),{scrollToSection:a}=NV(),o=ZH(),s=e=>{if(o(),n)return n(e);if(e.onSelect)return e.onSelect();if(r)return r(e);if(e.onRun)return e.onRun();if(e.to)return i(e.to);if(e.sectionId)return a(e.sectionId)},c=e=>{o(),e.onRun?.()},l=e=>{o(),i(e)};return(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,q.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,q.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,q.jsx)(TJ,{entries:e.entries,activeId:t,onSection:n,onSelect:r})]},e.id):e.kind===`wql`?null:e.kind===`widget`?(0,q.jsx)(`div`,{className:`px-1 py-1`,children:e.render()},e.id):(0,q.jsx)(wJ,{entry:e,active:t!=null&&e.sectionId===t,onActivate:s,onRunAction:c,onFilter:l},e.id))})}function EJ(){let e=dt(),{scrollToSection:t}=NV();return{navigate:(t,n)=>{e(t,{replace:n?.replace})},setQueryParam:(e,t)=>{},scrollToSection:t}}function DJ(){let e=EJ(),t=ZH();return n=>{t(),AG(n.action,e)}}function OJ(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 kJ({items:e}){let{navState:t}=NV(),n=Qe(),r=DJ();return(0,q.jsx)(tU,{children:e.map(e=>{let i=OJ(e,t,n);return e.children&&e.children.length>0?(0,q.jsx)(FG,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>OJ(e,t,n)),collapsible:e.id!==`syntax-group`,buttonClassName:`text-xs font-bold tracking-[0.14em] text-muted-foreground`,children:e.children.map(e=>{let i=OJ(e,t,n);return(0,q.jsxs)(rU,{onClick:()=>r(e),current:i,children:[e.icon&&(0,q.jsx)(e.icon,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:e.label})]},e.id)})},e.id):(0,q.jsxs)(`div`,{className:`group relative flex items-center`,children:[(0,q.jsxs)(rU,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:$(`flex-1`,e.disabled&&`opacity-60`),children:[e.icon&&(0,q.jsx)(e.icon,{"data-slot":`icon`}),(0,q.jsx)(iU,{children:e.disabled?`+`:e.label})]}),e.onTogglePin&&(0,q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),e.onTogglePin?.()},title:e.pinned?`Unpin from sidebar`:`Pin to sidebar`,"aria-label":e.pinned?`Unpin ${e.label}`:`Pin ${e.label}`,className:`opacity-0 group-hover:opacity-100 focus-visible:opacity-100 p-1 max-lg:min-h-11 max-lg:min-w-11 flex items-center justify-center text-muted-foreground hover:text-foreground transition-opacity`,children:(0,q.jsx)(iee,{className:`size-3.5`})})]},e.id)})})}function AJ({navSpec:e}){let{tree:t,navState:n,dispatch:r}=NV(),i=SJ(e),a=(t??[]).find(e=>e?.id===n.activeL1Id)??null;return(0,q.jsxs)(QH,{"aria-label":a?`${a.label} places`:`Workspace`,children:[(0,q.jsx)($H,{children:(0,q.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:a?.label??`Wod Wiki`})}),(0,q.jsxs)(eU,{children:[(()=>{if(!a)return null;if(a.panel){let e=a.panel;return(0,q.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,q.jsx)(e,{item:a,navState:n,dispatch:r})})}return a.children&&a.children.length>0?(0,q.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,q.jsx)(kJ,{items:a.children})}):null})(),i.length>0&&(0,q.jsx)(`div`,{className:`pt-1`,children:(0,q.jsx)(TJ,{entries:i})})]})]})}var jJ=`0.63.2267`,MJ={version:jJ,gitSha:`9fcef3fca515`,builtAt:`2026-11-24T03:58:34.541Z`},NJ=`https://github.com/bitcobblers/wod-wiki/releases`;function PJ(e){return/-pr\.\d+$/.test(e)?NJ:`${NJ}/tag/v${e}`}function FJ({onSearch:e,onCreate:t,variant:n=`rail`}){let{tree:r,navState:i,dispatch:a}=NV(),o=dt(),s=Qe(),c=ZH(),l={navigate:(e,t)=>{o(e,{replace:t?.replace})},setQueryParam:()=>{},scrollToSection:()=>{}},u=n===`mobile-list`,d=(r??[]).find(e=>e?.id===`home`),f=d?OJ(d,i,s):s.pathname===`/`||s.pathname===``,p=(r??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`home`&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),m=s.pathname.startsWith(`/settings/profile`),h=s.pathname.startsWith(`/settings`),g=`pointer-events-none absolute left-full top-1/2 -translate-y-1/2 z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,_=e=>$(`flex w-full min-h-11 items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[13px] transition-colors`,e?`bg-primary/10 font-semibold text-primary`:`font-medium text-muted-foreground hover:bg-muted/60 hover:text-foreground`);return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a({type:`SET_ACTIVE_L1`,id:`home`}),o(`/`)},title:`Wod Wiki home`,"aria-label":`Wod Wiki home`,"aria-current":f?`page`:void 0,"data-testid":Q.NAV_L1_HOME,className:u?$(_(f),`mb-1.5 shrink-0`):$(`group relative mb-3 grid size-9 shrink-0 place-items-center rounded-lg transition-colors`,f?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&f&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(Mq,{size:u?24:32,className:$(`shrink-0 shadow-sm shadow-black/15`,u?`size-6 rounded-[6px]`:`size-8 rounded-[8px]`)}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Home`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Wod Wiki home`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Wod Wiki home`})]})]}),(0,q.jsx)(`nav`,{"aria-label":`Primary`,className:u?`flex w-full flex-col gap-0.5`:`flex w-full flex-col items-center gap-1.5`,children:p.map(e=>{let t=e.icon,n=OJ(e,i,s);return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{let t=!!(e.panel||e.children&&e.children.length>0);(!u||!t||n)&&c(),a({type:`SET_ACTIVE_L1`,id:e.id}),AG(e.action,l)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,"data-testid":`nav-l1-${e.id}`,className:u?_(n):$(`group 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:[!u&&n&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(t,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:e.label}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:e.label})]})]},e.id)})}),(0,q.jsx)(`div`,{className:`flex-1 min-h-2`}),(0,q.jsxs)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,"data-testid":Q.NAV_L1_SEARCH,className:u?_(!1):`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,q.jsx)(hi,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Search`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Search`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Search (⌘/)`})]})]}),(0,q.jsxs)(`a`,{href:HK,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:u?_(!1):`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,q.jsx)(UK,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Buy Me a Coffee`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Buy Me a Coffee`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Buy Me a Coffee`})]})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),o(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":m?`page`:void 0,"data-testid":`nav-profile`,className:u?$(_(m),`mt-0.5`):$(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,m?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&m&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(Zt,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Profile`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Profile`}),(0,q.jsx)(`span`,{role:`tooltip`,className:g,children:`Profile`})]})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{c(),o(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":h?`page`:void 0,"data-testid":`nav-settings`,className:u?$(_(h),`mt-0.5`):$(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,h?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[!u&&h&&(0,q.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,q.jsx)(ui,{className:u?`size-4 shrink-0`:`size-5`}),u?(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Settings`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`span`,{className:`sr-only`,children:`Settings`}),(0,q.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 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`Settings (v`,jJ,`)`]})]})]})]})}function IJ({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,q.jsx)(`nav`,{className:$(`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,q.jsx)(`button`,{onClick:()=>AG(e.action,r),className:$(`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 LJ=class e{now;name=`tick`;timestamp;data;static _counter=0;constructor(t,n=of){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this.data=t}},RJ=20,zJ=e=>{let[t,n]=(0,K.useState)(`idle`),[r,i]=(0,K.useState)(0),[a,o]=(0,K.useState)(0),[s,c]=(0,K.useState)(null),l=(0,K.useRef)(null),u=(0,K.useRef)(`idle`),d=(0,K.useRef)(0),f=(0,K.useRef)(null),p=(0,K.useRef)(!1),m=(0,K.useCallback)(()=>e?.nowProvider?.nowMs()??of.nowMs(),[e]),h=(0,K.useCallback)(()=>e?.nowProvider?.now()??of.now(),[e]),g=(0,K.useCallback)(()=>u.current===`running`&&f.current!==null?d.current+Math.max(0,m()-f.current):d.current,[m]),_=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null);let e=g();d.current=e,f.current=null,u.current=`idle`,i(e),n(`idle`)},[g]),v=(0,K.useCallback)(()=>{if(e)try{let t=new LJ(void 0,e.nowProvider);e.handle(t),o(e=>e+1)}catch{_(),u.current=`error`,n(`error`)}},[e,_]);(0,K.useEffect)(()=>{if(e)return e.subscribeToStack(e=>{if(e.blocks.length===0&&u.current!==`completed`){l.current&&=(clearInterval(l.current),null);let e=g();d.current=e,f.current=null,u.current=`completed`,i(e),n(`completed`)}})},[e,g]),(0,K.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]);let y=(0,K.useCallback)(()=>{if(!e){console.warn(`useRuntimeExecution: Cannot start execution without a runtime`);return}if(u.current===`running`){console.warn(`useRuntimeExecution: Runtime is already running`);return}u.current===`paused`&&e.handle({name:`timer:resume`,timestamp:h(),data:{}});let t=m();f.current=t,p.current||(p.current=!0,c(t)),u.current=`running`,n(`running`),l.current=setInterval(v,RJ)},[e,h,m,v]),b=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null);let t=g();d.current=t,f.current=null,i(t),e&&e.handle({name:`timer:pause`,timestamp:h(),data:{}}),u.current=`paused`,n(`paused`)},[e,g,h]),x=(0,K.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),d.current=0,f.current=null,p.current=!1,u.current=`idle`,i(0),o(0),n(`idle`),c(null)},[]),S=(0,K.useCallback)(()=>{!e||u.current===`running`||(u.current=`paused`,n(`paused`),v())},[e,v]);return(0,K.useEffect)(()=>{if(t!==`running`)return;let e=setInterval(()=>{i(g())},100);return()=>clearInterval(e)},[t,g]),(0,K.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]),(0,K.useEffect)(()=>{x()},[e,x]),(0,K.useMemo)(()=>({status:t,elapsedTime:r,getElapsedTime:g,stepCount:a,startTime:s,start:y,pause:b,stop:_,reset:x,step:S}),[t,r,g,a,s,y,b,_,x,S])};function BJ(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,K.useState)(r);return(0,K.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 VJ(e){return BJ(e,`round`)}function HJ(e){return BJ(e,`display`)}function UJ(e){let t=VJ(e),n=HJ(e);return(0,K.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 WJ=(0,K.createContext)(void 0),GJ=({runtime:e,children:t})=>(0,q.jsx)(WJ.Provider,{value:e,children:t});function KJ(){let e=(0,K.useContext)(WJ);if(!e)throw Error(`useScriptRuntime must be used within ScriptRuntimeProvider`);return e}function qJ(){return(0,K.useContext)(WJ)??null}function JJ(e){let t=KJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(()=>n?.getOutputStatements?.()??[]);return(0,K.useEffect)(()=>{if(!n){i([]);return}return i(n.getOutputStatements()),n.subscribeToOutput?.(()=>{i(n.getOutputStatements())})},[n]),(0,K.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 YJ(){let e=KJ(),[t,n]=(0,K.useState)({type:`initial`,blocks:e.stack.blocks,depth:e.stack.count,clockTime:e.clock.currentDate});return(0,K.useEffect)(()=>e.subscribeToStack(e=>{n(e)}),[e]),t}function XJ(){return YJ().blocks}function ZJ(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.useMemo)(()=>{for(let t of e){let e=t.getMemoryByTag(`metric:next`);if(e.length===0)continue;let n=Qo.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 QJ(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.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 $J(){let e=XJ(),[t,n]=(0,K.useState)(0);return(0,K.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,K.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 eY(e){let t=KJ(),n=(0,K.useMemo)(()=>t.stack.blocks.find(t=>t.key.toString()===e),[t,e]),[r,i]=(0,K.useState)(()=>n?.getMemoryByTag(`time`)[0]?.metrics[0]?.value);(0,K.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,K.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,K.useMemo)(()=>r?.spans??[],[r]),o=a.length>0&&a[a.length-1].ended===void 0,[s,c]=(0,K.useState)(Of()),l=(0,K.useMemo)(()=>a.length===0?0:oh(a,s),[a,s]);return(0,K.useEffect)(()=>{if(!o)return;let e,t=()=>{c(Of()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[o]),{elapsed:l,isRunning:o,timeSpans:a}}function tY(e={}){let t=qJ(),n=e.runtime===void 0?t:e.runtime,r=e.active??!0,[i,a]=(0,K.useState)({revision:0,skipFlash:!1,skipFlashKey:0});(0,K.useEffect)(()=>{if(!(!n||!r))return fh(n,({skipFlash:e,skipFlashKey:t})=>{a(n=>({revision:n.revision+1,skipFlash:e,skipFlashKey:t}))})},[n,r]);let[o,s]=(0,K.useState)(()=>Of()),c=(0,K.useMemo)(()=>(i.revision,gh(n,{nowMs:o,executionStatus:e.executionStatus,canNextOverride:e.canNextOverride,skipFlash:i.skipFlash,skipFlashKey:i.skipFlashKey})),[n,i.revision,i.skipFlash,i.skipFlashKey,o,e.executionStatus,e.canNextOverride]);return(0,K.useEffect)(()=>{if(!r||!c.isRunning||c.isPaused||typeof requestAnimationFrame!=`function`)return;let e=0,t=!0,n=()=>{t&&(s(Of()),e=requestAnimationFrame(n))};return e=requestAnimationFrame(n),()=>{t=!1,cancelAnimationFrame(e)}},[r,c.isRunning,c.isPaused]),c}function nY(e){let t=qJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(0);return(0,K.useEffect)(()=>{if(!n){i(0);return}return n.subscribeToOutput?.(()=>{i(e=>e+1)})},[n]),(0,K.useMemo)(()=>Ch(n),[n,r])}function rY(e){let t=qJ(),n=e===void 0?t:e,[r,i]=(0,K.useState)(0);return(0,K.useEffect)(()=>{if(!n)return;let e=n.subscribeToStack(()=>i(e=>e+1)),t=n.subscribeToOutput?.(()=>i(e=>e+1));return()=>{e(),t?.()}},[n]),(0,K.useMemo)(()=>Eh(n),[n,r])}var iY=(0,K.createContext)(void 0),aY=(0,K.createContext)(null),oY=({factory:e,children:t})=>{let[n,r]=(0,K.useState)(null),[i,a]=(0,K.useState)(null),[o,s]=(0,K.useState)(!1),[c,l]=(0,K.useState)(null),u=(0,K.useRef)(e);u.current=e;let d=(0,K.useRef)(null),f=(0,K.useRef)(null),p=(0,K.useRef)(!1),m=(0,K.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),Bz.getState().setSubscriptionManager(null),Bz.getState().setRuntime(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,K.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 ah(i);e.add(new ih({id:`local`})),f.current=e,a(e),Bz.getState().setRuntime(i),Bz.getState().setSubscriptionManager(e)}else f.current=null,a(null),Bz.getState().setRuntime(null),Bz.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,K.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,q.jsx)(iY.Provider,{value:g,children:(0,q.jsx)(aY.Provider,{value:i,children:t})})};function sY({factory:e,children:t}){return(0,q.jsx)(oY,{factory:e,children:t})}var cY=`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`,lY=`flex flex-col flex-1 min-w-0 min-h-screen lg:rounded-[2.5rem]`,uY=1023;function dY(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function fY(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);if(r===null)return null;let i=t[r],{meta:a,body:o}=ac(i),s=new Set([`search`,`template`,`route`,`type`,`title`,`description`,`subtitle`,`section`,`order`]);return Object.keys(a).some(e=>!s.has(e.trim().toLowerCase()))?i:o};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i;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(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function pY(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function mY(e){let t=new Map,n=null;for(let r of e)pY(r)&&(n=r),t.set(r.id,n);return t}function hY(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${uY}px)`).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${uY}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function gY(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})}function _Y({onOpen:e}){let t=ZH();return(0,q.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{t(),e()},"data-testid":`query-settings-trigger`,className:`w-full max-lg:min-h-11 justify-start gap-2 rounded-lg text-xs`,children:[(0,q.jsx)(Vi,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate`,children:`Query settings`})]})}var vY=[4,8,16],yY=`sum:totalVolume{}`;function bY(e){let t=Number.parseInt(e??``,10);return vY.includes(t)?t:16}function xY(e={}){let{defaultQuery:t=yY,runOnLanding:n=!1}=e,[r,i]=be(),a=r.get(`q`)??``,o=bY(r.get(`weeks`)),s=a?!!Xg(a).error:!1,[c,l]=(0,K.useState)(()=>a||t),[u,d]=(0,K.useState)(()=>s?a:null),[f,p]=(0,K.useState)(()=>a&&!s?a:n?t:``),m=(0,K.useRef)(c);m.current=c;let h=(0,K.useRef)(f);h.current=f;let g=(0,K.useRef)(r);g.current=r;let _=(0,K.useRef)(!0),v=(0,K.useRef)(a);v.current=a;let y=(0,K.useRef)(a);(0,K.useEffect)(()=>{if(a===y.current||(y.current=a,m.current===a))return;_.current=!0;let e=a?!!Xg(a).error:!1;l(a||t),e?(d(a),p(e=>e||(n?t:``))):(d(null),p(a||(n?t:``)))},[a,t,n]);let b=(0,K.useRef)(t);return(0,K.useEffect)(()=>{t!==b.current&&(b.current=t,!a&&(d(null),l(t),p(n?t:``)))},[t,a,n]),{draft:c,setDraft:(0,K.useCallback)(e=>{if(e!==m.current){if(e.trim().length>0&&!Xg(e).error){d(null);let t=new URLSearchParams(g.current);t.set(`q`,e),i(t,{replace:!_.current}),_.current=!1}l(e)}},[i]),submitted:f,invalidUrlQuery:u,revertDraft:(0,K.useCallback)(()=>{let e=h.current||t;d(null),l(e);let n=new URLSearchParams(g.current);h.current?n.set(`q`,h.current):n.delete(`q`),i(n,{replace:!0}),_.current=!0},[t,i]),submit:(0,K.useCallback)(e=>{let t=e??m.current;if(t.trim().length===0||Xg(t).error)return;if(d(null),_.current&&v.current===t){p(t);return}let n=new URLSearchParams(g.current);n.set(`q`,t),i(n,{replace:!0}),_.current=!0,p(t)},[i]),weeks:o,setWeeks:(0,K.useCallback)(e=>{let t=new URLSearchParams(g.current);t.set(`weeks`,String(e)),i(t,{replace:!0})},[i])}}var SY=4;function CY(e){return!e||e.length===0?!1:e.some(e=>e.kind===`wql`||e.kind!==`section`||CY(e.entries))}function wY(e,t){let n=PV();return!!(CY(e)||n?.l3Items&&n.l3Items.length>0||CY(n?.l3Connections)||n?.l3Actions&&n.l3Actions.length>0||n?.analyticsControls||t)}function TY({controls:e}){let{unit:t,setUnit:n}=fk(),r=e.showRange!==!1,i=e.showUnits!==!1,a=e.weeks!==void 0&&e.onWeeksChange!==void 0;return(0,q.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":Q.L3_ANALYTICS_CONTROLS,children:[e.onOpenQuerySettings&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`This page`}),(0,q.jsx)(_Y,{onOpen:e.onOpenQuerySettings})]}),r&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date range`}),a?(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":Q.L3_RANGE_OPTIONS,children:vY.map(t=>{let n=e.weeks===t;return(0,q.jsxs)(`button`,{type:`button`,"aria-pressed":n,onClick:()=>e.onWeeksChange?.(t),"data-testid":`l3-range-${t}w`,className:$(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 max-lg:min-h-11 text-xs transition-colors`,n?`bg-primary/10 font-semibold text-primary`:`text-foreground/85 hover:bg-muted/60 hover:text-foreground`),children:[(0,q.jsx)(`span`,{className:`w-3.5 text-primary`,children:n?(0,q.jsx)(zr,{className:`size-3.5`,"aria-hidden":`true`}):null}),(0,q.jsxs)(`span`,{children:[`Past `,t,` weeks`]})]},t)})}):(0,q.jsx)(rk,{})]}),i&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:[`Units`,e.unitForced?` — pinned by query`:``]}),(0,q.jsx)(`div`,{className:`grid grid-cols-2 gap-1`,"data-testid":Q.L3_UNIT_OPTIONS,children:[`kg`,`lb`].map(r=>{let i=t===r;return(0,q.jsx)(`button`,{type:`button`,disabled:!!e.unitForced,"aria-pressed":i,onClick:()=>n(r),"data-testid":`l3-unit-${r}`,className:$(`flex min-h-8 max-lg:min-h-11 items-center justify-center rounded-md border px-2 py-1 text-xs font-medium transition-colors`,e.unitForced?`border-transparent text-muted-foreground/75 opacity-70 cursor-not-allowed`:i?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`),children:r},r)})})]})]})}function EY({action:e,variant:t=`default`}){let n=ZH(),r=e.icon;return(0,q.jsxs)(`button`,{type:`button`,disabled:e.disabled,"data-testid":e.testId,onClick:()=>{e.disabled||(n(),e.onRun())},className:$(`flex w-full items-center gap-2 rounded-lg transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`,t===`primary`&&`justify-center bg-primary px-3 py-2 min-h-9 max-lg:min-h-11 text-sm font-semibold text-primary-foreground shadow-sm hover:bg-primary/90`,t==="default"&&`px-2 py-1.5 max-lg:min-h-11 text-left text-[13px] text-foreground/85 hover:bg-muted/60 hover:text-foreground`,t===`danger`&&`px-2 py-1.5 max-lg:min-h-11 text-left text-[13px] font-medium text-destructive hover:bg-destructive/10 hover:text-destructive`,e.disabled&&(t===`primary`?`cursor-not-allowed opacity-50`:t===`danger`?`cursor-not-allowed text-destructive/50 hover:bg-transparent`:`cursor-not-allowed text-muted-foreground/60 hover:bg-transparent`)),children:[r&&(0,q.jsx)(r,{"aria-hidden":`true`,className:`size-4 shrink-0`}),(0,q.jsx)(`span`,{className:$(`min-w-0 truncate`,t!==`primary`&&`flex-1`),title:e.label,children:e.label})]})}function DY({bucket:e}){let t=e.items.length+ +!!e.extraNode;return(0,q.jsxs)(`details`,{"data-testid":e.testId,className:`group rounded-lg border border-border/40 bg-muted/20`,children:[(0,q.jsxs)(`summary`,{className:`flex min-h-9 max-lg:min-h-11 cursor-pointer list-none items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-semibold text-foreground/85 select-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden`,children:[(0,q.jsx)(ee,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 group-open:rotate-90`}),(0,q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}),(0,q.jsx)(`span`,{className:`shrink-0 text-xs font-medium tabular-nums text-muted-foreground`,children:t})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-0.5 px-1 pb-1.5 pt-0.5`,children:[e.items.map(e=>(0,q.jsx)(EY,{action:e},e.id)),e.extraNode&&(0,q.jsx)(`div`,{className:`pt-0.5`,children:e.extraNode})]})]})}function OY({actions:e,pageAction:t}){let n=(0,K.useMemo)(()=>e.filter(e=>e.group===`primary`),[e]),r=(0,K.useMemo)(()=>e.filter(e=>e.group===`author`),[e]),i=(0,K.useMemo)(()=>e.filter(e=>e.group===`organize`||e.group===void 0),[e]),a=(0,K.useMemo)(()=>e.filter(e=>e.group===`share`),[e]),o=(0,K.useMemo)(()=>e.filter(e=>e.group===`danger`),[e]),s=r.length+i.length+a.length,c=s>=SY,l=(0,K.useMemo)(()=>{let e=[];return r.length>0&&e.push({id:`author`,label:`Author`,testId:Q.L3_ACTIONS_GROUP_AUTHOR,items:r}),i.length>0&&e.push({id:`organize`,label:`Organize`,testId:Q.L3_ACTIONS_GROUP_ORGANIZE,items:i}),(a.length>0||c&&t)&&e.push({id:`share`,label:`Share & Export`,testId:Q.L3_ACTIONS_GROUP_SHARE,items:a,extraNode:c?t:void 0}),e},[r,i,a,c,t]);return(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[n.length>0&&(0,q.jsx)(`div`,{"data-testid":Q.L3_ACTIONS_PRIMARY,className:`flex flex-col gap-1.5 pb-1`,children:n.map(e=>(0,q.jsx)(EY,{action:e,variant:`primary`},e.id))}),c?(0,q.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:l.map(e=>(0,q.jsx)(DY,{bucket:e},e.id))}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:[...r,...i,...a].map(e=>(0,q.jsx)(EY,{action:e},e.id))}),t&&(0,q.jsx)(`div`,{className:$(s>0&&`pt-1`),children:t})]}),o.length>0&&(0,q.jsx)(`div`,{"data-testid":Q.L3_ACTIONS_DANGER,className:`mt-1 flex flex-col gap-0.5 border-t border-destructive/25 pt-2`,children:o.map(e=>(0,q.jsx)(EY,{action:e,variant:`danger`},e.id))})]})}function kY({spec:e,pageAction:t}){let{l3Items:n,l3Connections:r,l3Actions:i=[],analyticsControls:a}=NV(),o=SJ(e),s=SJ(r),c=(0,K.useMemo)(()=>gY(n),[n]),l=CJ(),u=!!a,d=CY(o),f=c.length>0,p=CY(s),m=d||f||p,h=i.length>0||!!t;return!u&&!m&&!h?null:(0,q.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[u&&(0,q.jsx)(`div`,{className:$(`flex flex-col gap-4`,(m||h)&&`pb-3 border-b border-border/50`),children:a&&(0,q.jsx)(TY,{controls:a})}),d&&(0,q.jsx)(TJ,{entries:o,activeId:l}),f&&(0,q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,q.jsx)(TJ,{entries:c,activeId:l})]}),p&&(0,q.jsxs)(`div`,{"data-testid":Q.L3_CONNECTIONS,className:$(`flex flex-col gap-1`,(f||d)&&`pt-3 border-t border-border/50`),children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Connections`}),(0,q.jsx)(TJ,{entries:s,activeId:l})]}),h&&(0,q.jsxs)(`div`,{"data-testid":Q.L3_ACTIONS,className:$(`flex flex-col gap-1`,m&&`pt-3 border-t border-border/50`),children:[(0,q.jsx)(`h2`,{className:`px-2 pb-1 pt-1 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Actions`}),(0,q.jsx)(OY,{actions:i,pageAction:t})]})]})}var AY=`(min-width: 1520px)`;function jY(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(AY).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(AY);if(t(e.matches),typeof e.addEventListener!=`function`)return;let n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var MY=(0,K.createContext)(null);function NY({value:e,children:t}){return(0,q.jsx)(MY.Provider,{value:e,children:t})}function PY(){let e=(0,K.useContext)(MY),{dispatch:t,analyticsControls:n,l3Items:r,l3Connections:i,l3Actions:a=[],secondarySpec:o}=NV();return e||{railHasContent:!!(CY(o)||r&&r.length>0||CY(i)||a&&a.length>0||n),hasAppliedFilters:!1,openRightDrawer:()=>t({type:`SET_RIGHT_DRAWER`,open:!0})}}function FY(){let{railHasContent:e,hasAppliedFilters:t,openRightDrawer:n}=PY(),r=jY(),i=hY();return!e||r||i?null:(0,q.jsxs)(J,{type:`button`,variant:`ghost`,size:`icon`,onClick:n,"aria-label":`Page options`,title:`Page options (⌘.)`,"data-testid":`l3-drawer-trigger`,className:`relative hidden lg:inline-flex 2xl:hidden text-muted-foreground hover:text-foreground`,children:[(0,q.jsx)(Vi,{className:`size-4`,"aria-hidden":`true`}),t&&(0,q.jsx)(`span`,{"data-testid":`header-filters-active`,className:`absolute top-1.5 right-1.5 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Page options`})]})}function IY({id:e,parent:t,title:n,subtitle:r,titleAccessory:i,actions:a,queryBar:o,subheader:s,titleTestId:c,className:l}){let{railHasContent:u}=PY(),d=!!(a||u);return(0,q.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:$(`max-lg:hidden lg:sticky lg:top-0 z-30 border-b border-border/50 bg-background/95 backdrop-blur-md transition-colors`,l),children:[(0,q.jsxs)(`div`,{className:$(`sph-row flex min-h-[54px] justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,o?`items-start`:`items-center`),children:[(t||n)&&(0,q.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[t&&(0,q.jsxs)(M,{to:t.to,"data-testid":Q.PAGE_HEADER_PARENT_BREADCRUMB,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 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground shrink-0 no-underline`,children:[(0,q.jsx)(j,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`truncate max-w-[140px]`,children:t.label})]}),n&&(0,q.jsxs)(q.Fragment,{children:[!t&&(0,q.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(`h1`,{"data-testid":c,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:n}),r&&(0,q.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:r})]}),i]})]})]}),o&&(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:o}),d&&(0,q.jsxs)(`div`,{className:`sph-actions flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:[a,(0,q.jsx)(FY,{})]})]}),s&&(0,q.jsx)(`div`,{className:`bg-background/40`,children:s})]})}function LY({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,K.useRef)(``),u=(0,K.useRef)(i),d=(0,K.useRef)(a),f=(0,K.useRef)(null),p=(0,K.useRef)(1);(0,K.useEffect)(()=>{u.current=i},[i]),(0,K.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,K.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,K.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,K.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,K.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 RY({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]=V(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,K.useState)(c?.[0]?.id??``);if(LY({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}),LY({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,q.jsxs)(`div`,{className:$(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,q.jsx)(IJ,{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,q.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,q.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,q.jsx)(sY,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,q.jsx)(`div`,{className:$(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,q.jsxs)(`div`,{className:$(lY,cY),children:[(0,q.jsx)(IY,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,q.jsx)(`div`,{className:`flex-1`,children:i})]})})}var zY=`[data-page-sticky-boundary="true"]`,BY=0;function VY(e,t=BY){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(zY)).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 HY(e,t=BY){let[n,r]=(0,K.useState)(e);return(0,K.useEffect)(()=>{let n=0,i=()=>r(VY(e,t)),a=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(i)};i(),window.addEventListener(`scroll`,a,{passive:!0}),window.addEventListener(`resize`,i);let o=typeof ResizeObserver>`u`?void 0:new ResizeObserver(i);document.querySelectorAll(zY).forEach(e=>o?.observe(e));let s=typeof MutationObserver>`u`?void 0:new MutationObserver(()=>{document.querySelectorAll(zY).forEach(e=>o?.observe(e)),i()});return typeof document<`u`&&document.body&&s?.observe(document.body,{childList:!0,subtree:!0}),()=>{s?.disconnect(),o?.disconnect(),cancelAnimationFrame(n),window.removeEventListener(`scroll`,a),window.removeEventListener(`resize`,i)}},[e,t]),n}function UY({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,q.jsxs)(`div`,{"data-testid":a,className:$(`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,q.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,q.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var WY=(0,K.createContext)(null),GY=(0,K.createContext)(null);function KY({children:e}){let[t,n]=(0,K.useState)(null);return(0,q.jsx)(GY.Provider,{value:n,children:(0,q.jsx)(WY.Provider,{value:t,children:e})})}function qY({className:e}){let t=(0,K.useContext)(GY);return(0,q.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function JY(){return(0,K.useContext)(WY)}function YY({editor:e,parent:t,title:n,subtitle:r,titleAccessory:i,titleTestId:a,actions:o,timerOverlay:s,reviewOverlay:c,isTimerOpen:l=!1,isReviewOpen:u=!1,onCloseTimer:d,onCloseReview:f,className:p}){return(0,q.jsxs)(`div`,{className:$(`relative flex w-full min-h-screen justify-start items-start`,p),children:[(0,q.jsxs)(`div`,{className:$(lY,cY),children:[(0,q.jsx)(IY,{parent:t,title:n,subtitle:r,titleAccessory:i,titleTestId:a,actions:o}),(0,q.jsx)(`div`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),l&&s&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,q.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,q.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,q.jsx)(`button`,{onClick:d,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,q.jsx)(`div`,{className:`flex-1 min-h-0`,children:s})]})}),u&&c&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,q.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,q.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,q.jsx)(`button`,{onClick:f,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,q.jsx)(`div`,{className:`flex-1 min-h-0`,children:c})]})})]})}var XY=`wodwiki:fabAlignment`,ZY=[{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 QY(){try{return $Y(localStorage.getItem(XY))}catch{return}}function $Y(e){return e===`right`||e===`left`?e:void 0}var eX=typeof window>`u`?void 0:QY();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===XY&&(eX=$Y(e.newValue))});function tX(e){eX=e;try{e===`right`?localStorage.removeItem(XY):localStorage.setItem(XY,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:XY,newValue:e}))}function nX(){let[e,t]=(0,K.useState)(()=>eX??`right`);return(0,K.useEffect)(()=>{let e=e=>{e.key===XY&&t($Y(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,tX]}function rX({onOpen:e}){return(0,q.jsxs)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,title:`Search`,"data-testid":`search-fab`,className:$(`size-12 rounded-full flex items-center justify-center`,`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:[(0,q.jsx)(hi,{className:`size-6`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Search`})]})}var iX=(0,K.createContext)(null),aX=(0,K.createContext)(!1),oX=(0,K.createContext)(null),sX=(0,K.createContext)(null);function cX(){return(0,K.useContext)(iX)!==null}function lX({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,K.useContext)(iX),o=(0,K.useContext)(aX),s=hY(),c=(0,K.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=K.Children.toArray(n).length>0,f=(0,K.useMemo)(()=>(0,q.jsx)(aX.Provider,{value:!0,children:n}),[n]),p=l||u,m=(0,K.useRef)(null);return m.current={id:c,primary:e,navbar:t,children:f,hasContent:d,label:r??`Page options`,fallback:i},(0,K.useEffect)(()=>{if(p)return a.register(m.current),()=>a.unregister(c)},[p,a,c]),(0,K.useEffect)(()=>{p&&a.register(m.current)},[p,a,e,t,f,d,r,i]),i||a&&s&&!o?null:(0,q.jsx)(aX.Provider,{value:!0,children:(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function uX({onSearch:e,renderDock:t=!0,secondarySpec:n,pageAction:r,children:i}){let[a,o]=(0,K.useState)([]),s=(0,K.useCallback)(e=>o(t=>{let n=t.findIndex(t=>t.id===e.id);if(n===-1)return[...t,e];let r=t[n];if(r.primary===e.primary&&r.navbar===e.navbar&&r.children===e.children&&r.hasContent===e.hasContent&&r.label===e.label&&r.fallback===e.fallback)return t;let i=[...t];return i[n]=e,i}),[]),c=(0,K.useCallback)(e=>o(t=>t.filter(t=>t.id!==e)),[]),l=(0,K.useMemo)(()=>({register:s,unregister:c}),[s,c]),u=(0,K.useMemo)(()=>{for(let e=a.length-1;e>=0;--e)if(!a[e].fallback)return a[e].navbar??null;return null},[a]),d=(0,K.useMemo)(()=>({registrations:a,onSearch:e,secondarySpec:n,pageAction:r}),[a,e,n,r]);return(0,q.jsx)(iX.Provider,{value:l,children:(0,q.jsx)(oX.Provider,{value:u,children:(0,q.jsxs)(sX.Provider,{value:d,children:[i,t&&(0,q.jsx)(mX,{registrations:a,onSearch:e,secondarySpec:n,pageAction:r})]})})})}function dX(){let e=(0,K.useContext)(sX);return e?(0,q.jsx)(mX,{registrations:e.registrations,onSearch:e.onSearch,secondarySpec:e.secondarySpec,pageAction:e.pageAction}):null}function fX(){let e=(0,K.useContext)(oX);return e?(0,q.jsx)(q.Fragment,{children:e}):null}function pX(e){return`[data-testid="${e}"]`}function mX({registrations:e,onSearch:t,secondarySpec:n,pageAction:r}){let i=hY(),[a]=nX(),o=Wj(),s=PV(),c=wY(n,r),l=!!s?.navState?.rightDrawerOpen,u=!!(s?.navState?.inspectorDrawerOpen||s?.peekTarget),d=s?.dispatch,f=s?.analyticsControls?.onReset,[p,m]=(0,K.useState)(!1),[g,_]=(0,K.useState)(!1),v=p||l,y=(0,K.useCallback)(()=>{m(!1),l&&d?.({type:`SET_RIGHT_DRAWER`,open:!1})},[l,d]),b=(0,K.useCallback)(()=>{v?y():m(!0)},[v,y]),x=(0,K.useId)(),S=(0,K.useRef)(null),C=(0,K.useRef)(null),w=(0,K.useRef)(null),T=(0,K.useRef)(null),E=(0,K.useRef)(v);E.current=v;let D=(0,K.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),O=(0,K.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]),k=(0,K.useCallback)(()=>{if(typeof document>`u`||!i){_(e=>e&&!1);return}if(u){m(e=>e&&!1),_(e=>e||!0);return}if(document.querySelector(`${pX(Q.MOBILE_WHEEL_COMPOSER)}, ${pX(Q.MOBILE_TYPING_BAR)}`)){m(e=>e&&!1),_(e=>e||!0);return}let e=window.visualViewport;if(e&&window.innerHeight-(e.height+e.offsetTop)>100){m(e=>e&&!1),_(e=>e||!0);return}let t=document.querySelector(pX(Q.RESULTS_MOBILE_BAR));if(t&&!t.hidden){let e=window.getComputedStyle(t);if(e.display!==`none`&&e.visibility!==`hidden`){m(e=>e&&!1),_(e=>e||!0);return}}if(!E.current&&S.current){let e=S.current.getBoundingClientRect();if(e.width>0&&e.height>0){let t=document.querySelectorAll(`.cm-frontmatter-preview input`);for(let n of t){let t=n.getBoundingClientRect();if(t.width<=4||t.height<=4||t.bottom<=0||t.top>=window.innerHeight||t.right<=0||t.left>=window.innerWidth)continue;let r=window.getComputedStyle(n);if(r.display!==`none`&&r.visibility!==`hidden`&&t.left<e.right+4&&e.left-4<t.right&&t.top<e.bottom+4&&e.top-4<t.bottom){_(e=>e||!0);return}}}}_(e=>e&&!1)},[i,u]);(0,K.useLayoutEffect)(()=>{k()},[k,a,v,D,O,t,o.height,c]),(0,K.useEffect)(()=>{if(!i||typeof document>`u`||!document.body)return;k();let e=new MutationObserver(e=>{S.current&&e.every(e=>S.current.contains(e.target))||k()});e.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`hidden`,`style`,`class`]});let t=new MutationObserver(()=>{k()});t.observe(document.documentElement,{attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`scroll`,k,{passive:!0,capture:!0}),window.addEventListener(`resize`,k,{passive:!0});let n=window.visualViewport;return n?.addEventListener(`resize`,k),n?.addEventListener(`scroll`,k),()=>{e.disconnect(),t.disconnect(),window.removeEventListener(`scroll`,k,{capture:!0}),window.removeEventListener(`resize`,k),n?.removeEventListener(`resize`,k),n?.removeEventListener(`scroll`,k)}},[i,k]),(0,K.useLayoutEffect)(()=>{v&&C.current?.focus({preventScroll:!0})},[v]);let A=!!(D?.hasContent||O?.hasContent||c),j=D?.hasContent?D.label:O?.hasContent?O.label:`Page options`;if(!i||!t&&!D&&!O&&!c)return null;let M=o.height===null?`100dvh`:`${o.height}px`;return(0,q.jsxs)(`div`,{ref:S,"data-testid":Q.ACTIONS_DOCK,"aria-hidden":g||void 0,className:$(`fixed z-40 lg:hidden flex flex-col gap-2 w-auto`,`transition-opacity duration-150 ease-out`,a===`left`?`left-4 items-start`:`right-4 items-end`,g&&`invisible pointer-events-none`),style:{bottom:`calc(1rem + var(--thumb-dock-lift, 0px) + env(safe-area-inset-bottom, 0px))`,maxHeight:`calc(${M} - 2rem - var(--thumb-dock-lift, 0px) - env(safe-area-inset-bottom, 0px))`},children:[v&&A&&(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 bg-black/20 dark:bg-black/35 cursor-default`,onClick:y}),(0,q.jsx)(`div`,{id:x,ref:C,role:v&&A?`dialog`:void 0,"aria-modal":v&&A?!0:void 0,"aria-label":v&&A?j:void 0,tabIndex:-1,hidden:!v||!A,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),y())},className:$(v&&A?`flex`:`hidden`,`relative z-40 min-h-0 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/10 outline-none`,c?`w-72`:`w-60`,`[&_button]:min-h-11 [&_button]:min-w-11 [&_summary]:min-h-11`),style:{maxHeight:`calc(${M} - 8rem - var(--thumb-dock-lift, 0px) - env(safe-area-inset-bottom, 0px))`},children:(0,q.jsxs)(XH,{close:y,children:[c&&(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/50 pb-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground truncate`,children:j}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[f&&(0,q.jsx)(`button`,{type:`button`,onClick:f,"data-testid":Q.L3_DRAWER_RESET_BTN,className:`inline-flex min-h-11 items-center justify-center rounded-lg px-2.5 text-xs font-medium text-muted-foreground hover:bg-muted/60 hover:text-foreground transition-colors`,children:`Reset`}),(0,q.jsx)(`button`,{type:`button`,onClick:y,"data-testid":Q.L3_DRAWER_DONE_BTN,className:`inline-flex min-h-11 items-center justify-center rounded-lg bg-primary/10 px-3 text-xs font-semibold text-primary hover:bg-primary/15 transition-colors`,children:`Done`})]})]}),D?.hasContent&&(0,q.jsx)(`div`,{ref:w,className:`contents`,children:D.children}),v&&c&&(0,q.jsxs)(q.Fragment,{children:[D?.hasContent&&(0,q.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,q.jsx)(`div`,{"data-testid":Q.ACTIONS_SHEET_L3,className:`-mx-3 -my-2 flex flex-col`,children:(0,q.jsx)(kY,{spec:n,pageAction:r})})]}),O?.hasContent&&(0,q.jsxs)(q.Fragment,{children:[(D?.hasContent||c)&&(0,q.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,q.jsx)(`div`,{ref:T,className:`contents`,children:O.children})]})]})}),(t||D?.primary)&&(0,q.jsxs)(`div`,{className:$(`relative z-40 flex shrink-0 flex-col gap-2`,a===`left`?`items-start`:`items-end`),children:[t&&(0,q.jsx)(rX,{onOpen:()=>{y(),t()}}),D?.primary&&(0,q.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:D.primary})]}),A&&(0,q.jsxs)(`button`,{type:`button`,onClick:b,"aria-label":j,title:j,"aria-expanded":v,"aria-controls":x,"data-testid":Q.ACTIONS_OVERFLOW,className:$(`relative z-40 flex size-12 shrink-0 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:[v?(0,q.jsx)(h,{className:`size-6`}):(0,q.jsx)(hn,{className:`size-6`}),(0,q.jsx)(`span`,{className:`sr-only`,children:j})]})]})}var hX=null,gX=new Set;function _X(e){hX=e;for(let e of gX)e();return()=>{if(hX===e){hX=null;for(let e of gX)e()}}}function vX(){return hX}function yX(e){return gX.add(e),()=>{gX.delete(e)}}function bX(){return(0,K.useSyncExternalStore)(yX,vX,()=>null)}var xX=null,SX=new Set;function CX(e){xX=e;for(let e of SX)e();return()=>{if(xX===e){xX=null;for(let e of SX)e()}}}function wX(){return xX}function TX(e){return SX.add(e),()=>{SX.delete(e)}}function EX(){return(0,K.useSyncExternalStore)(TX,wX,()=>null)}var DX=null,OX=new Set;function kX(e){DX=e;for(let e of OX)e();return()=>{if(DX===e){DX=null;for(let e of OX)e()}}}function AX(){return DX}function jX(e){return OX.add(e),()=>{OX.delete(e)}}function MX(){return(0,K.useSyncExternalStore)(jX,AX,()=>null)}var NX=null,PX=new Set;function FX(e){NX=e;for(let e of PX)e();return()=>{if(NX===e){NX=null;for(let e of PX)e()}}}function IX(){return NX}function LX(e){return PX.add(e),()=>{PX.delete(e)}}function RX(){return(0,K.useSyncExternalStore)(LX,IX,()=>null)}var zX=[],BX=null,VX=null,HX=null,UX=new Set;function WX(){let e=zX.length>0?zX[zX.length-1]:null;if(!e&&!BX&&!VX)HX=null;else{let t=BX,n=VX;HX={getTarget:()=>(e?e.getTarget():t)??null,openPeek:t=>{if(e)e.openPeek(t);else throw Error(`No Entity Peek host is registered to open new targets.`)},closePeek:()=>{n?.(),e?.closePeek()}}}for(let e of UX)e()}function GX(e){return zX.push(e),WX(),()=>{let t=zX.lastIndexOf(e);t!==-1&&(zX.splice(t,1),WX())}}function KX(e,t){return BX=e,VX=e?t:null,WX(),()=>{BX===e&&(BX=null,VX=null,WX())}}function qX(){return HX}function JX(e){return UX.add(e),()=>{UX.delete(e)}}function YX(){return(0,K.useSyncExternalStore)(JX,qX,()=>null)}var XX=0,ZX=new Set;function QX(e){if(!e)return()=>{};XX+=1;for(let e of ZX)e();let t=!1;return()=>{if(!t){t=!0,XX=Math.max(0,XX-1);for(let e of ZX)e()}}}function $X(){return XX>0}function eZ(e){return ZX.add(e),()=>{ZX.delete(e)}}function tZ(){return(0,K.useSyncExternalStore)(eZ,$X,()=>!1)}function nZ(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 e.phase}}function rZ(e){if(!e||e.phase===`checking`||e.phase===`finished`)return null;let t=[];return typeof e.completedRecords==`number`&&typeof e.totalRecords==`number`&&t.push(`${e.completedRecords} / ${e.totalRecords} records`),e.totalChunks>0&&t.push(`${e.completedChunks} / ${e.totalChunks} notebooks`),t.length>0?t.join(` · `):null}var iZ=[`samples-movement`,`samples-results`],aZ=`wodwiki.seedSubscriptions`,oZ=`wodwiki.seedAutoSync`;function sZ(e){try{let t=typeof localStorage<`u`?localStorage.getItem(e):null;if(!t)return new Set;let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?new Set:new Set(Object.keys(n))}catch{return new Set}}function cZ(e){let t=new Set(e.map(e=>e.id)),n=QF()??{},r=new Set([...sZ(aZ),...Object.keys(n)]),i=new Set([...sZ(oZ),...Object.keys(tI()??{}),...Object.entries(n).filter(([,e])=>e.autoSync!==void 0).map(([e])=>e)]),a=rI()??{},o=[];for(let e of iZ)t.has(e)&&(r.has(e)||(VI(e,!0),!a[e]&&!n[e]?.offlinePolicy&&XI(e,`index-only`),o.push(e)),i.has(e)||JI(e,!0));return o}var lZ=`idle`,uZ=null,dZ=!1,fZ=0,pZ=null,mZ=!1,hZ=new Set,gZ=null,_Z=null;function vZ(){for(let e of hZ)e()}function yZ(e){typeof document>`u`||(document.documentElement.dataset.feedState=e)}function bZ(e){typeof document>`u`||(e===null?delete document.documentElement.dataset.feedOutcome:document.documentElement.dataset.feedOutcome=e)}function xZ(e){typeof document>`u`||(e?document.documentElement.dataset.feedImportPending=`true`:delete document.documentElement.dataset.feedImportPending)}yZ(lZ);function SZ(e){lZ!==e&&(lZ=e,yZ(e),vZ())}function CZ(e){if(dZ===e)return;let t=dZ||fZ>0;dZ=e;let n=dZ||fZ>0;xZ(n),t!==n&&vZ()}function wZ(e){let t=dZ||fZ>0;fZ+=1,e!==void 0&&(pZ=e),xZ(dZ||fZ>0),(!t||e!==void 0)&&vZ()}function TZ(){if(fZ===0)return;let e=dZ||fZ>0;fZ=Math.max(0,fZ-1),fZ===0&&(pZ=null);let t=dZ||fZ>0;xZ(t),(e!==t||fZ===0)&&vZ()}function EZ(){return pZ}function DZ(){return(0,K.useSyncExternalStore)(LZ,EZ)}function OZ(){gZ&&=(clearTimeout(gZ),null),_Z&&=(_Z.close(),null)}function kZ(e){uZ=e,vZ()}function AZ(){OZ(),bZ(null);let e=uZ!==null,t=!dZ;if(uZ=null,dZ=!0,xZ(!0),lZ===`preparing`){(e||t)&&vZ();return}SZ(`preparing`)}function jZ(){lZ===`preparing`&&!dZ&&fZ===0&&SZ(`ready`)}function MZ(e){let t=lZ,n=dZ||fZ>0;dZ=!1,lZ=e;let r=dZ||fZ>0;xZ(r),yZ(e),(t!==e||n!==r)&&vZ()}function NZ(e){switch(bZ(e),e){case`busy`:if(lZ!==`preparing`&&!dZ)return;typeof BroadcastChannel<`u`&&!_Z&&(_Z=new BroadcastChannel(mx),_Z.onmessage=e=>{e.data?.kind===`seed-imported`&&(OZ(),mZ=!1,MZ(`ready`))}),gZ=setTimeout(()=>{aV({onProgress:kZ}).then(NZ)},IB);break;case`error`:OZ(),mZ?SZ(`error`):MZ(`error`);break;default:if(OZ(),mZ)return;MZ(`ready`)}}function PZ(){return lZ===`idle`?`ready`:lZ}function FZ(){return dZ||fZ>0}function IZ(){return uZ}function LZ(e){return hZ.add(e),()=>hZ.delete(e)}function RZ(){return(0,K.useSyncExternalStore)(LZ,PZ)}function zZ(){return(0,K.useSyncExternalStore)(LZ,FZ)}function BZ(){return(0,K.useSyncExternalStore)(LZ,IZ)}var VZ=null;function HZ(e={}){return FE(`feedStart`),(e.isEnabled??VB)()&&CZ(!0),VZ??=WZ(e).finally(()=>{FE(`feedSettled`)}),VZ}async function UZ(e,t){for(let n of e)if(!(n.id===`core`||!BI(n.id)||!qI(n.id)))try{let e=await t.getSeedMeta(bx(n.id));if(!e||e.seedVersion<=0)return!0}catch{return!0}return!1}async function WZ(e){let t=t=>{kZ(t),e.onProgress?.(t)},n=e.storage??NI();n.storageInstance&&await ZF(n.storageInstance).catch(e=>console.error(`[feedSync] registry hydration failed`,e));let r=e.sources??HB();await vV(e).catch(e=>console.error(`[feedSync] notebook vocabulary migration failed`,e)),await gV(e).catch(e=>console.error(`[feedSync] checkpoint adoption failed`,e)),await Mue(r,n).catch(e=>console.error(`[feedSync] subscription migration failed`,e)),cZ(r);let i;try{i=await n.getSeedMeta(bx(`core`))}catch{i=void 0}let a=(e.isEnabled??VB)(),o=!i||i.seedVersion<=0,s=!o&&await UZ(r,n);if(a&&(o||s)?(mZ=!0,AZ()):NZ(`current`),await _V(e).catch(e=>console.error(`[feedSync] feed provenance repair failed`,e)),o){try{let n=await aV({...e,sources:r,onProgress:t,onFirstPaint:()=>jZ()});n!==`busy`&&n!==`error`&&r.some(e=>e.id!==`core`&&BI(e.id))&&await aV({...e,sources:r.filter(e=>e.id!==`core`),onProgress:t}).catch(e=>console.error(`[feedSync] background boot sync failed`,e)),mZ=!1,NZ(n)}finally{mZ&&(mZ=!1,CZ(!1))}return}let c=`current`;try{c=await aV({...e,sources:r,onProgress:t}).catch(e=>(console.error(`[feedSync] background boot sync failed`,e),`error`))}finally{mZ&&(mZ=!1,NZ(c===`error`?`current`:c))}}function GZ(){let[e,t]=(0,K.useState)(null);return(0,K.useEffect)(()=>{let e=!1,n=()=>{pV().then(n=>{e||t(!n.libraryImported)}).catch(()=>{e||t(!0)})};n();let r=DE(()=>n()),i=$B(()=>n()),a=null;if(typeof BroadcastChannel<`u`)try{a=new BroadcastChannel(mx),a.onmessage=()=>n()}catch{}return()=>{e=!0,r(),i(),a?.close()}},[]),e}var KZ=`(min-width: 1520px)`;function qZ(){let[e,t]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(KZ).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(KZ);if(t(e.matches),typeof e.addEventListener!=`function`)return;let n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function JZ(){return(0,q.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,q.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 YZ(){return(0,q.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,q.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 XZ({open:e,close:t,onSearch:n,children:r}){let i=(0,K.useRef)(null);return(0,q.jsxs)(Fr,{side:`start`,open:e,onOpenChange:e=>{e||t()},children:[(0,q.jsx)(We,{className:`bg-black/30 dark:bg-black/30 transition-none data-[closed]:hidden lg:hidden`}),(0,q.jsxs)(lt,{initialFocus:()=>i.current,"data-testid":Q.MOBILE_NAV_DRAWER,className:`w-full max-w-none h-dvh max-h-dvh p-0 gap-0 rounded-none border-0 bg-card transition-none data-[closed]:hidden lg:hidden`,children:[(0,q.jsx)(ve,{className:`sr-only`,children:`Navigation`}),(0,q.jsx)(XH,{close:t,children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,q.jsx)(`div`,{className:`flex h-full w-[156px] sm:w-44 shrink-0 flex-col overflow-y-auto border-r border-zinc-950/5 bg-background/72 px-2 py-3 dark:border-white/5`,children:(0,q.jsx)(FJ,{variant:`mobile-list`,onSearch:()=>{t(),n?.()}})}),(0,q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-end px-3 pt-3`,children:(0,q.jsx)(Xe,{render:(0,q.jsx)(jq,{"aria-label":`Close navigation`,title:`Close navigation`,"data-testid":Q.MOBILE_NAV_CLOSE}),children:(0,q.jsx)(YZ,{})})}),(0,q.jsx)(`div`,{ref:i,tabIndex:-1,className:`flex min-h-0 flex-1 flex-col outline-none`,children:r})]})]})})]})]})}function ZZ({open:e,close:t,showControlsFooter:n=!1,onReset:r,children:i}){let a=(0,K.useRef)(null);return(0,q.jsxs)(Fr,{side:`end`,open:e,onOpenChange:e=>{e||t()},children:[(0,q.jsx)(We,{className:`bg-black/25 dark:bg-black/40 transition-none data-[closed]:hidden 2xl:hidden`}),(0,q.jsx)(lt,{initialFocus:()=>a.current,"data-testid":Q.L3_RIGHT_DRAWER,"aria-label":`Page options panel`,className:`w-full lg:w-80 max-w-none h-dvh max-h-dvh p-0 gap-0 rounded-none border-0 lg:border-l lg:border-border/60 bg-card lg:shadow-2xl flex flex-col transition-none data-[closed]:hidden 2xl:hidden`,children:(0,q.jsxs)(XH,{close:t,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border/40 px-4 py-2.5`,children:[(0,q.jsx)(ve,{className:`text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Page options`}),(0,q.jsx)(Xe,{render:(0,q.jsx)(jq,{"aria-label":`Close page options`,title:`Close page options`}),children:(0,q.jsx)(YZ,{})})]}),(0,q.jsx)(`div`,{ref:a,tabIndex:-1,className:`flex min-h-0 flex-1 flex-col overflow-y-auto outline-none`,children:i}),n&&(0,q.jsxs)(`div`,{className:`shrink-0 flex items-center gap-2 border-t border-border/50 bg-card p-3`,children:[r&&(0,q.jsx)(`button`,{type:`button`,onClick:r,"data-testid":Q.L3_DRAWER_RESET_BTN,className:`h-10 max-lg:h-11 flex-1 rounded-lg border border-border bg-background px-3 text-sm font-medium text-foreground hover:bg-muted transition-colors`,children:`Reset`}),(0,q.jsx)(`button`,{type:`button`,onClick:t,"data-testid":Q.L3_DRAWER_DONE_BTN,className:`h-10 max-lg:h-11 flex-1 rounded-lg bg-primary px-3 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Done`})]})]})})]})}function QZ({navbar:e,sidebar:t,onSearch:n,secondary:r,pageAction:i,peekSlot:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,K.useState)(!1),u=qZ(),d=hY(),{navState:f,dispatch:p,peekTarget:m,closePeek:h,analyticsControls:g}=NV(),_=Qe().pathname===`/`||!!o,v=!!f?.rightDrawerOpen,y=!!(f?.inspectorDrawerOpen||m),b=!!(m&&a),x=(0,K.useCallback)(e=>p({type:`SET_RIGHT_DRAWER`,open:e}),[p]),S=(0,K.useCallback)(()=>x(!0),[x]),C=(0,K.useCallback)(()=>x(!1),[x]),w=wY(r,i),T=(0,K.useMemo)(()=>({railHasContent:w,hasAppliedFilters:!1,openRightDrawer:S}),[w,S]);(0,K.useEffect)(()=>{if(!c&&!v&&!m)return;let e=()=>{l(!1),x(!1),h?.()};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[c,v,m,x,h]),(0,K.useEffect)(()=>{if(!w)return;let e=e=>{if(!e.defaultPrevented&&(e.metaKey||e.ctrlKey)&&e.key===`.`&&!e.shiftKey&&!e.altKey){if(window.innerWidth>=1520)return;e.preventDefault(),x(!v)}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[w,v,x]),(0,K.useEffect)(()=>{if(!b)return;let e=e=>{e.defaultPrevented||e.key===`Escape`&&(e.preventDefault(),h?.())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[b,h]);let E=u&&w&&!y,D=!u&&!d&&v;return(0,q.jsx)(NY,{value:T,children:(0,q.jsx)(KY,{children:(0,q.jsx)(uX,{onSearch:n,renderDock:!1,secondarySpec:r,pageAction:i,children:(0,q.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,q.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,q.jsxs)(`div`,{"data-shell-nav":`desktop`,className:`hidden lg:flex`,children:[(0,q.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,q.jsx)(FJ,{onSearch:n??(()=>{})})}),(0,q.jsx)(`div`,{className:$(`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,q.jsx)(XZ,{open:c,close:()=>l(!1),onSearch:n,children:t}),(0,q.jsxs)(`div`,{className:$(`flex flex-1 flex-col min-w-0 2xl:max-w-none`,_||y?`xl:max-w-none`:`xl:max-w-[984px]`),children:[(0,q.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,q.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,q.jsxs)(jq,{onClick:()=>l(!0),"aria-label":`Open navigation`,title:`Open navigation`,"data-testid":Q.MOBILE_NAV_OPEN,children:[(0,q.jsx)(JZ,{}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Open navigation`})]})}),(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:e})]}),(0,q.jsxs)($Z,{children:[(0,q.jsx)(`div`,{className:`grow w-full max-lg:pb-[calc(12rem+var(--thumb-dock-lift,0px)+env(safe-area-inset-bottom,0px))] lg:overflow-visible`,children:s}),(0,q.jsx)(tQ,{}),(0,q.jsx)(dX,{})]})]}),E&&(0,q.jsx)(`aside`,{"aria-label":`Page outline and actions`,"data-testid":Q.L3_INLINE_RAIL,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,q.jsx)(kY,{spec:r,pageAction:i})}),y&&(0,q.jsx)(`div`,{"aria-hidden":`true`,"data-testid":Q.INSPECTOR_DRAWER_RAIL_SPACER,className:`hidden xl:block w-[340px] shrink-0`}),b&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":`Close peek drawer`,"data-testid":Q.PEEK_DRAWER_BACKDROP,onClick:()=>h?.(),className:`xl:hidden fixed inset-0 z-[29] bg-black/25 dark:bg-black/40 cursor-default`}),(0,q.jsx)(`div`,{"data-testid":Q.PEEK_DRAWER_SLOT,className:`fixed right-0 top-0 bottom-0 z-30 flex w-[340px] max-w-[92vw] flex-col overflow-hidden max-xl:shadow-2xl xl:shadow-none`,children:a})]}),D&&(0,q.jsx)(ZZ,{open:v,close:C,showControlsFooter:!!g,onReset:g?.onReset,children:(0,q.jsx)(kY,{spec:r,pageAction:i})})]})})})})})}function $Z({children:e}){let t=Qe(),n=tZ(),r=RZ(),i=zZ(),a=DZ(),o=BZ(),s=n||r===`preparing`||i,c=i&&t.pathname!==`/`,l=c?rZ(o):null;return(0,q.jsxs)(`main`,{"aria-busy":s,"data-agent-status":s?`loading`:`ready`,className:`flex flex-1 flex-col lg:min-w-0`,children:[e,c&&(0,q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"data-testid":Q.BOOT_IMPORT_PROGRESS,className:`pointer-events-none fixed z-30 max-lg:bottom-[calc(0.75rem+var(--thumb-dock-lift,0px)+env(safe-area-inset-bottom,0px))] max-lg:left-3 max-lg:right-auto max-lg:max-w-[calc(100vw-5.5rem)] lg:bottom-4 lg:right-4 lg:left-auto flex items-center gap-2 rounded-lg border border-border bg-card/95 px-3 py-1.5 text-xs text-foreground shadow-sm`,children:[(0,q.jsx)(`span`,{className:`truncate`,children:a??(o?nZ(o):`Importing library…`)}),l&&(0,q.jsx)(`span`,{className:`text-muted-foreground shrink-0`,children:l})]})]})}var eQ=17;function tQ(){let e=(0,K.useRef)(null),[t,n]=(0,K.useState)(0);(0,K.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()},[]);let r=t>0?t+eQ:0;return(0,K.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${r}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[r]),(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:$(`lg:hidden fixed inset-x-0 bottom-0 z-30`,r>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,q.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,q.jsx)(qY,{className:`flex w-full min-w-0`})})}),(0,q.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:r}})]})}function nQ(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function rQ(e){return String(lc(ac(e).meta,`search`)??``).toLowerCase()===`hidden`}function iQ(e){let t=lc(ac(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 aQ(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=lc(ac(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():wP(r),category:nQ(n),content:i,date:iQ(i),searchHidden:rQ(i)}})}function oQ(){let e=HP();return(0,K.useMemo)(()=>e?aQ(e):[],[e])}var sQ={};function cQ(e,t){let{canvasPage:n,workoutItems:r,selectWorkout:i}=t;if(e===`/`)return[];if(n){let t=/^\/notebook\//.test(e),a=t?e.split(`/`).pop()??null:null,o=[],s=e.startsWith(`/page/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=$K(e).split(`
|
|
813
813
|
`),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&&a&&(o.push({id:`notebook-workouts`,label:`Explore`,type:`heading`}),r.filter(e=>e.category===a&&e.name.toLowerCase()!==`readme`).forEach(e=>{o.push({id:`workout-${e.id}`,label:e.name,type:`time`,onRun:()=>i(e),runIcon:`link`})})),o}return[]}var lQ=/^[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 uQ(e){return lQ.test(e)}function dQ(e){try{return decodeURIComponent(e)}catch{return null}}function fQ(e){if(!gU(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 pQ(e){let t=(e.length>1?e.replace(/\/+$/,``):e).match(/^\/day\/([^/]+)$/);if(!t)return{kind:`invalid`};let n=dQ(t[1]);return n!=null&&fQ(n)?{kind:`date`,date:n}:{kind:`invalid`}}var mQ=`# My Workout Notebook
|
|
814
814
|
|
|
815
815
|
Welcome to the **WOD.WIKI** playground.
|
|
@@ -857,15 +857,15 @@ Timer 12:00
|
|
|
857
857
|
`),r=Math.min(Math.max(0,t),n.length-1),i=!1,a=!1,o;for(let e=0;e<=r;e++){let r=(n[e]??``).trim();if(e===0&&r===`---`){i=!0;continue}if(i){r===`---`&&(i=!1);continue}if(r.startsWith("```")){if(e===t)break;a=!a;continue}if(a)continue;let s=x0(r);s&&(o=s)}return o}function _pe(e){if(!e||!e.trimStart().startsWith(`---`))return;let{meta:t}=ac(e);return typeof t.title==`string`&&t.title.trim()?t.title.trim():void 0}function vpe(e){for(let t of e.split(`
|
|
858
858
|
`)){let e=t.trim();if(e)return x0(e)}}function S0(e,t){let n;for(let r of e){if(t&&r.id===t)break;if(r.type===`header`){let e=r.content.replace(/^#{1,6}\s+/,``).trim();e&&(n=e)}}return n}function C0(e,t){let n=e.label?.trim(),r=t?gpe(t,e.startLine):void 0,i=_pe(t),a=vpe(e.content),o=n||r||i||a||void 0,s=Th({statements:e.statements??nu({tags:Sz()}).read(e.content,e.sport).statements});return{...o?{workoutTitle:o}:{},...s?{workoutFormat:s}:{}}}function ype(){let e=$1();return e?t0(e.runId,{kind:`stop-request`}):!1}function bpe(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:Nc(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:Nc(Math.round(e.elapsed*1e3))})})}return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:n,completedSegments:e.length,rows:r}}}function xpe(e){return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:e.totalDurationMs,completedSegments:e.segmentCount,rows:[{label:`Total Time`,value:Nc(e.totalDurationMs)},{label:`Segments`,value:String(e.segmentCount)}]}}}function Spe(e,t){let n=t.filter(e=>e.type===`time`||e.type===`log`);if(n.length===0&&!e)return{type:`rpc-workbench-update`,mode:`idle`};let r=e?n.find(t=>t.scriptBlock?.id===e.id)??n[0]:n[0],i=(e?.content??r?.content??``).split(`
|
|
859
859
|
`)[0]?.trim().substring(0,60);return{type:`rpc-workbench-update`,mode:`preview`,previewData:{title:e?.label?.trim()||S0(t,r?.id)||i||`Workout`,blocks:n.slice(0,8).map(e=>({id:e.id,title:S0(t,e.id)||(e.scriptBlock?.content??e.content).split(`
|
|
860
|
-
`)[0]?.trim().substring(0,50)||`Workout`,statementCount:e.scriptBlock?.statements?.length??0}))}}}var w0=`wod-wiki:userOutputOverrides`;function Cpe(e=!1){let t=Bz(e=>e.userOutputOverrides),n=Bz(e=>e.setUserOverride),r=Bz(e=>e.clearUserOverride);return(0,K.useEffect)(()=>{if(e)try{let e=localStorage.getItem(w0);if(!e)return;let t=JSON.parse(e);for(let[e,r]of Object.entries(t))n(e,r.map(Tpe))}catch{}},[e,n]),(0,K.useEffect)(()=>{if(!e)return;if(t.size===0){localStorage.removeItem(w0);return}let n={};for(let[e,r]of t)n[e]=r.map(wpe);localStorage.setItem(w0,JSON.stringify(n))},[t,e]),{overrides:t,setOverride:(0,K.useCallback)((e,r,i,a)=>{let o=(t.get(e)??Qo.empty(e)).filter(e=>e.type!==r),s={type:r,origin:`user`,value:i,image:a??String(i??``)};n(e,Qo.from(o,e).add(s))},[t,n]),removeOverride:(0,K.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,K.useCallback)(e=>{r(e)},[r]),clearAll:(0,K.useCallback)(()=>{for(let e of t.keys())r(e)},[t,r])}}function wpe(e){let t=e.timestamp instanceof Date?e.timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp);return{type:e.type,value:e.value,image:e.image,origin:e.origin,sourceBlockKey:e.sourceBlockKey,timestamp:t&&!Number.isNaN(t.getTime())?t.toISOString():void 0}}function Tpe(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 Epe=(typeof window<`u`?window.__wod_runtimeNowProvider?.():void 0)??of,Dpe=new Vm(rh(),Epe),T0=new WeakSet;function E0(e){let t=Kz(e),n=t&&t.tags.length>0?t.tagIndex:Sz(),r=t?qz(t):void 0,i=nu({tags:n,...r?{references:r}:{}}),a={...e,statements:i.read(e.content,e.sport).statements};return T0.add(a),t&&Gz(a,t),a}function Ope(e){if(!e||!e.trimStart().startsWith(`---`))return[];let{meta:t}=ac(e),n=Nre(t,`note`,`note-frontmatter`);return Object.keys(n.metrics??{}).length>0||Object.keys(n.summaries??{}).length>0||Object.keys(n.widgets??{}).length>0?[n]:[]}var kpe=[`tags`,`category`,`domain`,`format`,`equipment`,`quality`,`intent`,`discipline`,`intensity`,`sound`];function D0(e,t={}){let n=t.tags??Sz(),r=[],i=[];if(e&&e.trimStart().startsWith(`---`)){r.push(...Ope(e));let t=pc(e,[...kpe]);for(let e of t){let t=e.label.trim();t&&n.resolve(t)&&!i.includes(t)&&i.push(t)}}let a=Mp(n,i);return{activeTags:i,propertySources:r,dashboardWidgets:Ire([...r,...a],{scopeFilter:t.scopeFilter??(t.noteId?zb({noteId:t.noteId,rawContent:e}).scopeFilter:void 0)})}}function Ape(e,t){let n=Kz(e),r=n&&n.tags.length>0?n.tagIndex:Sz(),{activeTags:i,propertySources:a}=D0(t,{tags:r}),o=n?(()=>{let e=new Zd;return e.seed(Xd),e.seed(n.efforts),new Jd(e)})():void 0,s=n?qz(n):void 0,c={analyticsOptions:{tags:r,activeTags:i,propertySources:a,...o?{effortResolver:o}:{},...s?{references:s}:{}}},l=T0.has(e)&&e.statements?e:E0(e);return Dpe.createRuntime(l,c)??null}function O0(e,t){return{startTime:t.startTime??t.now.nowMs(),endTime:t.now.nowMs(),duration:t.elapsedTime,completed:t.completed,logs:e.map(Qw)}}function jpe(e){return e.filter(e=>e.outputType===`segment`).length}function Mpe(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 k0(e){let t=e.kind===`choice`?Y.Choice:String(e.metricType),n=e.kind===`value`&&e.sourceStatementId!==void 0?`:${e.sourceStatementId}`:``;return`${e.blockKey}:${t}${n}`}var Npe={[Y.Rep]:!0,[Y.Rounds]:!0,[Y.RIR]:!0,[Y.SessionRPE]:!0,[Y.Lap]:!0},Ppe={[Y.Duration]:!0},Fpe={[Y.Choice]:!0};function Ipe(e){let t=String(e);return Npe[t]?`integer`:Ppe[t]?`duration`:Fpe[t]?`choice`:`decimal`}function A0(e,t,n){return e.kind===`choice`?{fieldId:k0(e),label:e.exerciseLabel,metricType:Y.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:k0(e),label:e.exerciseLabel,metricType:String(e.metricType),domain:Ipe(e.metricType),intent:e.intent,required:e.intent===`target`,value:null,unit:e.unit??``,index:t,total:n}}function Lpe(e,t,n){let r=e?.statements[t.statementIndex];r&&zm(r,t.alternatives,n)}function Rpe(e,t){if(e.type===Y.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===Y.Distance||e.type===Y.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 zpe(e,t,n,r){if(r!==`target`||!Number.isFinite(n))return!1;if(t.kind===`choice`)return!Number.isInteger(n)||n<0?!1:(Lpe(e,t,n),!0);if(M0[String(t.metricType)]&&n<=0||t.metricType===Y.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(Rpe(a,n))):i.metrics.add({type:t.metricType,origin:`user-plan`,value:n,image:String(n)}),!0}function j0(e){if(!(`context`in e))return;let t=e.context;if(!(!t||typeof t!=`object`))return t}function Bpe(e){let t=j0(e)?.sourceBlockKey;return typeof t==`string`&&t.length>0?t:void 0}var M0={[Y.Duration]:!0,[Y.Rounds]:!0};function N0(e){return!M0[String(e)]}function Vpe(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===Y.Effort||e.type===Y.Label),c=s?.value?.toString()||s?.image||`Exercise`;for(let t of i.metrics){if(t.type===Y.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:N0(t.type)})}}}return r}for(let n of e){if(!n.metrics)continue;let e=Bpe(n);if(!e)continue;let i=j0(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`&&!M0[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===Y.Effort||e.type===Y.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:N0(t.type)})}}}return r}function P0(e,t,n){let r=(0,K.useMemo)(()=>Vpe(e,t,n),[e,t,n]);return{collectionItems:r,totalCount:r.length,isComplete:r.length===0}}function F0(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 I0(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 L0=(e,t)=>e?e(t):{},R0=({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,K.useState)(u??``),m=l??f,h=e=>{p(e),c?.(e)},[g,_]=(0,K.useState)(null),[v,y]=(0,K.useState)(e.selectedIndex??0),b=(0,K.useRef)(!1),x=(0,K.useRef)(null);(0,K.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`?F0(e,v):p0(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.nativeEvent.isComposing||e.keyCode===229||e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.repeat||w())},E=t=>{_(null),h(f0(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=g0(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=I0(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,K.useEffect)(()=>{y(e.selectedIndex??0)},[e.selectedIndex]),(0,q.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,q.jsx)(`div`,{className:`flex w-full flex-col gap-3`,role:`radiogroup`,"aria-label":e.label,children:S.map((e,t)=>(0,q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":v===t,"data-testid":`entry-choice-${t}`,onClick:()=>{y(t),_(null),s?.(t)},...L0(d,`entry-choice-${t}`),className:$(`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,q.jsxs)(`div`,{className:`flex items-center justify-center gap-2`,onKeyDown:T,children:[(0,q.jsx)(`input`,{"data-testid":`entry-min`,"aria-label":`Minutes`,inputMode:`numeric`,value:I0(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,q.jsx)(`span`,{className:`text-3xl font-bold text-muted-foreground`,children:`:`}),(0,q.jsx)(`input`,{"data-testid":`entry-sec`,"aria-label":`Seconds`,inputMode:`numeric`,value:I0(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,q.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,q.jsx)(`p`,{role:`alert`,className:`text-sm font-medium text-destructive`,children:C}),A&&(0,q.jsxs)(`div`,{className:`grid w-full max-w-[260px] grid-cols-3 gap-2`,"aria-label":`Number pad`,children:[j.map(e=>(0,q.jsx)(`button`,{type:`button`,"data-testid":e.id,onClick:()=>E(e.key),...L0(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,q.jsx)(`button`,{type:`button`,"data-testid":`entry-clear`,onClick:()=>E(`clear`),...L0(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,q.jsxs)(`div`,{className:`flex w-full items-center justify-between gap-3`,children:[(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-cancel`,onClick:i,...L0(d,`entry-cancel`),className:`min-h-11 min-w-11 px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:`Cancel`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[a&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-skip`,onClick:a,...L0(d,`entry-skip`),className:`min-h-11 min-w-11 px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:o??`Skip`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-save`,onClick:w,disabled:t,...L0(d,`entry-save`),className:`flex min-h-11 min-w-11 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`})]})]})]})},z0=({items:e,onSave:t,onSkip:n,onStart:r,onClose:i,mode:a,runId:o,className:s})=>{let[c,l]=(0,K.useState)(new Set),[u,d]=(0,K.useState)(new Set),[f,p]=(0,K.useState)(0),[m,h]=(0,K.useState)({}),[g,_]=(0,K.useState)({}),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(!1),w=(0,K.useRef)(!1),T=(0,K.useRef)(!1);e.length>0&&(T.current=!0);let E=G1(),D=(0,K.useMemo)(()=>e.filter(e=>!c.has(k0(e))),[e,c]),O=Math.min(f,Math.max(D.length-1,0)),k=D[O],A=k?k0(k):null,M=a===`pre-run`&&D.length===0&&T.current;(0,K.useEffect)(()=>{A&&typeof E==`string`&&h(e=>e[A]===E?e:{...e,[A]:E})},[E,A]);let N=(0,K.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}),u0(``)},[]),P=(0,K.useCallback)((e,t)=>{h(n=>({...n,[e]:t})),u0(t)},[]),F=(0,K.useCallback)(async(n,r)=>{if(w.current)return!1;let i=k0(n),a=F0(A0(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 N(i),l(e=>new Set(e).add(i)),!0},[t,e.length,N]),I=(0,K.useCallback)(()=>{if(!k||w.current)return;let e=k0(k);a===`pre-run`&&!k.deferrable||(N(e),a===`post-run`&&n&&n(k),d(t=>new Set(t).add(e)),l(t=>new Set(t).add(e)))},[k,a,n,N]),L=(0,K.useCallback)(e=>{switch(e.kind){case`entry-save`:return!k||w.current||e.fieldId!==k0(k)?!1:(F(k,e.value),!0);case`entry-cancel`:return k?(P(k0(k),``),x(null),!0):!1;case`entry-skip`:return!k||w.current||e.fieldId!==k0(k)?!1:(I(),!0);case`choice-select`:return!k||k.kind!==`choice`||e.fieldId!==k0(k)||!Number.isInteger(e.index)||e.index<0||e.index>=k.alternatives.length?!1:(_(t=>({...t,[k0(k)]:e.index})),x(null),!0);case`ready-start`:return M?(r?.(),!0):!1;case`dismiss`:return a===`pre-run`&&!M?!1:(C(!0),i?.(),!0);default:return!1}},[k,F,I,M,r,i,a,P]);W1((0,K.useMemo)(()=>{if(D.length===0)return M&&!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?A0(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,M,S]),L,a===`pre-run`?10:20,{keyboard:!0});let R=(0,K.useCallback)(()=>{a===`pre-run`&&!M||(C(!0),i?.())},[a,M,i]);if(D.length===0)return M&&!S?(0,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:`Ready to Start`}),(0,q.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,q.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,q.jsx)(ee,{className:`w-5 h-5`})]})]}):null;if(!k)return null;let z=A0(k,O,D.length),B=k.kind===`choice`?g[z.fieldId]??0:0,V=a===`post-run`||k.deferrable;return(0,q.jsxs)(`div`,{className:$(`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,q.jsx)(`div`,{className:`h-1 bg-muted`,children:(0,q.jsx)(`div`,{className:`h-full bg-primary transition-all duration-300`,style:{width:`${(e.length-D.length+1)/(e.length+1)*100}%`}})}),(0,q.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-muted/10 px-6 py-4`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:a===`pre-run`?`Set Your Targets`:`Fill in your actuals`}),(0,q.jsxs)(`p`,{className:`text-xs uppercase tracking-label text-muted-foreground`,children:[e.length-D.length+1,` of `,e.length,` metrics`]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[O>0&&(0,q.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,q.jsx)(j,{className:`w-4 h-4`}),`Back`]}),i&&a===`post-run`&&(0,q.jsx)(`button`,{type:`button`,onClick:R,className:`rounded-full p-2 transition-colors hover:bg-muted`,children:(0,q.jsx)(ze,{className:`w-5 h-5 text-muted-foreground`})})]})]}),(0,q.jsx)(`div`,{className:`flex flex-1 flex-col items-center justify-center w-full max-w-md mx-auto p-8`,children:(0,q.jsxs)(`div`,{className:`w-full space-y-6`,children:[(0,q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,q.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,q.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,q.jsx)(R0,{entry:k.kind===`choice`?{...z,selectedIndex:B}:z,saving:v,error:b,onSave:e=>void F(k,e),onCancel:()=>{P(z.fieldId,``),x(null)},onSkip:V?I:void 0,skipLabel:a===`pre-run`?`Log after workout`:`Skip`,onChoice:k.kind===`choice`?e=>_(t=>({...t,[z.fieldId]:e})):void 0,onDraftChange:e=>P(z.fieldId,e),initialDraft:m[z.fieldId]??``},z.fieldId)]})}),b&&(0,q.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,q.jsx)($i,{className:`h-4 w-4`}),(0,q.jsxs)(`span`,{role:`alert`,children:[b,` — your entry is kept.`]})]})]})};function Hpe(e){let t=[];for(let n of e)n.origin===`user`&&n.type===Y.Rep&&typeof n.value==`number`&&t.push(n);return t}function B0(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 V0(e,t,n){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Actual rep count must be a nonnegative safe integer, got ${t}`);let r=B0(e,n,!0),i={type:Y.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 Cf(`metric:result`,n===r?[i]:[]));return}e.pushMemory(new Cf(`metric:result`,[i]));return}let o=a[Math.min(r,a.length-1)],s=o.metrics.filter(e=>e.origin!==`user`||e.type!==Y.Rep);o.update([...s,i])}function H0(e,t){let n=e.getMemoryByTag(`metric:result`);if(n.length===0)return null;let r=B0(e,t,!1);if(r===-1)return null;r=Math.min(r,n.length-1);let i=Hpe(n[r].metrics),a=i[i.length-1];return a?a.value:null}var Upe=new Set([`Rounds`,`Group`,`AMRAP`,`EMOM`,`SessionRoot`,`Root`]),Wpe=new Set([`Timer`]);function Gpe(e){let t=[];for(let n of e.stack.blocks){if(n.isComplete)continue;let e=n.blockType??``;if(Upe.has(e)||Wpe.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=Kpe(e);if(!(o!==null||e.metrics.some(e=>(e.type===Y.Effort||e.type===Y.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:qpe(n,e),target:o})}}return t}function Kpe(e){let t=null,n=null;for(let r of e.metrics)r.type===Y.Rep&&r.origin!==`user`&&typeof r.value==`number`&&(r.origin===`parser`?t=r.value:n=r.value);return n??t}function qpe(e,t){if(e.getMemoryByTag(`metric:display`).length<=1)return e.label;for(let e of t.metrics)if((e.type===Y.Effort||e.type===Y.Action)&&typeof e.value==`string`&&e.value)return e.value;return e.label}function U0(e,t){for(let n of e.stack.blocks){if(n.isComplete)continue;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 Jpe({runtime:e,executionStatus:t,actions:n,enabled:r=!0,saving:i=!1,hasCapturedWork:a=!1}){let o=(0,K.useRef)(Zfe()),[s,c]=(0,K.useState)(0),[l,u]=(0,K.useState)(0),[d,f]=(0,K.useState)(!1),[p,m]=(0,K.useState)(null),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(null),y=(0,K.useRef)({runtime:e,executionStatus:t,actions:n,hasCapturedWork:a});y.current={runtime:e,executionStatus:t,actions:n,hasCapturedWork:a},(0,K.useEffect)(()=>{if(e)return e.subscribeToStack(()=>c(e=>e+1))},[e]);let b=(0,K.useMemo)(()=>e?Gpe(e).map(t=>{let n=U0(e,t.occurrenceId);return{occurrenceId:t.occurrenceId,label:t.label,target:t.target,actual:n?H0(n.block,n.occurrence):null}}):[],[e,s,l]),x=t===`completed`?null:b.length===1?b[0].occurrenceId:p!==null&&b.some(e=>e.occurrenceId===p)?p:null;(0,K.useEffect)(()=>{m(x)},[x]),(0,K.useEffect)(()=>{b.length>0&&v(e=>e===`No rep movements`||e===`No rep movements to record`?null:e)},[b]);let S=h,C=e?.stack.current?.blockType===`WaitingToStart`,w=t,T=w===`completed`?`review`:C||w===`idle`&&!e?`ready`:`live`,E=w===`running`||w===`idle`,D=w===`running`||w===`paused`||a,O=(0,K.useMemo)(()=>!r||!e?null:{runId:o.current,phase:T,status:w,canNext:E,canStop:D,stopRequested:d,reps:b,selectedOccurrenceId:x,entry:S,error:_,saving:i},[r,e,T,w,E,D,d,b,x,S,_,i]);return W1(O,(0,K.useCallback)(e=>{let t=y.current.runtime,n=y.current.executionStatus,r=y.current.actions;if(h!==null&&[`next`,`ready-start`,`playback`,`stop-request`,`reps-select`].includes(e.kind))return!1;let i=e=>t!==null&&e!==null?U0(t,e):void 0,a=e=>{let t=b.find(t=>t.occurrenceId===e);return t?(g({fieldId:`reps:${t.occurrenceId}`,label:t.label,metricType:`reps`,domain:`integer`,intent:`actual`,required:!1,value:t.actual,unit:`reps`,index:0,total:1}),v(null),!0):(v(`Movement no longer active`),!1)};switch(e.kind){case`next`:return d?!1:n===`paused`?(v(`Paused — press play to continue first`),!1):n!==`running`&&n!==`idle`?!1:(r.next(),!0);case`ready-start`:return d||n!==`idle`?!1:(r.start(),!0);case`playback`:return d||n===`completed`?!1:(v(null),r.playback(),!0);case`stop-request`:{let e=n===`running`||n===`paused`||y.current.hasCapturedWork;return d||h!==null||!e?!1:(f(!0),!0)}case`stop-cancel`:return d?(f(!1),!0):!1;case`stop-confirm`:return d?(f(!1),r.stop(),!0):!1;case`values-open`:{if(h!==null||d)return!1;let e=x;return e===null?(v(b.length>1?`Select a movement first`:`No rep movements to record`),!1):a(e)}case`entry-cancel`:return h!==null&&(g(null),v(null),!0);case`entry-save`:{if(h===null||e.fieldId!==h.fieldId)return!1;if(!Number.isSafeInteger(e.value)||e.value<0)return v(`Reps must be a whole number of 0 or more`),!1;let t=i(h.fieldId.slice(5));return t?(V0(t.block,e.value,t.occurrence),u(e=>e+1),g(null),v(null),!0):(v(`Movement no longer active — draft preserved`),!1)}case`entry-skip`:return h===null||e.fieldId!==h.fieldId?!1:(g(null),v(null),!0);case`reps-adjust`:{if(h!==null||d)return!1;if(n===`completed`||T===`review`)return v(`Workout completed — rep controls are inactive`),!1;let t=e.occurrenceId===``?x:e.occurrenceId;if(t===null)return v(b.length>1?`Select a movement first`:`No rep movements`),!1;let r=i(t);if(!r)return v(`Movement no longer active`),!1;let a=(H0(r.block,r.occurrence)??0)+e.delta;return a<0||(V0(r.block,a,r.occurrence),u(e=>e+1),v(null),!0)}case`reps-set`:{if(h!==null||d)return!1;if(n===`completed`||T===`review`)return v(`Workout completed — rep controls are inactive`),!1;if(!Number.isSafeInteger(e.value)||e.value<0)return v(`Reps must be a whole number of 0 or more`),!1;let t=e.occurrenceId===``?x:e.occurrenceId;if(t===null)return v(b.length>1?`Select a movement first`:`No rep movements`),!1;let r=i(t);return r?(V0(r.block,e.value,r.occurrence),u(e=>e+1),v(null),!0):(v(`Movement no longer active`),!1)}case`reps-select`:return d||!b.some(t=>t.occurrenceId===e.occurrenceId)?!1:(m(e.occurrenceId),v(null),!0);case`choice-select`:return!1;case`dismiss`:return r.dismiss?(r.dismiss(),!0):!1}},[b,p,x,T,h,d]),0,{keyboard:!0}),{snapshot:O,dispatch:(0,K.useCallback)(e=>t0(o.current,e),[])}}var Ype=`Enter Select · Numpad Enter Next · 8/2/4/6 Move · +/- Reps · * Values · / Play · Esc Stop`,Xpe=`Enter Next · Numpad Enter Next · 8/2/4/6 Move · +/- Reps · * Values · / Play · Esc Stop`;function Zpe({mode:e,className:t}){return(0,q.jsx)(`p`,{"data-testid":Q.CLOCK_LEGEND,className:`hidden sm:block px-3 text-[10px] leading-4 text-muted-foreground ${t??``}`,children:e===`keypad`?Xpe:Ype})}var Qpe=({mode:e,onModeChange:t,className:n,getFocusProps:r})=>{let[i,a]=(0,K.useState)(()=>h0()),o=e??i,s=e=>{ipe(e),a(e),t?.(e)};return(0,q.jsx)(`div`,{"data-testid":Q.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,q.jsx)(`button`,{type:`button`,"aria-pressed":o===e,onClick:()=>s(e),...r?.(`board-keymode-${e}`),className:`min-h-11 min-w-11 rounded-full px-3 py-2 text-xs font-medium ${o===e?`bg-foreground text-background`:`text-muted-foreground hover:text-foreground`}`,children:e===`navigation`?`Nav`:`Keypad`},e))})},$pe=({open:e,onClose:t,getFocusProps:n})=>{let[r,i]=(0,K.useState)([]),a=(0,K.useRef)(null);return(0,K.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,K.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,q.jsx)(`div`,{className:`fixed inset-0 z-[140] flex items-center justify-center bg-black/60 p-4`,children:(0,q.jsxs)(`div`,{"data-testid":Q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`Key check`}),(0,q.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,q.jsxs)(`table`,{className:`mt-3 w-full font-mono text-[11px]`,children:[(0,q.jsx)(`thead`,{children:(0,q.jsxs)(`tr`,{className:`text-left text-muted-foreground`,children:[(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`key`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`code`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`loc`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`keyCode`}),(0,q.jsx)(`th`,{className:`font-medium`,children:`repeat`})]})}),(0,q.jsx)(`tbody`,{children:r.map((e,t)=>(0,q.jsxs)(`tr`,{className:`border-t border-border/60`,children:[(0,q.jsx)(`td`,{className:`pr-2`,children:e.key}),(0,q.jsx)(`td`,{className:`pr-2`,children:e.code}),(0,q.jsx)(`td`,{className:`pr-2`,children:e.location}),(0,q.jsxs)(`td`,{className:`pr-2`,children:[e.keyCode,`×`,e.count]}),(0,q.jsx)(`td`,{children:e.repeat?`yes`:`no`})]},t))})]}),(0,q.jsx)(`div`,{className:`mt-3 flex justify-end`,children:(0,q.jsx)(`button`,{type:`button`,ref:a,onClick:t,...n?.(`board-keycheck-close`),className:`min-h-11 min-w-11 rounded-md border border-border px-3 py-2 text-xs font-medium hover:bg-accent`,children:`Close`})})]})}):null},eme=({snapshot:e,dispatch:t,className:n,getFocusProps:r})=>{let i=G1(),a=Jfe(),[o,s]=(0,K.useState)(()=>h0()),[c,l]=(0,K.useState)(!1),u=e=>r?.(e),d=e.entry,f=(0,K.useRef)(d?.fieldId??null);K.useLayoutEffect(()=>{let e=d?.fieldId??null;r&&f.current!==e&&u0(``),f.current=e},[d?.fieldId,r]);let p=e.error??a,m=e.status===`completed`||e.phase===`review`,h=m?null:e.reps.find(t=>t.occurrenceId===e.selectedOccurrenceId)??null,g=e.phase===`live`&&!m&&e.selectedOccurrenceId!==null&&h!==null,_=e.reps.length>0&&(e.phase===`live`||e.phase===`collection`);return(0,q.jsxs)(`div`,{"data-testid":Q.CLOCK_COMMAND_BOARD,className:n,children:[p!==null&&(0,q.jsx)(`p`,{"data-testid":Q.CLOCK_ERROR,role:`status`,className:`px-3 pt-1 text-xs text-destructive`,children:p}),r&&e.phase===`ready`&&d===null&&(0,q.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`}),_&&(0,q.jsxs)(`div`,{"data-testid":Q.CLOCK_REP_COUNTER,className:`flex flex-wrap items-center gap-2 px-3 py-1.5 text-sm`,children:[(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Actual reps`}),(0,q.jsx)(`span`,{"data-testid":Q.CLOCK_REP_VALUE,className:`font-mono text-sm font-semibold`,children:m?`Complete`:`${h?.actual??`—`}${h?.target==null?``:` / Target ${h.target}`}`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_REP_MINUS,"aria-label":`Remove one rep`,title:`Subtract one rep`,disabled:!g,"aria-disabled":!g,className:`h-11 w-11 min-h-11 min-w-11 rounded-full border border-border text-base font-semibold hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-reps-minus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:-1}),children:`−`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_REP_PLUS,"aria-label":`Add one rep`,title:`Add one rep`,disabled:!g,"aria-disabled":!g,className:`h-11 w-11 min-h-11 min-w-11 rounded-full border border-border text-base font-semibold hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-reps-plus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:1}),children:`+`}),i!==``&&d===null&&(0,q.jsxs)(`span`,{"data-testid":Q.CLOCK_DRAFT_CHIP,className:`rounded bg-muted px-1.5 py-0.5 font-mono text-xs`,children:[i,` `,(0,q.jsx)(`span`,{className:`text-muted-foreground`,children:`⏎ to set`})]}),e.reps.length>1&&(0,q.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,role:`group`,"aria-label":`Counted movement`,children:e.reps.map(n=>(0,q.jsx)(`button`,{type:`button`,"data-testid":`${Q.CLOCK_REP_SELECT}-${n.occurrenceId}`,"aria-pressed":!m&&n.occurrenceId===e.selectedOccurrenceId,disabled:m,"aria-disabled":m,...u(`board-reps-${n.occurrenceId}`),onClick:()=>t({kind:`reps-select`,occurrenceId:n.occurrenceId}),className:`min-h-11 min-w-11 max-w-[9rem] truncate rounded-full border px-3 py-2 text-xs disabled:opacity-40 disabled:cursor-not-allowed ${!m&&n.occurrenceId===e.selectedOccurrenceId?`border-foreground bg-foreground text-background`:`border-border text-muted-foreground hover:bg-accent`}`,children:n.label},n.occurrenceId))}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_VALUES_BUTTON,disabled:m,"aria-disabled":m,className:`ml-auto min-h-11 min-w-11 rounded-full border border-border px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-values`),onClick:()=>t({kind:`values-open`}),children:`Values *`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 px-3 py-1`,children:[(0,q.jsx)(Zpe,{mode:o,className:`min-w-0 flex-1 truncate px-0`}),(0,q.jsx)(Qpe,{mode:o,onModeChange:s,getFocusProps:r,className:`shrink-0`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_KEY_CHECK_BUTTON,className:`min-h-11 min-w-11 shrink-0 rounded-full border border-border px-3 py-2 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground`,...u(`board-key-check`),onClick:()=>l(!0),children:`Keys?`})]}),o===`keypad`&&d===null&&e.phase!==`review`&&(0,q.jsx)(`div`,{role:`group`,"aria-label":`Numeric keypad`,className:`border-t border-border/60 px-3 py-2`,children:e.reps.length>0&&e.selectedOccurrenceId?(0,q.jsxs)(`div`,{className:`grid w-full grid-cols-6 gap-1.5`,children:[[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`0`].map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-label":`Digit ${e}`,title:`Digit ${e}`,disabled:!g,"aria-disabled":!g,onClick:()=>{i.length<5&&u0(i+e)},...u(`board-keypad-${e}`),className:`min-h-11 min-w-11 w-full rounded-md border border-border bg-muted/40 font-mono text-sm font-semibold hover:bg-accent active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed`,children:e},e)),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Backspace`,title:`Backspace`,disabled:!g||i.length===0,"aria-disabled":!g||i.length===0,onClick:()=>u0(i.slice(0,-1)),...u(`board-keypad-back`),className:`flex min-h-11 min-w-11 w-full items-center justify-center rounded-md border border-border px-2 text-xs font-medium hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,children:(0,q.jsx)(Zn,{className:`h-4 w-4`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Set reps`,title:`Set reps`,disabled:!g||i.length===0,"aria-disabled":!g||i.length===0,onClick:()=>{let n=Number.parseInt(i,10);!Number.isSafeInteger(n)||n<0||t({kind:`reps-set`,occurrenceId:e.selectedOccurrenceId,value:n})&&u0(``)},...u(`board-keypad-set`),className:`min-h-11 min-w-11 w-full rounded-md bg-primary px-2 text-xs font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed`,children:`Set`})]}):(0,q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.reps.length>1?`Select a movement above to enter reps.`:`No rep movements active for keypad entry.`})}),d!==null&&(0,q.jsx)(`div`,{"data-testid":Q.CLOCK_ENTRY_OVERLAY,className:`fixed inset-0 z-[120] flex items-center justify-center bg-background/80 p-4`,children:(0,q.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,q.jsx)(`p`,{className:`mb-1 text-sm font-semibold`,children:d.label}),(0,q.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,q.jsx)(R0,{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:u0,getFocusProps:r},d.fieldId)]})}),e.stopRequested&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-[130] flex items-center justify-center bg-black/60 p-4`,children:(0,q.jsxs)(`div`,{"data-testid":Q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`Stop workout?`}),(0,q.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Partial results are saved. This cannot be undone.`}),(0,q.jsxs)(`div`,{className:`mt-4 flex justify-center gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,autoFocus:!0,"data-testid":Q.CLOCK_STOP_CONFIRM_CANCEL,className:`min-h-11 rounded-md border border-border px-3 py-2 text-xs font-medium hover:bg-accent`,...u(`board-stop-cancel`),onClick:()=>t({kind:`stop-cancel`}),children:`Keep going`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_STOP_CONFIRM_ACCEPT,className:`min-h-11 rounded-md bg-destructive px-3 py-2 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,...u(`board-stop-confirm`),onClick:()=>t({kind:`stop-confirm`}),children:`Stop — keep partial results`})]})]})}),(0,q.jsx)($pe,{open:c,onClose:()=>l(!1),getFocusProps:r})]})},W0=({noteId:e})=>{let t=Bz(e=>e.haltedRun),n=Ke(),[,r]=(0,K.useState)(0);(0,K.useEffect)(()=>{let e=Hz();e&&!Bz.getState().haltedRun&&Bz.getState().setHaltedRun(e)},[]),(0,K.useEffect)(()=>ide(()=>{r(e=>e+1)}),[]);let i=t??Hz();if(!i||e&&i.noteId&&i.noteId!==e)return null;let a=ade(i.sessionId);if(a.status===`pending`||a.status===`flushing`)return null;if(a.status===`failed`)return(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`halted-run-notice`,className:`mx-4 my-2 flex flex-wrap items-center justify-between gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-foreground`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsx)(`span`,{children:`Previous workout run could not be saved on reload.`}),(i.workoutTitle||i.elapsedMs!==void 0&&i.elapsedMs>0)&&(0,q.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[i.workoutTitle,i.elapsedMs!==void 0&&i.elapsedMs>0?`${i.workoutTitle?` · `:``}${ps(i.elapsedMs)}`:``]}),a.error&&(0,q.jsx)(`span`,{className:`text-destructive`,children:a.error})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>{ER()},className:`min-h-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent`,children:`Retry save`}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>{wR(i.sessionId),Uz(i.sessionId)},"aria-label":`Dismiss partial results notice`,className:`min-h-11 min-w-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Dismiss`})]})]});let o=AH(i.sessionId);return(0,q.jsxs)(`div`,{role:`status`,"data-testid":`halted-run-notice`,className:`mx-4 my-2 flex flex-wrap items-center justify-between gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-foreground`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsx)(`span`,{children:`Previous workout run was saved as partial results on reload.`}),(i.workoutTitle||i.elapsedMs!==void 0&&i.elapsedMs>0)&&(0,q.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[i.workoutTitle,i.elapsedMs!==void 0&&i.elapsedMs>0?`${i.workoutTitle?` · `:``}${ps(i.elapsedMs)}`:``]}),n?(0,q.jsx)(M,{to:o,onClick:()=>Uz(i.sessionId),className:`font-semibold underline underline-offset-2 hover:text-primary`,children:`View partial results`}):(0,q.jsx)(`a`,{href:o,onClick:()=>Uz(i.sessionId),className:`font-semibold underline underline-offset-2 hover:text-primary`,children:`View partial results`})]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>Uz(i.sessionId),"aria-label":`Dismiss partial results notice`,className:`min-h-11 min-w-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Dismiss`})]})},tme=({execution:e,outputCount:t,createdAt:n,handleStart:r,handleStop:i,handleNext:a,commandBoard:o,notice:s,runtimeErrors:c,canNext:l,workoutTitle:u,workoutFormat:d})=>{let{isCompact:f,isFull:p}=p1(),m=c&&c.length>0?(0,q.jsx)(`div`,{role:`alert`,"data-testid":Q.RUNTIME_ERROR_BANNER,className:`mx-3 mt-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:c.join(` · `)}):null;return p?(0,q.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[s,m,(0,q.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex ${f?`flex-col`:`flex-row`}`,children:[(0,q.jsx)(`div`,{className:`overflow-hidden bg-secondary/10 ${f?`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,q.jsx)(M1,{})}),(0,q.jsx)(`div`,{className:`flex flex-col overflow-y-auto bg-background ${f?`order-1 min-h-[min(280px,100%)] flex-[3]`:`min-h-0 w-2/3`}`,children:(0,q.jsx)(D1,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:l,compact:f,enableDisplayStack:!0})})]}),o,(0,q.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,q.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,q.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]}):(0,q.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[s,m,(0,q.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:(0,q.jsx)(Dfe,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:l,workoutTitle:u,workoutFormat:d})}),o,(0,q.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,q.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,q.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]})},G0=({block:e,view:t,noteContent:n,onClose:r,onComplete:i,isExpanded:a=!1,onToggleExpand:o,autoStart:s,onRuntimeReady:c,onRunStarted:l,externalPause:u,externalStop:d,adoptRuntime:f,parkOnUnmount:p,onPark:m,resultId:h,noteId:g})=>{let[_]=(0,K.useState)(()=>E0(e)),[v]=(0,K.useState)(()=>({statements:_.statements})),y=K.useMemo(()=>C0(_,t?.state.doc.toString()??n),[_,t,n]),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(!1),[w,T]=(0,K.useState)(0),[E,D]=(0,K.useState)(null),[O,k]=(0,K.useState)(!1),[A,j]=(0,K.useState)(!1),M=(0,K.useRef)(!1),N=(0,K.useRef)(!1),P=(0,K.useRef)(!1),[F,I]=(0,K.useState)(!1),ee=e.startLine+1,{overrides:L,setOverride:R}=Cpe(!0),{collectionItems:z}=P0([],L,v),B=(0,K.useCallback)(e=>{let n=e.subscribeToStack(n=>{if(!t)return;if(n.blocks.length===0){KN(t,[]);return}let r=n.blocks[0];r?.sourceIds?.length?KN(t,Mpe(e.script,r.sourceIds).map(e=>ee+e)):KN(t,[])}),r=e.subscribeToOutput(e=>{(e.outputType===`segment`||e.outputType===`milestone`)&&e.sourceBlockKey!==`waiting-to-start`&&(M.current||(M.current=!0,Uz(),l?.()),T(e=>e+1))});return()=>{n(),r(),t&&KN(t,[])}},[t,ee,l]),V=(0,K.useRef)(!1);(0,K.useEffect)(()=>()=>{V.current=!0},[]),(0,K.useEffect)(()=>{if(f||!O&&(z.length>0||ue.current))return;let e=Ape(_,t?.state.doc.toString()??n);if(!e){I(!0);return}x(e),Bz.getState().setRuntime(e),c?.(e);let r=B(e);return C(!0),()=>{if(r(),p&&V.current){m?.(e);return}Bz.getState().runtime===e&&Bz.getState().setRuntime(null),e.dispose()}},[O,z.length,f]),(0,K.useEffect)(()=>{if(!f)return;let e=f;k(!0),x(e),Bz.getState().setRuntime(e),c?.(e);let t=B(e);return C(!0),()=>{t(),m?.(e)}},[f]);let H=zJ(b);(0,K.useEffect)(()=>{H.status!==`idle`&&Bz.getState().setExecution(H)},[H.status,H.elapsedTime,H.stepCount,H.startTime]),(0,K.useEffect)(()=>{if((s||A)&&S&&H.status===`idle`){if(b?.stack.current?.blockType===`WaitingToStart`){if(!A)return;b.handle(new th(void 0,b.nowProvider))}(!b||b.stack.count>0)&&H.start(),j(!1)}},[s,A,S,H.status,H.start,b]),(0,K.useEffect)(()=>{H.status===`running`&&!M.current&&(M.current=!0,Uz(),l?.())},[H.status,l]),(0,K.useEffect)(()=>{u&&H.status===`running`&&H.pause()},[u,H.status,H.pause]),(0,K.useEffect)(()=>{!d||H.status===`completed`||H.status!==`running`&&H.status!==`paused`&&!M.current||(N.current=!0,Bz.getState().setActiveSessionMeta(null,null),ne())},[d,H.status,H.stop]);let U=(0,K.useCallback)(t=>{if(!b||P.current)return;P.current=!0,b.finalizeAnalytics();let n=O0(b.getOutputStatements(),{startTime:H.startTime??void 0,elapsedTime:H.getElapsedTime(),completed:t,now:b.nowProvider});i?.(e.id,n)},[e.id,H,i,b]),te=hpe({runtime:b,identity:y,executionStatus:H.status===`error`?`idle`:H.status}),W=(0,K.useRef)(null);(0,K.useEffect)(()=>{W.current=null},[te]),(0,K.useEffect)(()=>{if(H.status===`completed`){W.current=null;return}let e=S?`active`:null;if(!(!e||e===W.current||!te?.connected)){W.current=e;try{te.send({type:`rpc-workbench-update`,mode:e})}catch{}}},[S,H.status,te]),(0,K.useEffect)(()=>()=>{if(W.current===`active`)try{bB()?.send({type:`rpc-workbench-update`,mode:`idle`})}catch{}},[]),(0,K.useEffect)(()=>{if(H.status===`completed`&&!E&&!P.current&&(N.current=!0,Bz.getState().setActiveSessionMeta(null,null),D(new Date),U(!0),te?.connected)){let e=jpe(b?.getOutputStatements()||[]),t=xpe({totalDurationMs:H.getElapsedTime(),segmentCount:e});try{te.send(t)}catch{}}},[H,E,U,te,b]);let ne=(0,K.useCallback)(()=>{let e=H.status===`running`||H.status===`paused`||M.current||w>0,t=b?b.stack.count===0:!1;H.stop(),e&&(b?.handle({name:`abort`,timestamp:b.clock.currentDate,data:{}}),U(t))},[b,H,U,w]),re=(0,K.useCallback)(()=>{N.current=!0,Bz.getState().setActiveSessionMeta(null,null),ne(),r()},[ne,r]),ie=h??Bz.getState().activeSessionId,ae=g??Bz.getState().activeNoteId,oe=(H.status===`running`||H.status===`paused`||w>0||M.current)&&H.status!==`completed`,se=(0,K.useCallback)(()=>{if(!b)return;b.finalizeAnalytics();let t=O0(b.getOutputStatements(),{startTime:H.startTime??void 0,elapsedTime:H.getElapsedTime(),completed:!1,now:b.nowProvider});sde({resultId:ie||e.id,...ae?{noteId:ae}:{},blockId:e.id,...typeof e.version==`number`?{blockVersion:e.version}:{},...e.contentId?{blockContentId:e.contentId}:{},data:t,createdAt:Date.now()})},[b,H,e.id,e.version,e.contentId,ie,ae]),ce=(0,K.useRef)({isLive:oe,sessionId:ie,noteId:ae,workoutTitle:y.workoutTitle,elapsedMs:H.getElapsedTime(),stopAndReport:ne,stagePartialUnload:se});ce.current={isLive:oe,sessionId:ie,noteId:ae,workoutTitle:y.workoutTitle,elapsedMs:H.getElapsedTime(),stopAndReport:ne,stagePartialUnload:se},(0,K.useEffect)(()=>{let t=!1,n=()=>{if(t||N.current)return;let n=ce.current;if(!n.isLive)return;t=!0;let r=n.sessionId||e.id;Vz({sessionId:r,runtimeId:r,noteId:n.noteId??void 0,workoutTitle:n.workoutTitle,timestamp:Date.now(),elapsedMs:n.elapsedMs}),n.stagePartialUnload(),n.stopAndReport()};return window.addEventListener(`beforeunload`,n),window.addEventListener(`pagehide`,n),()=>{window.removeEventListener(`beforeunload`,n),window.removeEventListener(`pagehide`,n)}},[e.id]);let le=(0,K.useCallback)(()=>{b&&b.stack.current?.blockType===`WaitingToStart`&&b.handle(new th(void 0,b.nowProvider)),(!b||b.stack.count>0)&&H.start(),a||o?.()},[b,H,a,o]),ue=(0,K.useRef)(!1);(0,K.useEffect)(()=>{z.length>0&&(ue.current=!0)},[z.length]);let de=!O&&(z.length>0||ue.current),fe=()=>{k(!0),j(!0),a||o?.()},pe=(0,K.useCallback)(()=>{if(H.status===`paused`||!b)return;let e=H.status===`idle`;b.handle(new th(void 0,b.nowProvider)),e&&b.stack.count>0&&H.start()},[b,H]),{snapshot:me,dispatch:he}=Jpe({runtime:b,executionStatus:H.status===`error`?`idle`:H.status,enabled:S&&!de&&!F&&H.status!==`error`,hasCapturedWork:w>0||M.current,actions:{next:pe,start:le,playback:()=>{H.status===`running`?H.pause():H.status===`idle`||b?.stack.current?.blockType===`WaitingToStart`?le():H.start()},stop:re,dismiss:r}});return de?(0,q.jsx)(m1,{children:(0,q.jsx)(z0,{items:z,onSave:(e,t)=>{if(typeof t!=`number`)throw TypeError(`A numeric target is required`);if(!zpe(v,e,t,`target`))throw Error(`Enter a valid target before starting`);e.kind===`value`&&R(e.blockKey,e.metricType,t)},onSkip:()=>{},onStart:fe,mode:`pre-run`})}):F?(0,q.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`Nothing to run`}),(0,q.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,q.jsx)(`button`,{type:`button`,onClick:r,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`})]}):!S||!b?(0,q.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Initializing…`}):(0,q.jsx)(m1,{children:(0,q.jsx)(GJ,{runtime:b,children:(0,q.jsx)(tme,{execution:H,outputCount:w,createdAt:E,handleStart:()=>{let e=me?.phase===`ready`?{kind:`ready-start`}:{kind:`playback`};he(e)||le()},handleStop:()=>{he({kind:`stop-request`})||re()},handleNext:pe,commandBoard:me?(0,q.jsx)(eme,{snapshot:me,dispatch:he}):null,notice:oe?null:(0,q.jsx)(W0,{noteId:g}),runtimeErrors:(b.errors?.length??0)>0?b.errors.map(e=>e.error?.message||String(e.error??``)).filter(Boolean):H.status===`error`?[`Workout execution error`]:void 0,canNext:me?.canNext??!1,workoutTitle:y.workoutTitle,workoutFormat:y.workoutFormat})})})};function K0({intake:e=w$,recorder:t=_R,persistence:n=eR}={}){let[r,i]=(0,K.useState)(null),[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)(null),l=(0,K.useRef)(null),u=(0,K.useRef)(!1),d=(0,K.useRef)(null),f=(0,K.useRef)(null),p=(0,K.useRef)(null),m=(0,K.useCallback)(async(t,r,a)=>{if(f.current!==null)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(`
|
|
860
|
+
`)[0]?.trim().substring(0,50)||`Workout`,statementCount:e.scriptBlock?.statements?.length??0}))}}}var w0=`wod-wiki:userOutputOverrides`;function Cpe(e=!1){let t=Bz(e=>e.userOutputOverrides),n=Bz(e=>e.setUserOverride),r=Bz(e=>e.clearUserOverride);return(0,K.useEffect)(()=>{if(e)try{let e=localStorage.getItem(w0);if(!e)return;let t=JSON.parse(e);for(let[e,r]of Object.entries(t))n(e,r.map(Tpe))}catch{}},[e,n]),(0,K.useEffect)(()=>{if(!e)return;if(t.size===0){localStorage.removeItem(w0);return}let n={};for(let[e,r]of t)n[e]=r.map(wpe);localStorage.setItem(w0,JSON.stringify(n))},[t,e]),{overrides:t,setOverride:(0,K.useCallback)((e,r,i,a)=>{let o=(t.get(e)??Qo.empty(e)).filter(e=>e.type!==r),s={type:r,origin:`user`,value:i,image:a??String(i??``)};n(e,Qo.from(o,e).add(s))},[t,n]),removeOverride:(0,K.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,K.useCallback)(e=>{r(e)},[r]),clearAll:(0,K.useCallback)(()=>{for(let e of t.keys())r(e)},[t,r])}}function wpe(e){let t=e.timestamp instanceof Date?e.timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp);return{type:e.type,value:e.value,image:e.image,origin:e.origin,sourceBlockKey:e.sourceBlockKey,timestamp:t&&!Number.isNaN(t.getTime())?t.toISOString():void 0}}function Tpe(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 Epe=(typeof window<`u`?window.__wod_runtimeNowProvider?.():void 0)??of,Dpe=new Vm(rh(),Epe),T0=new WeakSet;function E0(e){let t=Kz(e),n=t&&t.tags.length>0?t.tagIndex:Sz(),r=t?qz(t):void 0,i=nu({tags:n,...r?{references:r}:{}}),a={...e,statements:i.read(e.content,e.sport).statements};return T0.add(a),t&&Gz(a,t),a}function Ope(e){if(!e||!e.trimStart().startsWith(`---`))return[];let{meta:t}=ac(e),n=Nre(t,`note`,`note-frontmatter`);return Object.keys(n.metrics??{}).length>0||Object.keys(n.summaries??{}).length>0||Object.keys(n.widgets??{}).length>0?[n]:[]}var kpe=[`tags`,`category`,`domain`,`format`,`equipment`,`quality`,`intent`,`discipline`,`intensity`,`sound`];function D0(e,t={}){let n=t.tags??Sz(),r=[],i=[];if(e&&e.trimStart().startsWith(`---`)){r.push(...Ope(e));let t=pc(e,[...kpe]);for(let e of t){let t=e.label.trim();t&&n.resolve(t)&&!i.includes(t)&&i.push(t)}}let a=Mp(n,i);return{activeTags:i,propertySources:r,dashboardWidgets:Ire([...r,...a],{scopeFilter:t.scopeFilter??(t.noteId?zb({noteId:t.noteId,rawContent:e}).scopeFilter:void 0)})}}function Ape(e,t){let n=Kz(e),r=n&&n.tags.length>0?n.tagIndex:Sz(),{activeTags:i,propertySources:a}=D0(t,{tags:r}),o=n?(()=>{let e=new Zd;return e.seed(Xd),e.seed(n.efforts),new Jd(e)})():void 0,s=n?qz(n):void 0,c={analyticsOptions:{tags:r,activeTags:i,propertySources:a,...o?{effortResolver:o}:{},...s?{references:s}:{}}},l=T0.has(e)&&e.statements?e:E0(e);return Dpe.createRuntime(l,c)??null}function O0(e,t){return{startTime:t.startTime??t.now.nowMs(),endTime:t.now.nowMs(),duration:t.elapsedTime,completed:t.completed,logs:e.map(Qw)}}function jpe(e){return e.filter(e=>e.outputType===`segment`).length}function Mpe(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 k0(e){let t=e.kind===`choice`?Y.Choice:String(e.metricType),n=e.kind===`value`&&e.sourceStatementId!==void 0?`:${e.sourceStatementId}`:``;return`${e.blockKey}:${t}${n}`}var Npe={[Y.Rep]:!0,[Y.Rounds]:!0,[Y.RIR]:!0,[Y.SessionRPE]:!0,[Y.Lap]:!0},Ppe={[Y.Duration]:!0},Fpe={[Y.Choice]:!0};function Ipe(e){let t=String(e);return Npe[t]?`integer`:Ppe[t]?`duration`:Fpe[t]?`choice`:`decimal`}function A0(e,t,n){return e.kind===`choice`?{fieldId:k0(e),label:e.exerciseLabel,metricType:Y.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:k0(e),label:e.exerciseLabel,metricType:String(e.metricType),domain:Ipe(e.metricType),intent:e.intent,required:e.intent===`target`,value:null,unit:e.unit??``,index:t,total:n}}function Lpe(e,t,n){let r=e?.statements[t.statementIndex];r&&zm(r,t.alternatives,n)}function Rpe(e,t){if(e.type===Y.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===Y.Distance||e.type===Y.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 zpe(e,t,n,r){if(r!==`target`||!Number.isFinite(n))return!1;if(t.kind===`choice`)return!Number.isInteger(n)||n<0?!1:(Lpe(e,t,n),!0);if(M0[String(t.metricType)]&&n<=0||t.metricType===Y.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(Rpe(a,n))):i.metrics.add({type:t.metricType,origin:`user-plan`,value:n,image:String(n)}),!0}function j0(e){if(!(`context`in e))return;let t=e.context;if(!(!t||typeof t!=`object`))return t}function Bpe(e){let t=j0(e)?.sourceBlockKey;return typeof t==`string`&&t.length>0?t:void 0}var M0={[Y.Duration]:!0,[Y.Rounds]:!0};function N0(e){return!M0[String(e)]}function Vpe(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===Y.Effort||e.type===Y.Label),c=s?.value?.toString()||s?.image||`Exercise`;for(let t of i.metrics){if(t.type===Y.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:N0(t.type)})}}}return r}for(let n of e){if(!n.metrics)continue;let e=Bpe(n);if(!e)continue;let i=j0(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`&&!M0[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===Y.Effort||e.type===Y.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:N0(t.type)})}}}return r}function P0(e,t,n){let r=(0,K.useMemo)(()=>Vpe(e,t,n),[e,t,n]);return{collectionItems:r,totalCount:r.length,isComplete:r.length===0}}function F0(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 I0(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 L0=(e,t)=>e?e(t):{},R0=({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,K.useState)(u??``),m=l??f,h=e=>{p(e),c?.(e)},[g,_]=(0,K.useState)(null),[v,y]=(0,K.useState)(e.selectedIndex??0),b=(0,K.useRef)(!1),x=(0,K.useRef)(null);(0,K.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`?F0(e,v):p0(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.nativeEvent.isComposing||e.keyCode===229||e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.repeat||w())},E=t=>{_(null),h(f0(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=g0(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=I0(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,K.useEffect)(()=>{y(e.selectedIndex??0)},[e.selectedIndex]),(0,q.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,q.jsx)(`div`,{className:`flex w-full flex-col gap-3`,role:`radiogroup`,"aria-label":e.label,children:S.map((e,t)=>(0,q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":v===t,"data-testid":`entry-choice-${t}`,onClick:()=>{y(t),_(null),s?.(t)},...L0(d,`entry-choice-${t}`),className:$(`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,q.jsxs)(`div`,{className:`flex items-center justify-center gap-2`,onKeyDown:T,children:[(0,q.jsx)(`input`,{"data-testid":`entry-min`,"aria-label":`Minutes`,inputMode:`numeric`,value:I0(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,q.jsx)(`span`,{className:`text-3xl font-bold text-muted-foreground`,children:`:`}),(0,q.jsx)(`input`,{"data-testid":`entry-sec`,"aria-label":`Seconds`,inputMode:`numeric`,value:I0(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,q.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,q.jsx)(`p`,{role:`alert`,className:`text-sm font-medium text-destructive`,children:C}),A&&(0,q.jsxs)(`div`,{className:`grid w-full max-w-[260px] grid-cols-3 gap-2`,"aria-label":`Number pad`,children:[j.map(e=>(0,q.jsx)(`button`,{type:`button`,"data-testid":e.id,onClick:()=>E(e.key),...L0(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,q.jsx)(`button`,{type:`button`,"data-testid":`entry-clear`,onClick:()=>E(`clear`),...L0(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,q.jsxs)(`div`,{className:`flex w-full items-center justify-between gap-3`,children:[(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-cancel`,onClick:i,...L0(d,`entry-cancel`),className:`min-h-11 min-w-11 px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:`Cancel`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[a&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-skip`,onClick:a,...L0(d,`entry-skip`),className:`min-h-11 min-w-11 px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:o??`Skip`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`entry-save`,onClick:w,disabled:t,...L0(d,`entry-save`),className:`flex min-h-11 min-w-11 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`})]})]})]})},z0=({items:e,onSave:t,onSkip:n,onStart:r,onClose:i,mode:a,runId:o,className:s})=>{let[c,l]=(0,K.useState)(new Set),[u,d]=(0,K.useState)(new Set),[f,p]=(0,K.useState)(0),[m,h]=(0,K.useState)({}),[g,_]=(0,K.useState)({}),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(!1),w=(0,K.useRef)(!1),T=(0,K.useRef)(!1);e.length>0&&(T.current=!0);let E=G1(),D=(0,K.useMemo)(()=>e.filter(e=>!c.has(k0(e))),[e,c]),O=Math.min(f,Math.max(D.length-1,0)),k=D[O],A=k?k0(k):null,M=a===`pre-run`&&D.length===0&&T.current;(0,K.useEffect)(()=>{A&&typeof E==`string`&&h(e=>e[A]===E?e:{...e,[A]:E})},[E,A]);let N=(0,K.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}),u0(``)},[]),P=(0,K.useCallback)((e,t)=>{h(n=>({...n,[e]:t})),u0(t)},[]),F=(0,K.useCallback)(async(n,r)=>{if(w.current)return!1;let i=k0(n),a=F0(A0(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 N(i),l(e=>new Set(e).add(i)),!0},[t,e.length,N]),I=(0,K.useCallback)(()=>{if(!k||w.current)return;let e=k0(k);a===`pre-run`&&!k.deferrable||(N(e),a===`post-run`&&n&&n(k),d(t=>new Set(t).add(e)),l(t=>new Set(t).add(e)))},[k,a,n,N]),L=(0,K.useCallback)(e=>{switch(e.kind){case`entry-save`:return!k||w.current||e.fieldId!==k0(k)?!1:(F(k,e.value),!0);case`entry-cancel`:return k?(P(k0(k),``),x(null),!0):!1;case`entry-skip`:return!k||w.current||e.fieldId!==k0(k)?!1:(I(),!0);case`choice-select`:return!k||k.kind!==`choice`||e.fieldId!==k0(k)||!Number.isInteger(e.index)||e.index<0||e.index>=k.alternatives.length?!1:(_(t=>({...t,[k0(k)]:e.index})),x(null),!0);case`ready-start`:return M?(r?.(),!0):!1;case`dismiss`:return a===`pre-run`&&!M?!1:(C(!0),i?.(),!0);default:return!1}},[k,F,I,M,r,i,a,P]);W1((0,K.useMemo)(()=>{if(D.length===0)return M&&!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?A0(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,M,S]),L,a===`pre-run`?10:20,{keyboard:!0});let R=(0,K.useCallback)(()=>{a===`pre-run`&&!M||(C(!0),i?.())},[a,M,i]);if(D.length===0)return M&&!S?(0,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:`Ready to Start`}),(0,q.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,q.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,q.jsx)(ee,{className:`w-5 h-5`})]})]}):null;if(!k)return null;let z=A0(k,O,D.length),B=k.kind===`choice`?g[z.fieldId]??0:0,V=a===`post-run`||k.deferrable;return(0,q.jsxs)(`div`,{className:$(`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,q.jsx)(`div`,{className:`h-1 bg-muted`,children:(0,q.jsx)(`div`,{className:`h-full bg-primary transition-all duration-300`,style:{width:`${(e.length-D.length+1)/(e.length+1)*100}%`}})}),(0,q.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-muted/10 px-6 py-4`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:a===`pre-run`?`Set Your Targets`:`Fill in your actuals`}),(0,q.jsxs)(`p`,{className:`text-xs uppercase tracking-label text-muted-foreground`,children:[e.length-D.length+1,` of `,e.length,` metrics`]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[O>0&&(0,q.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,q.jsx)(j,{className:`w-4 h-4`}),`Back`]}),i&&a===`post-run`&&(0,q.jsx)(`button`,{type:`button`,onClick:R,className:`rounded-full p-2 transition-colors hover:bg-muted`,children:(0,q.jsx)(ze,{className:`w-5 h-5 text-muted-foreground`})})]})]}),(0,q.jsx)(`div`,{className:`flex flex-1 flex-col items-center justify-center w-full max-w-md mx-auto p-8`,children:(0,q.jsxs)(`div`,{className:`w-full space-y-6`,children:[(0,q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,q.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,q.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,q.jsx)(R0,{entry:k.kind===`choice`?{...z,selectedIndex:B}:z,saving:v,error:b,onSave:e=>void F(k,e),onCancel:()=>{P(z.fieldId,``),x(null)},onSkip:V?I:void 0,skipLabel:a===`pre-run`?`Log after workout`:`Skip`,onChoice:k.kind===`choice`?e=>_(t=>({...t,[z.fieldId]:e})):void 0,onDraftChange:e=>P(z.fieldId,e),initialDraft:m[z.fieldId]??``},z.fieldId)]})}),b&&(0,q.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,q.jsx)($i,{className:`h-4 w-4`}),(0,q.jsxs)(`span`,{role:`alert`,children:[b,` — your entry is kept.`]})]})]})};function Hpe(e){let t=[];for(let n of e)n.origin===`user`&&n.type===Y.Rep&&typeof n.value==`number`&&t.push(n);return t}function B0(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 V0(e,t,n){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Actual rep count must be a nonnegative safe integer, got ${t}`);let r=B0(e,n,!0),i={type:Y.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 Cf(`metric:result`,n===r?[i]:[]));return}e.pushMemory(new Cf(`metric:result`,[i]));return}let o=a[Math.min(r,a.length-1)],s=o.metrics.filter(e=>e.origin!==`user`||e.type!==Y.Rep);o.update([...s,i])}function H0(e,t){let n=e.getMemoryByTag(`metric:result`);if(n.length===0)return null;let r=B0(e,t,!1);if(r===-1)return null;r=Math.min(r,n.length-1);let i=Hpe(n[r].metrics),a=i[i.length-1];return a?a.value:null}var Upe=new Set([`Rounds`,`Group`,`AMRAP`,`EMOM`,`SessionRoot`,`Root`]),Wpe=new Set([`Timer`]);function Gpe(e){let t=[];for(let n of e.stack.blocks){if(n.isComplete)continue;let e=n.blockType??``;if(Upe.has(e)||Wpe.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=Kpe(e);if(!(o!==null||e.metrics.some(e=>(e.type===Y.Effort||e.type===Y.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:qpe(n,e),target:o})}}return t}function Kpe(e){let t=null,n=null;for(let r of e.metrics)r.type===Y.Rep&&r.origin!==`user`&&typeof r.value==`number`&&(r.origin===`parser`?t=r.value:n=r.value);return n??t}function qpe(e,t){if(e.getMemoryByTag(`metric:display`).length<=1)return e.label;for(let e of t.metrics)if((e.type===Y.Effort||e.type===Y.Action)&&typeof e.value==`string`&&e.value)return e.value;return e.label}function U0(e,t){for(let n of e.stack.blocks){if(n.isComplete)continue;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 Jpe({runtime:e,executionStatus:t,actions:n,enabled:r=!0,saving:i=!1,hasCapturedWork:a=!1}){let o=(0,K.useRef)(Zfe()),[s,c]=(0,K.useState)(0),[l,u]=(0,K.useState)(0),[d,f]=(0,K.useState)(!1),[p,m]=(0,K.useState)(null),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(null),y=(0,K.useRef)({runtime:e,executionStatus:t,actions:n,hasCapturedWork:a});y.current={runtime:e,executionStatus:t,actions:n,hasCapturedWork:a},(0,K.useEffect)(()=>{if(e)return e.subscribeToStack(()=>c(e=>e+1))},[e]);let b=(0,K.useMemo)(()=>e?Gpe(e).map(t=>{let n=U0(e,t.occurrenceId);return{occurrenceId:t.occurrenceId,label:t.label,target:t.target,actual:n?H0(n.block,n.occurrence):null}}):[],[e,s,l]),x=t===`completed`?null:b.length===1?b[0].occurrenceId:p!==null&&b.some(e=>e.occurrenceId===p)?p:null;(0,K.useEffect)(()=>{m(x)},[x]),(0,K.useEffect)(()=>{b.length>0&&v(e=>e===`No rep movements`||e===`No rep movements to record`?null:e)},[b]);let S=h,C=e?.stack.current?.blockType===`WaitingToStart`,w=t,T=w===`completed`?`review`:C||w===`idle`&&!e?`ready`:`live`,E=w===`running`||w===`idle`,D=w===`running`||w===`paused`||a,O=(0,K.useMemo)(()=>!r||!e?null:{runId:o.current,phase:T,status:w,canNext:E,canStop:D,stopRequested:d,reps:b,selectedOccurrenceId:x,entry:S,error:_,saving:i},[r,e,T,w,E,D,d,b,x,S,_,i]);return W1(O,(0,K.useCallback)(e=>{let t=y.current.runtime,n=y.current.executionStatus,r=y.current.actions;if(h!==null&&[`next`,`ready-start`,`playback`,`stop-request`,`reps-select`].includes(e.kind))return!1;let i=e=>t!==null&&e!==null?U0(t,e):void 0,a=e=>{let t=b.find(t=>t.occurrenceId===e);return t?(g({fieldId:`reps:${t.occurrenceId}`,label:t.label,metricType:`reps`,domain:`integer`,intent:`actual`,required:!1,value:t.actual,unit:`reps`,index:0,total:1}),v(null),!0):(v(`Movement no longer active`),!1)};switch(e.kind){case`next`:return d?!1:n===`paused`?(v(`Paused — press play to continue first`),!1):n!==`running`&&n!==`idle`?!1:(r.next(),!0);case`ready-start`:return d||n!==`idle`?!1:(r.start(),!0);case`playback`:return d||n===`completed`?!1:(v(null),r.playback(),!0);case`stop-request`:{let e=n===`running`||n===`paused`||y.current.hasCapturedWork;return d||h!==null||!e?!1:(f(!0),!0)}case`stop-cancel`:return d?(f(!1),!0):!1;case`stop-confirm`:return d?(f(!1),r.stop(),!0):!1;case`values-open`:{if(h!==null||d)return!1;let e=x;return e===null?(v(b.length>1?`Select a movement first`:`No rep movements to record`),!1):a(e)}case`entry-cancel`:return h!==null&&(g(null),v(null),!0);case`entry-save`:{if(h===null||e.fieldId!==h.fieldId)return!1;if(!Number.isSafeInteger(e.value)||e.value<0)return v(`Reps must be a whole number of 0 or more`),!1;let t=i(h.fieldId.slice(5));return t?(V0(t.block,e.value,t.occurrence),u(e=>e+1),g(null),v(null),!0):(v(`Movement no longer active — draft preserved`),!1)}case`entry-skip`:return h===null||e.fieldId!==h.fieldId?!1:(g(null),v(null),!0);case`reps-adjust`:{if(h!==null||d)return!1;if(n===`completed`||T===`review`)return v(`Workout completed — rep controls are inactive`),!1;let t=e.occurrenceId===``?x:e.occurrenceId;if(t===null)return v(b.length>1?`Select a movement first`:`No rep movements`),!1;let r=i(t);if(!r)return v(`Movement no longer active`),!1;let a=(H0(r.block,r.occurrence)??0)+e.delta;return a<0||(V0(r.block,a,r.occurrence),u(e=>e+1),v(null),!0)}case`reps-set`:{if(h!==null||d)return!1;if(n===`completed`||T===`review`)return v(`Workout completed — rep controls are inactive`),!1;if(!Number.isSafeInteger(e.value)||e.value<0)return v(`Reps must be a whole number of 0 or more`),!1;let t=e.occurrenceId===``?x:e.occurrenceId;if(t===null)return v(b.length>1?`Select a movement first`:`No rep movements`),!1;let r=i(t);return r?(V0(r.block,e.value,r.occurrence),u(e=>e+1),v(null),!0):(v(`Movement no longer active`),!1)}case`reps-select`:return d||!b.some(t=>t.occurrenceId===e.occurrenceId)?!1:(m(e.occurrenceId),v(null),!0);case`choice-select`:return!1;case`dismiss`:return r.dismiss?(r.dismiss(),!0):!1}},[b,p,x,T,h,d]),0,{keyboard:!0}),{snapshot:O,dispatch:(0,K.useCallback)(e=>t0(o.current,e),[])}}var Ype=`Enter Select · Numpad Enter Next · 8/2/4/6 Move · +/- Reps · * Values · / Play · Esc Stop`,Xpe=`Enter Next · Numpad Enter Next · 8/2/4/6 Move · +/- Reps · * Values · / Play · Esc Stop`;function Zpe({mode:e,className:t}){return(0,q.jsx)(`p`,{"data-testid":Q.CLOCK_LEGEND,className:`hidden sm:block px-3 text-[10px] leading-4 text-muted-foreground ${t??``}`,children:e===`keypad`?Xpe:Ype})}var Qpe=({mode:e,onModeChange:t,className:n,getFocusProps:r})=>{let[i,a]=(0,K.useState)(()=>h0()),o=e??i,s=e=>{ipe(e),a(e),t?.(e)};return(0,q.jsx)(`div`,{"data-testid":Q.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,q.jsx)(`button`,{type:`button`,"aria-pressed":o===e,onClick:()=>s(e),...r?.(`board-keymode-${e}`),className:`min-h-11 min-w-11 rounded-full px-3 py-2 text-xs font-medium ${o===e?`bg-foreground text-background`:`text-muted-foreground hover:text-foreground`}`,children:e===`navigation`?`Nav`:`Keypad`},e))})},$pe=({open:e,onClose:t,getFocusProps:n})=>{let[r,i]=(0,K.useState)([]),a=(0,K.useRef)(null);return(0,K.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,K.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,q.jsx)(`div`,{className:`fixed inset-0 z-[140] flex items-center justify-center bg-black/60 p-4`,children:(0,q.jsxs)(`div`,{"data-testid":Q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`Key check`}),(0,q.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,q.jsxs)(`table`,{className:`mt-3 w-full font-mono text-[11px]`,children:[(0,q.jsx)(`thead`,{children:(0,q.jsxs)(`tr`,{className:`text-left text-muted-foreground`,children:[(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`key`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`code`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`loc`}),(0,q.jsx)(`th`,{className:`pr-2 font-medium`,children:`keyCode`}),(0,q.jsx)(`th`,{className:`font-medium`,children:`repeat`})]})}),(0,q.jsx)(`tbody`,{children:r.map((e,t)=>(0,q.jsxs)(`tr`,{className:`border-t border-border/60`,children:[(0,q.jsx)(`td`,{className:`pr-2`,children:e.key}),(0,q.jsx)(`td`,{className:`pr-2`,children:e.code}),(0,q.jsx)(`td`,{className:`pr-2`,children:e.location}),(0,q.jsxs)(`td`,{className:`pr-2`,children:[e.keyCode,`×`,e.count]}),(0,q.jsx)(`td`,{children:e.repeat?`yes`:`no`})]},t))})]}),(0,q.jsx)(`div`,{className:`mt-3 flex justify-end`,children:(0,q.jsx)(`button`,{type:`button`,ref:a,onClick:t,...n?.(`board-keycheck-close`),className:`min-h-11 min-w-11 rounded-md border border-border px-3 py-2 text-xs font-medium hover:bg-accent`,children:`Close`})})]})}):null},eme=({snapshot:e,dispatch:t,className:n,getFocusProps:r})=>{let i=G1(),a=Jfe(),[o,s]=(0,K.useState)(()=>h0()),[c,l]=(0,K.useState)(!1),u=e=>r?.(e),d=e.entry,f=(0,K.useRef)(d?.fieldId??null);K.useLayoutEffect(()=>{let e=d?.fieldId??null;r&&f.current!==e&&u0(``),f.current=e},[d?.fieldId,r]);let p=e.error??a,m=e.status===`completed`||e.phase===`review`,h=m?null:e.reps.find(t=>t.occurrenceId===e.selectedOccurrenceId)??null,g=e.phase===`live`&&!m&&e.selectedOccurrenceId!==null&&h!==null,_=e.reps.length>0&&(e.phase===`live`||e.phase===`collection`);return(0,q.jsxs)(`div`,{"data-testid":Q.CLOCK_COMMAND_BOARD,className:n,children:[p!==null&&(0,q.jsx)(`p`,{"data-testid":Q.CLOCK_ERROR,role:`status`,className:`px-3 pt-1 text-xs text-destructive`,children:p}),r&&e.phase===`ready`&&d===null&&(0,q.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`}),_&&(0,q.jsxs)(`div`,{"data-testid":Q.CLOCK_REP_COUNTER,className:`flex flex-wrap items-center gap-2 px-3 py-1.5 text-sm`,children:[(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Actual reps`}),(0,q.jsx)(`span`,{"data-testid":Q.CLOCK_REP_VALUE,className:`font-mono text-sm font-semibold`,children:m?`Complete`:`${h?.actual??`—`}${h?.target==null?``:` / Target ${h.target}`}`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_REP_MINUS,"aria-label":`Remove one rep`,title:`Subtract one rep`,disabled:!g,"aria-disabled":!g,className:`h-11 w-11 min-h-11 min-w-11 rounded-full border border-border text-base font-semibold hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-reps-minus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:-1}),children:`−`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_REP_PLUS,"aria-label":`Add one rep`,title:`Add one rep`,disabled:!g,"aria-disabled":!g,className:`h-11 w-11 min-h-11 min-w-11 rounded-full border border-border text-base font-semibold hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-reps-plus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:1}),children:`+`}),i!==``&&d===null&&(0,q.jsxs)(`span`,{"data-testid":Q.CLOCK_DRAFT_CHIP,className:`rounded bg-muted px-1.5 py-0.5 font-mono text-xs`,children:[i,` `,(0,q.jsx)(`span`,{className:`text-muted-foreground`,children:`⏎ to set`})]}),e.reps.length>1&&(0,q.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,role:`group`,"aria-label":`Counted movement`,children:e.reps.map(n=>(0,q.jsx)(`button`,{type:`button`,"data-testid":`${Q.CLOCK_REP_SELECT}-${n.occurrenceId}`,"aria-pressed":!m&&n.occurrenceId===e.selectedOccurrenceId,disabled:m,"aria-disabled":m,...u(`board-reps-${n.occurrenceId}`),onClick:()=>t({kind:`reps-select`,occurrenceId:n.occurrenceId}),className:`min-h-11 min-w-11 max-w-[9rem] truncate rounded-full border px-3 py-2 text-xs disabled:opacity-40 disabled:cursor-not-allowed ${!m&&n.occurrenceId===e.selectedOccurrenceId?`border-foreground bg-foreground text-background`:`border-border text-muted-foreground hover:bg-accent`}`,children:n.label},n.occurrenceId))}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_VALUES_BUTTON,disabled:m,"aria-disabled":m,className:`ml-auto min-h-11 min-w-11 rounded-full border border-border px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,...u(`board-values`),onClick:()=>t({kind:`values-open`}),children:`Values *`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 px-3 py-1`,children:[(0,q.jsx)(Zpe,{mode:o,className:`min-w-0 flex-1 truncate px-0`}),(0,q.jsx)(Qpe,{mode:o,onModeChange:s,getFocusProps:r,className:`shrink-0`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_KEY_CHECK_BUTTON,className:`min-h-11 min-w-11 shrink-0 rounded-full border border-border px-3 py-2 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground`,...u(`board-key-check`),onClick:()=>l(!0),children:`Keys?`})]}),o===`keypad`&&d===null&&e.phase!==`review`&&(0,q.jsx)(`div`,{role:`group`,"aria-label":`Numeric keypad`,className:`border-t border-border/60 px-3 py-2`,children:e.reps.length>0&&e.selectedOccurrenceId?(0,q.jsxs)(`div`,{className:`grid w-full grid-cols-6 gap-1.5`,children:[[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`0`].map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-label":`Digit ${e}`,title:`Digit ${e}`,disabled:!g,"aria-disabled":!g,onClick:()=>{i.length<5&&u0(i+e)},...u(`board-keypad-${e}`),className:`min-h-11 min-w-11 w-full rounded-md border border-border bg-muted/40 font-mono text-sm font-semibold hover:bg-accent active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed`,children:e},e)),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Backspace`,title:`Backspace`,disabled:!g||i.length===0,"aria-disabled":!g||i.length===0,onClick:()=>u0(i.slice(0,-1)),...u(`board-keypad-back`),className:`flex min-h-11 min-w-11 w-full items-center justify-center rounded-md border border-border px-2 text-xs font-medium hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed`,children:(0,q.jsx)(Zn,{className:`h-4 w-4`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Set reps`,title:`Set reps`,disabled:!g||i.length===0,"aria-disabled":!g||i.length===0,onClick:()=>{let n=Number.parseInt(i,10);!Number.isSafeInteger(n)||n<0||t({kind:`reps-set`,occurrenceId:e.selectedOccurrenceId,value:n})&&u0(``)},...u(`board-keypad-set`),className:`min-h-11 min-w-11 w-full rounded-md bg-primary px-2 text-xs font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed`,children:`Set`})]}):(0,q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.reps.length>1?`Select a movement above to enter reps.`:`No rep movements active for keypad entry.`})}),d!==null&&(0,q.jsx)(`div`,{"data-testid":Q.CLOCK_ENTRY_OVERLAY,className:`fixed inset-0 z-[120] flex items-center justify-center bg-background/80 p-4`,children:(0,q.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,q.jsx)(`p`,{className:`mb-1 text-sm font-semibold`,children:d.label}),(0,q.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,q.jsx)(R0,{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:u0,getFocusProps:r},d.fieldId)]})}),e.stopRequested&&(0,q.jsx)(`div`,{className:`fixed inset-0 z-[130] flex items-center justify-center bg-black/60 p-4`,children:(0,q.jsxs)(`div`,{"data-testid":Q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`Stop workout?`}),(0,q.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Partial results are saved. This cannot be undone.`}),(0,q.jsxs)(`div`,{className:`mt-4 flex justify-center gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,autoFocus:!0,"data-testid":Q.CLOCK_STOP_CONFIRM_CANCEL,className:`min-h-11 rounded-md border border-border px-3 py-2 text-xs font-medium hover:bg-accent`,...u(`board-stop-cancel`),onClick:()=>t({kind:`stop-cancel`}),children:`Keep going`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.CLOCK_STOP_CONFIRM_ACCEPT,className:`min-h-11 rounded-md bg-destructive px-3 py-2 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,...u(`board-stop-confirm`),onClick:()=>t({kind:`stop-confirm`}),children:`Stop — keep partial results`})]})]})}),(0,q.jsx)($pe,{open:c,onClose:()=>l(!1),getFocusProps:r})]})},W0=({noteId:e})=>{let t=Bz(e=>e.haltedRun),n=Ke(),[,r]=(0,K.useState)(0);(0,K.useEffect)(()=>{let e=Hz();e&&!Bz.getState().haltedRun&&Bz.getState().setHaltedRun(e)},[]),(0,K.useEffect)(()=>ide(()=>{r(e=>e+1)}),[]);let i=t??Hz();if(!i||e&&i.noteId&&i.noteId!==e)return null;let a=ade(i.sessionId);if(a.status===`pending`||a.status===`flushing`)return null;if(a.status===`failed`)return(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`halted-run-notice`,className:`mx-4 my-2 flex flex-wrap items-center justify-between gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-foreground`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsx)(`span`,{children:`Previous workout run could not be saved on reload.`}),(i.workoutTitle||i.elapsedMs!==void 0&&i.elapsedMs>0)&&(0,q.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[i.workoutTitle,i.elapsedMs!==void 0&&i.elapsedMs>0?`${i.workoutTitle?` · `:``}${ps(i.elapsedMs)}`:``]}),a.error&&(0,q.jsx)(`span`,{className:`text-destructive`,children:a.error})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>{ER()},className:`min-h-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent`,children:`Retry save`}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>{wR(i.sessionId),Uz(i.sessionId)},"aria-label":`Dismiss partial results notice`,className:`min-h-11 min-w-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Dismiss`})]})]});let o=AH(i.sessionId);return(0,q.jsxs)(`div`,{role:`status`,"data-testid":`halted-run-notice`,className:`mx-4 my-2 flex flex-wrap items-center justify-between gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-foreground`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsx)(`span`,{children:`Previous workout run was saved as partial results on reload.`}),(i.workoutTitle||i.elapsedMs!==void 0&&i.elapsedMs>0)&&(0,q.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[i.workoutTitle,i.elapsedMs!==void 0&&i.elapsedMs>0?`${i.workoutTitle?` · `:``}${ps(i.elapsedMs)}`:``]}),n?(0,q.jsx)(M,{to:o,onClick:()=>Uz(i.sessionId),className:`font-semibold underline underline-offset-2 hover:text-primary`,children:`View partial results`}):(0,q.jsx)(`a`,{href:o,onClick:()=>Uz(i.sessionId),className:`font-semibold underline underline-offset-2 hover:text-primary`,children:`View partial results`})]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>Uz(i.sessionId),"aria-label":`Dismiss partial results notice`,className:`min-h-11 min-w-11 rounded border border-border/70 px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Dismiss`})]})},tme=({execution:e,outputCount:t,createdAt:n,handleStart:r,handleStop:i,handleNext:a,commandBoard:o,notice:s,runtimeErrors:c,canNext:l,workoutTitle:u,workoutFormat:d})=>{let{isCompact:f,isFull:p}=p1(),m=c&&c.length>0?(0,q.jsx)(`div`,{role:`alert`,"data-testid":Q.RUNTIME_ERROR_BANNER,className:`mx-3 mt-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:c.join(` · `)}):null;return p?(0,q.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[s,m,(0,q.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex ${f?`flex-col`:`flex-row`}`,children:[(0,q.jsx)(`div`,{className:`overflow-hidden bg-secondary/10 ${f?`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,q.jsx)(M1,{})}),(0,q.jsx)(`div`,{className:`flex flex-col overflow-y-auto bg-background ${f?`order-1 min-h-[min(280px,100%)] flex-[3]`:`min-h-0 w-2/3`}`,children:(0,q.jsx)(D1,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:l,compact:f,enableDisplayStack:!0})})]}),o,(0,q.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,q.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,q.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]}):(0,q.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[s,m,(0,q.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:(0,q.jsx)(Dfe,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:l,workoutTitle:u,workoutFormat:d})}),o,(0,q.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,q.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,q.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]})},G0=({block:e,view:t,noteContent:n,onClose:r,onComplete:i,isExpanded:a=!1,onToggleExpand:o,autoStart:s,onRuntimeReady:c,onRunStarted:l,externalPause:u,externalStop:d,adoptRuntime:f,parkOnUnmount:p,onPark:m,resultId:h,noteId:g})=>{let[_]=(0,K.useState)(()=>E0(e)),[v]=(0,K.useState)(()=>({statements:_.statements})),y=K.useMemo(()=>C0(_,t?.state.doc.toString()??n),[_,t,n]),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(!1),[w,T]=(0,K.useState)(0),[E,D]=(0,K.useState)(null),[O,k]=(0,K.useState)(!1),[A,j]=(0,K.useState)(!1),M=(0,K.useRef)(!1),N=(0,K.useRef)(!1),P=(0,K.useRef)(!1),[F,I]=(0,K.useState)(!1),ee=e.startLine+1,{overrides:L,setOverride:R}=Cpe(!0),{collectionItems:z}=P0([],L,v),B=(0,K.useCallback)(e=>{let n=e.subscribeToStack(n=>{if(!t)return;if(n.blocks.length===0){KN(t,[]);return}let r=n.blocks[0];r?.sourceIds?.length?KN(t,Mpe(e.script,r.sourceIds).map(e=>ee+e)):KN(t,[])}),r=e.subscribeToOutput(e=>{(e.outputType===`segment`||e.outputType===`milestone`)&&e.sourceBlockKey!==`waiting-to-start`&&(M.current||(M.current=!0,Uz(),l?.()),T(e=>e+1))});return()=>{n(),r(),t&&KN(t,[])}},[t,ee,l]),V=(0,K.useRef)(!1);(0,K.useEffect)(()=>()=>{V.current=!0},[]),(0,K.useEffect)(()=>{if(f||!O&&(z.length>0||ue.current))return;let e=Ape(_,t?.state.doc.toString()??n);if(!e){I(!0);return}x(e),Bz.getState().setRuntime(e),c?.(e);let r=B(e);return C(!0),()=>{if(r(),p&&V.current){m?.(e);return}Bz.getState().runtime===e&&Bz.getState().setRuntime(null),e.dispose()}},[O,z.length,f]),(0,K.useEffect)(()=>{if(!f)return;let e=f;k(!0),x(e),Bz.getState().setRuntime(e),c?.(e);let t=B(e);return C(!0),()=>{t(),m?.(e)}},[f]);let H=zJ(b);(0,K.useEffect)(()=>{H.status!==`idle`&&Bz.getState().setExecution(H)},[H.status,H.elapsedTime,H.stepCount,H.startTime]),(0,K.useEffect)(()=>{if((s||A)&&S&&H.status===`idle`){if(b?.stack.current?.blockType===`WaitingToStart`){if(!A)return;b.handle(new th(void 0,b.nowProvider))}(!b||b.stack.count>0)&&H.start(),j(!1)}},[s,A,S,H.status,H.start,b]),(0,K.useEffect)(()=>{H.status===`running`&&!M.current&&(M.current=!0,Uz(),l?.())},[H.status,l]),(0,K.useEffect)(()=>{u&&H.status===`running`&&H.pause()},[u,H.status,H.pause]),(0,K.useEffect)(()=>{!d||H.status===`completed`||H.status!==`running`&&H.status!==`paused`&&!M.current||(N.current=!0,Bz.getState().setActiveSessionMeta(null,null),ne())},[d,H.status,H.stop]);let U=(0,K.useCallback)(t=>{if(!b||P.current)return;P.current=!0,b.finalizeAnalytics();let n=O0(b.getOutputStatements(),{startTime:H.startTime??void 0,elapsedTime:H.getElapsedTime(),completed:t,now:b.nowProvider});i?.(e.id,n)},[e.id,H,i,b]),te=hpe({runtime:b,identity:y,executionStatus:H.status===`error`?`idle`:H.status}),W=(0,K.useRef)(null);(0,K.useEffect)(()=>{W.current=null},[te]),(0,K.useEffect)(()=>{if(H.status===`completed`){W.current=null;return}let e=S?`active`:null;if(!(!e||e===W.current||!te?.connected)){W.current=e;try{te.send({type:`rpc-workbench-update`,mode:e})}catch{}}},[S,H.status,te]),(0,K.useEffect)(()=>()=>{if(W.current===`active`)try{bB()?.send({type:`rpc-workbench-update`,mode:`idle`})}catch{}},[]),(0,K.useEffect)(()=>{if(H.status===`completed`&&!E&&!P.current&&(N.current=!0,Bz.getState().setActiveSessionMeta(null,null),D(new Date),U(!0),te?.connected)){let e=jpe(b?.getOutputStatements()||[]),t=xpe({totalDurationMs:H.getElapsedTime(),segmentCount:e});try{te.send(t)}catch{}}},[H,E,U,te,b]);let ne=(0,K.useCallback)(()=>{let e=H.status===`running`||H.status===`paused`||M.current||w>0,t=b?b.stack.count===0:!1;H.stop(),e&&(b?.handle({name:`abort`,timestamp:b.clock.currentDate,data:{}}),U(t))},[b,H,U,w]),re=(0,K.useCallback)(()=>{N.current=!0,Bz.getState().setActiveSessionMeta(null,null),ne(),r()},[ne,r]),ie=h??Bz.getState().activeSessionId,ae=g??Bz.getState().activeNoteId,oe=(H.status===`running`||H.status===`paused`||w>0||M.current)&&H.status!==`completed`,se=(0,K.useCallback)(()=>{if(!b)return;b.finalizeAnalytics();let t=O0(b.getOutputStatements(),{startTime:H.startTime??void 0,elapsedTime:H.getElapsedTime(),completed:!1,now:b.nowProvider});sde({resultId:ie||e.id,...ae?{noteId:ae}:{},blockId:e.id,...typeof e.version==`number`?{blockVersion:e.version}:{},...e.contentId?{blockContentId:e.contentId}:{},...e.content?{blockContent:e.content}:{},...e.dialect?{blockDialect:e.dialect}:{},...e.sport?{blockSport:e.sport}:{},data:t,createdAt:Date.now()})},[b,H,e.id,e.version,e.contentId,e.content,e.dialect,e.sport,ie,ae]),ce=(0,K.useRef)({isLive:oe,sessionId:ie,noteId:ae,workoutTitle:y.workoutTitle,elapsedMs:H.getElapsedTime(),stopAndReport:ne,stagePartialUnload:se});ce.current={isLive:oe,sessionId:ie,noteId:ae,workoutTitle:y.workoutTitle,elapsedMs:H.getElapsedTime(),stopAndReport:ne,stagePartialUnload:se},(0,K.useEffect)(()=>{let t=!1,n=()=>{if(t||N.current)return;let n=ce.current;if(!n.isLive)return;t=!0;let r=n.sessionId||e.id;Vz({sessionId:r,runtimeId:r,noteId:n.noteId??void 0,workoutTitle:n.workoutTitle,timestamp:Date.now(),elapsedMs:n.elapsedMs}),n.stagePartialUnload(),n.stopAndReport()};return window.addEventListener(`beforeunload`,n),window.addEventListener(`pagehide`,n),()=>{window.removeEventListener(`beforeunload`,n),window.removeEventListener(`pagehide`,n)}},[e.id]);let le=(0,K.useCallback)(()=>{b&&b.stack.current?.blockType===`WaitingToStart`&&b.handle(new th(void 0,b.nowProvider)),(!b||b.stack.count>0)&&H.start(),a||o?.()},[b,H,a,o]),ue=(0,K.useRef)(!1);(0,K.useEffect)(()=>{z.length>0&&(ue.current=!0)},[z.length]);let de=!O&&(z.length>0||ue.current),fe=()=>{k(!0),j(!0),a||o?.()},pe=(0,K.useCallback)(()=>{if(H.status===`paused`||!b)return;let e=H.status===`idle`;b.handle(new th(void 0,b.nowProvider)),e&&b.stack.count>0&&H.start()},[b,H]),{snapshot:me,dispatch:he}=Jpe({runtime:b,executionStatus:H.status===`error`?`idle`:H.status,enabled:S&&!de&&!F&&H.status!==`error`,hasCapturedWork:w>0||M.current,actions:{next:pe,start:le,playback:()=>{H.status===`running`?H.pause():H.status===`idle`||b?.stack.current?.blockType===`WaitingToStart`?le():H.start()},stop:re,dismiss:r}});return de?(0,q.jsx)(m1,{children:(0,q.jsx)(z0,{items:z,onSave:(e,t)=>{if(typeof t!=`number`)throw TypeError(`A numeric target is required`);if(!zpe(v,e,t,`target`))throw Error(`Enter a valid target before starting`);e.kind===`value`&&R(e.blockKey,e.metricType,t)},onSkip:()=>{},onStart:fe,mode:`pre-run`})}):F?(0,q.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`Nothing to run`}),(0,q.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,q.jsx)(`button`,{type:`button`,onClick:r,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`})]}):!S||!b?(0,q.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Initializing…`}):(0,q.jsx)(m1,{children:(0,q.jsx)(GJ,{runtime:b,children:(0,q.jsx)(tme,{execution:H,outputCount:w,createdAt:E,handleStart:()=>{let e=me?.phase===`ready`?{kind:`ready-start`}:{kind:`playback`};he(e)||le()},handleStop:()=>{he({kind:`stop-request`})||re()},handleNext:pe,commandBoard:me?(0,q.jsx)(eme,{snapshot:me,dispatch:he}):null,notice:oe?null:(0,q.jsx)(W0,{noteId:g}),runtimeErrors:(b.errors?.length??0)>0?b.errors.map(e=>e.error?.message||String(e.error??``)).filter(Boolean):H.status===`error`?[`Workout execution error`]:void 0,canNext:me?.canNext??!1,workoutTitle:y.workoutTitle,workoutFormat:y.workoutFormat})})})};function K0({intake:e=w$,recorder:t=_R,persistence:n=eR}={}){let[r,i]=(0,K.useState)(null),[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)(null),l=(0,K.useRef)(null),u=(0,K.useRef)(!1),d=(0,K.useRef)(null),f=(0,K.useRef)(null),p=(0,K.useRef)(null),m=(0,K.useCallback)(async(t,r,a)=>{if(f.current!==null)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(`
|
|
861
861
|
`).slice(0,r.startLine).join(`
|
|
862
862
|
`).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=Br(),_=await Yz({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,K.useCallback)(async(e,n)=>{if(f.current!==null)try{await f.current}catch{}let r=l.current;if(!r||u.current)return;if(p.current!==null)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,K.useCallback)(async()=>{if(f.current!==null)try{await f.current}catch{}p.current!==null&&await p.current},[]);return{run:r,recorded:a,pendingResults:s,start:m,finalize:h,reset:(0,K.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,K.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 q0({title:e,getBlock:t,getContent:n},{intake:r=w$,persistence:i=eR,recorder:a=_R,toast:o=CQ}={}){let s=K0({intake:r,persistence:i,recorder:a}),[c,l]=(0,K.useState)(null),[u,d]=(0,K.useState)(null),[f,p]=(0,K.useState)(!1),m=(0,K.useRef)(!1),h=(0,K.useRef)(0),g=(0,K.useRef)(null),_=(0,K.useRef)(null);(0,K.useEffect)(()=>()=>{h.current+=1},[]);let v=(0,K.useCallback)(async e=>{let t=++h.current;try{await s.end(e?.results)}catch(e){t===h.current&&o({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try stopping again.`,variant:`destructive`});return}t===h.current&&l(null)},[s]),y=(0,K.useCallback)(async(r,i)=>{let a=r??t();if(!a||m.current)return;m.current=!0;let c=++h.current;try{let t=await s.start(i??n(),a,{pageTitle:e??`Playground`});if(c!==h.current)return;d(null),l({kind:`timer`,block:t.block,results:null})}catch(e){c===h.current&&o({title:`Could not save playground workout`,description:e instanceof Error?e.message:`The workout was not started. Please try again.`,variant:`destructive`})}finally{m.current=!1}},[s,e,t,n,o]),b=(0,K.useCallback)(async t=>{let r=h.current;try{await s.finalize(t,t.completed??!1)}catch(e){r===h.current&&o({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try completing again.`,variant:`destructive`});return}if(r===h.current&&(d(t),l(null),g.current)){let t=g.current;g.current=null,p(!1);let r=_.current??{doc:n(),meta:{pageTitle:e??`Playground`}};_.current=null;try{await s.reset(r.doc,r.meta)}catch(e){o({title:`Could not save reset snapshot`,description:e instanceof Error?e.message:`Your partial results are kept — try resetting again.`,variant:`destructive`})}finally{t()}}},[s,n,e,o]),x=(0,K.useCallback)(async t=>{let r=t??n(),i={pageTitle:e??`Playground`};try{if(s.run&&!s.recorded&&c){if(s.pendingResults)return await s.finalize(s.pendingResults.results,!1),await s.reset(r,i),!0;_.current={doc:r,meta:i},p(!0);let e=Promise.withResolvers();return g.current=e.resolve,await e.promise,!0}return await s.reset(r,i),!0}catch(e){return o({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try resetting again.`,variant:`destructive`}),!1}},[s,n,e,c,o]);return{fullscreen:c,startRun:y,closeRun:v,completedResults:u,runState:(0,K.useMemo)(()=>({isReconnect:!1,onReconnect:()=>{},onRun:()=>{y()}}),[y]),handleWorkoutComplete:b,run:s.run,recorded:s.recorded,pendingResults:s.pendingResults,resetRequested:f,resetRun:x}}function nme({initialSource:e,initialSourceKey:t,contentOverride:n}){let[r,i]=(0,K.useState)(e),[a,o]=(0,K.useState)(1),[s,c]=(0,K.useState)(!1),[l,u]=(0,K.useState)(t),[d,f]=(0,K.useState)(e),p=(0,K.useRef)(e),m=(0,K.useRef)(null),h=(0,K.useRef)(new Map([[t,{original:e,current:e}]])),g=(0,K.useRef)(void 0),_=(0,K.useCallback)(()=>{requestAnimationFrame(()=>m.current?.focus())},[]),v=(0,K.useCallback)((e,t=e,n)=>{let r=h.current.get(t),a=r?.current??e,s=r?.original??e;r||h.current.set(t,{original:e,current:e}),u(t),f(s);let l=n?.focus!==!1;if(l&&_(),a===p.current){c(!1);return}clearTimeout(g.current),c(!0),o(0),g.current=setTimeout(()=>{p.current=a,i(a),o(1),c(!1),g.current=void 0,l&&_()},180)},[_]),y=(0,K.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,K.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,K.useCallback)(e=>{m.current=e},[]),S=(0,K.useCallback)(()=>p.current,[]),C=(0,K.useRef)(void 0);return(0,K.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 J0=`wodwiki.quests.v1`;function Y0(){try{let e=window.localStorage.getItem(J0);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 rme(e){try{window.localStorage.setItem(J0,JSON.stringify(e))}catch(e){console.error(`Failed to write quest progress:`,e)}}function X0(e){return Y0()[e]??{}}function Z0(e,t){let n=Y0();n[e]=t,rme(n),window.dispatchEvent(new StorageEvent(`storage`,{key:J0}))}function ime(e,t){let n=X0(e);n[t]||(n[t]=!0,Z0(e,n))}function ame(e,t){let n=X0(e);n[t]=!n[t],Z0(e,n)}function Q0(e,t){let[n,r]=(0,K.useState)(()=>X0(e));(0,K.useEffect)(()=>{let t=t=>{t.key===`wodwiki.quests.v1`&&r(X0(e))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)},[e]);let i=(0,K.useCallback)(t=>{ime(e,t),r(X0(e))},[e]),a=(0,K.useCallback)(t=>{ame(e,t),r(X0(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 $0({pageRoute:e,quests:t,completedResults:n,enabled:r=!0}){let{markComplete:i}=Q0(e,t),a=(0,K.useRef)(new Set),o=t.map(e=>e.id).join(`|`);(0,K.useEffect)(()=>{a.current.clear()},[e,o]);let s=t.filter(e=>e.validation?.type===`workout-complete`);return(0,K.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 e2({pageRoute:e,quests:t,initialSource:n,currentSource:r,enabled:i=!0}){let{markComplete:a}=Q0(e,t),o=t.some(e=>e.id===`qs-arrive`),s=t.some(e=>e.id===`qs-edit`),c=(0,K.useRef)(n);c.current=n;let l=(0,K.useRef)(r);l.current=r,(0,K.useEffect)(()=>{!i||!o||a(`qs-arrive`)},[i,o,a]),(0,K.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 t2(e){let[t,n]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(e).matches);return(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e);if(!t.addEventListener)return;let r=e=>n(e.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}var n2=(0,K.createContext)(null);function ome(){return(0,K.useContext)(n2)}function r2({title:e,subtitle:t,children:n,onReset:r,headerActions:i,className:a}){let o=ome();return(0,q.jsxs)(`div`,{className:$(`flex flex-col w-full h-full rounded-2xl lg:rounded-3xl border border-border shadow-2xl bg-background`,a),children:[(0,q.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,q.jsxs)(`div`,{className:`flex gap-1.5`,children:[r?(0,q.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,q.jsx)(`div`,{className:`size-2.5 rounded-full bg-red-500/30`}),(0,q.jsx)(`div`,{className:`size-2.5 rounded-full bg-amber-500/30`}),(0,q.jsx)(`div`,{className:`size-2.5 rounded-full bg-emerald-500/30`})]}),(0,q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[o?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex min-w-0 flex-1 justify-end`,children:o.status}),o.pips]}):(0,q.jsxs)(`span`,{className:`text-[9px] font-black text-muted-foreground uppercase tracking-[0.2em]`,children:[e,t&&(0,q.jsxs)(`span`,{className:`ml-1.5 font-medium normal-case tracking-normal text-muted-foreground`,children:[`· `,t]})]}),i,r&&(0,q.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,q.jsx)(_r,{className:`size-3`}),`Reset`]})]})]}),(0,q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden rounded-b-2xl lg:rounded-b-3xl`,children:n})]})}function i2(){let e=Ke(),t=(0,K.useContext)(Vr),n=(0,K.useCallback)(e=>{t.navigator.push(e)},[t]);return e&&t?.navigator?n:void 0}var sme=[{id:`timeseries`,label:`Trend Line`,icon:u},{id:`bar`,label:`Comparison Bar`,icon:Ir},{id:`summary`,label:`Session Summary`,icon:dn},{id:`table`,label:`Data Table`,icon:vn},{id:`value`,label:`KPI Value`,icon:he}],a2={totalVolume:`Total Volume`,reps:`Total Reps`,elapsed:`Split Duration`,"calc.e1rm":`Estimated 1RM`,tis:`Intensity Score (TIS)`,sessionLoad:`Session Load`,distance:`Total Distance`};function cme(e){let t=e.summary;return t?t.totalDistance>0&&t.totalVolume===0?`elapsed`:t.totalVolume>0?`totalVolume`:t.totalReps>0?`reps`:t.tis===void 0?`elapsed`:`tis`:`totalVolume`}function lme(e){let{ctx:t,viz:n,measure:r,movementSlug:i,scopes:a,bindBlockToken:o,bindNotebookToken:s,bindRangeToken:c}=e,l=t.notebooks?.[0]?.replace(/^notebook\//,``),u=t.noteTitle??`Workout`,d={};if(t.blockContentId&&(d.block=t.blockContentId),l&&(d.notebook=l),d.range=`12w`,n===`summary`){let e=`:session{result:${t.resultId}}`,n={view:`summary`,title:`${u} — Summary`,query:e};return{title:`${u} — Summary`,question:`Key execution KPIs and movement breakdown`,wql:e,yaml:fv(n),queryObject:n,tokens:d}}if(n===`table`&&a.length===1&&a[0]===`current`){let e=`:session{result:${t.resultId}}`,n={view:`table`,title:`${u} — Splits`,query:e};return{title:`${u} — Splits`,question:`Recorded segment splits for this workout run`,wql:e,yaml:fv(n),queryObject:n,tokens:d}}let f=r===`elapsed`?`avg`:r===`calc.e1rm`?`max`:r===`tis`?`avg`:`sum`,p=[];i!==`all`&&p.push(`effort:${i}`),a.includes(`current`)&&a.length===1?p.push(`result:${t.resultId}`):a.includes(`block`)&&t.blockContentId&&!a.includes(`history`)?p.push(`block:${o?`$block`:t.blockContentId}`):a.includes(`notebook`)&&l&&!a.includes(`history`)&&p.push(`notebook:${s?`$notebook`:l}`);let m=` by {week}`;n===`value`?m=``:a.includes(`current`)&&a.length===1?m=n===`timeseries`?` by {split}`:` by {effort}`:n===`bar`&&(m=i!==`all`||a.includes(`block`)?` by {session}`:` by {effort}`);let h=a.includes(`current`)&&a.length===1?``:c?` last $range`:` last 12w`,g=`${f}:${r}{${p.join(`, `)}}${m}${h}`,_=a2[r],v=i===`all`?`${u} · ${_}`:`${_} — ${i}`,y=a.includes(`history`)?`${_} across all recorded workouts`:a.includes(`block`)&&t.blockContentId?`${_} across attempts of ${u}`:`${_} from this workout`,b={view:n,title:v,description:y,query:g};return{title:v,question:y,wql:g,yaml:fv(b),queryObject:b,tokens:d}}function o2(e){return!e.open||!e.context?null:(0,q.jsx)(ume,{...e,context:e.context},e.context.resultId)}function ume({onOpenChange:e,context:t,preferredUnit:n,onOpenInStudio:r,onNavigateDashboard:i}){let a=i2(),{items:o,loading:s}=fU(),c=HP(),l=(0,K.useMemo)(()=>c?aU(c):[],[c]),u=(0,K.useMemo)(()=>o.filter(e=>e.editable),[o]),d=(0,K.useMemo)(()=>o.filter(e=>!e.editable),[o]),[f,p]=(0,K.useState)(1),[m,h]=(0,K.useState)(()=>t.blockContentId?`timeseries`:`summary`),[g,_]=(0,K.useState)(()=>cme(t)),[v,y]=(0,K.useState)(`all`),[b,x]=(0,K.useState)(()=>t.blockContentId?[`current`,`block`]:[`current`]),[S,C]=(0,K.useState)(!1),[w,T]=(0,K.useState)(!1),[E,D]=(0,K.useState)(!1),[O,k]=(0,K.useState)(!1),[A,j]=(0,K.useState)(!1),[M,N]=(0,K.useState)(()=>u.length>0?`existing`:`new`),[P,F]=(0,K.useState)(()=>u[0]?.slug??``),[I,ee]=(0,K.useState)(()=>d[0]?.slug??``),[L,R]=(0,K.useState)(()=>`${t.noteTitle??`Workout`} Dashboard`),[z,B]=(0,K.useState)(!1),[V,H]=(0,K.useState)(null);(0,K.useEffect)(()=>{!P&&u[0]?.slug&&F(u[0].slug),!I&&d[0]?.slug&&ee(d[0].slug)},[u,d,P,I]);let U=(0,K.useMemo)(()=>lme({ctx:t,viz:m,measure:g,movementSlug:v,scopes:b,bindBlockToken:S,bindNotebookToken:w,bindRangeToken:E}),[t,m,g,v,b,S,w,E]),[te,W]=(0,K.useState)(void 0),[ne,re]=(0,K.useState)(!0),[ie,oe]=(0,K.useState)(void 0);(0,K.useEffect)(()=>{let e=!1;return re(!0),oe(void 0),(async()=>{try{let r=t.notebooks?.[0]?.replace(/^notebook\//,``),i=await iJ({resultId:t.resultId,blockContentId:t.blockContentId,noteId:t.noteId,notebookSlug:r}),a=await new Ey(KE(sJ,{preferredUnit:n}),{tokens:U.tokens,pageSources:i}).run(U.wql),o=YE(Xg(U.wql),a,{}),s=a.outputs.find(e=>e.error)?.error??a.diagnostics[0];e||(W(o),oe(s))}catch(t){e||oe(t instanceof Error?t.message:String(t))}finally{e||re(!1)}})(),()=>{e=!0}},[t.resultId,t.blockContentId,t.noteId,t.notebooks,U.wql,U.tokens,n]);let se=e=>{x(t=>{let n=t.includes(e)?t.filter(t=>t!==e):[...t,e];return n.length>0?n:[`current`]})},ce=e=>{i?i(e):a&&a(zH(e))},le=()=>{e(!1),r?r(U.wql):a&&a(LH({q:U.wql}))},ue=()=>{typeof navigator<`u`&&navigator.clipboard?.writeText&&navigator.clipboard.writeText(`\`\`\`query\n${U.yaml}\n\`\`\``).catch(()=>{}),j(!0),setTimeout(()=>j(!1),1500)},de=async()=>{if(z)return;B(!0),H(null);let n={title:U.title,question:U.question,type:m,wql:U.wql,queryObject:U.queryObject};try{if(M===`existing`){if(!P)throw Error(`Select a destination dashboard.`);let t=await DU.resolve(P);await DU.update(t,Pb(t.rawContent,n)),sU(),e(!1),ce(P)}else if(M===`clone`){if(!I)throw Error(`Select a prebuilt dashboard to clone.`);let t=l.find(e=>e.slug===I);if(!t)throw Error(`Prebuilt dashboard template "${I}" was not found.`);let r=await kU.cloneDashboard(I,t.rawContent);await DU.update(r,Pb(r.rawContent,n)),sU();let{meta:i}=ac(r.rawContent),a=typeof i.slug==`string`&&i.slug?kb(i.slug):I;e(!1),ce(a)}else{let r=L.trim()||`${t.noteTitle??`Workout`} Dashboard`,i=t.notebooks?.[0]?.replace(/^notebook\//,``),a=Pb(lae({title:r,resultId:t.resultId,blockContentId:t.blockContentId,notebookSlug:i}),n),o=await DU.create({title:r,rawContent:a,type:`dashboard`,sourceId:`dashboards`});sU();let{meta:s}=ac(o.rawContent),c=typeof s.slug==`string`&&s.slug?kb(s.slug):kb(r);e(!1),ce(c)}}catch(e){H(e instanceof Error?e.message:String(e))}finally{B(!1)}},fe=t.summary?.movementRollup??[],pe=t.notebooks?.[0]?.replace(/^notebook\//,``);return(0,q.jsx)(SD,{open:!0,onClose:()=>e(!1),presentation:`sheet`,title:f===1?`Add Workout to Dashboard`:`Choose Dashboard Destination`,description:f===1?`Bind a metric and comparison scope, then verify the live chart preview.`:`Append to an existing vault board, clone a prebuilt board, or scaffold a dedicated workout dashboard.`,footer:(0,q.jsxs)(q.Fragment,{children:[f===2?(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_STEP_BACK,onClick:()=>p(1),className:`inline-flex items-center gap-1 min-h-11 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground hover:text-foreground`,children:[(0,q.jsx)(je,{className:`size-3.5`,"aria-hidden":`true`}),`Back`]}):(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_OPEN_STUDIO,onClick:le,className:`inline-flex items-center gap-1 min-h-11 rounded-lg border border-border px-3 text-xs font-medium text-foreground hover:bg-muted`,children:[(0,q.jsx)(nee,{className:`size-3.5 text-primary`,"aria-hidden":`true`}),`Open in WQL Studio`]}),(0,q.jsx)(`div`,{className:`flex-1`}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>e(!1),className:`min-h-11 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground hover:text-foreground`,children:`Cancel`}),f===1?(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_STEP_NEXT,onClick:()=>p(2),className:`inline-flex items-center gap-1.5 min-h-11 rounded-lg bg-primary px-4 text-xs font-semibold text-primary-foreground hover:bg-primary/90`,children:[(0,q.jsx)(`span`,{children:`Destination`}),(0,q.jsx)(ae,{className:`size-3.5`,"aria-hidden":`true`})]}):(0,q.jsxs)(`button`,{type:`button`,disabled:z,"data-testid":Q.ADD_DASHBOARD_COMMIT,onClick:()=>void de(),className:`inline-flex items-center gap-1.5 min-h-11 rounded-lg bg-primary px-4 text-xs font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:[(0,q.jsx)(ti,{className:`size-3.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:z?`Saving…`:M===`new`?`Create Dashboard`:`Save Widget`})]})]}),children:(0,q.jsx)(`div`,{"data-testid":Q.ADD_DASHBOARD_SHEET,className:`space-y-4`,children:f===1?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Visualization`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:sme.map(e=>{let t=e.icon,n=m===e.id;return(0,q.jsxs)(`button`,{type:`button`,"aria-pressed":n,onClick:()=>h(e.id),className:`inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors min-h-10 sm:min-h-8 ${n?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`}`,children:[(0,q.jsx)(t,{className:`size-3.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:e.label})]},e.id)})})]}),m!==`summary`&&(0,q.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,q.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Measure`}),(0,q.jsx)(`select`,{value:g,onChange:e=>_(e.target.value),className:`min-h-10 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground`,children:Object.entries(a2).map(([e,t])=>(0,q.jsx)(`option`,{value:e,children:t},e))})]}),(0,q.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Movement Scope`}),(0,q.jsxs)(`select`,{value:v,onChange:e=>y(e.target.value),className:`min-h-10 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground`,children:[(0,q.jsx)(`option`,{value:`all`,children:`All movements in scope`}),fe.map(e=>(0,q.jsx)(`option`,{value:e.effortSlug,children:e.label},e.effortSlug))]})]})]}),m!==`summary`&&(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Comparison Window & Peers`}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,q.jsx)(`button`,{type:`button`,"aria-pressed":b.includes(`current`),onClick:()=>se(`current`),className:`rounded-lg border px-2.5 py-1 text-xs font-medium min-h-9 ${b.includes(`current`)?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground`}`,children:`This run`}),(0,q.jsx)(`button`,{type:`button`,disabled:!t.blockContentId,"aria-pressed":b.includes(`block`),onClick:()=>se(`block`),className:`rounded-lg border px-2.5 py-1 text-xs font-medium min-h-9 disabled:opacity-40 ${b.includes(`block`)?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground`}`,children:`Prior runs of block`}),(0,q.jsx)(`button`,{type:`button`,disabled:!pe,"aria-pressed":b.includes(`notebook`),onClick:()=>se(`notebook`),className:`rounded-lg border px-2.5 py-1 text-xs font-medium min-h-9 disabled:opacity-40 ${b.includes(`notebook`)?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground`}`,children:pe?`Notebook: ${pe}`:`Notebook baseline`}),(0,q.jsx)(`button`,{type:`button`,"aria-pressed":b.includes(`history`),onClick:()=>se(`history`),className:`rounded-lg border px-2.5 py-1 text-xs font-medium min-h-9 ${b.includes(`history`)?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground`}`,children:`All history`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 pt-1 text-xs text-muted-foreground`,children:[t.blockContentId&&(0,q.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 cursor-pointer`,children:[(0,q.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>C(e.target.checked)}),(0,q.jsxs)(`span`,{children:[`Bind `,(0,q.jsx)(`code`,{children:`$block`}),` token`]})]}),pe&&(0,q.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 cursor-pointer`,children:[(0,q.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked)}),(0,q.jsxs)(`span`,{children:[`Bind `,(0,q.jsx)(`code`,{children:`$notebook`}),` token`]})]}),(0,q.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 cursor-pointer`,children:[(0,q.jsx)(`input`,{type:`checkbox`,checked:E,onChange:e=>D(e.target.checked)}),(0,q.jsxs)(`span`,{children:[`Bind `,(0,q.jsx)(`code`,{children:`$range`}),` token`]})]})]})]}),(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Live Preview`}),ne&&(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Running query…`})]}),(0,q.jsx)(`div`,{className:`rounded-xl border border-border bg-background/60 p-3 min-h-[200px]`,children:ie?(0,q.jsx)(`div`,{className:`text-xs text-destructive font-mono`,children:ie}):(0,q.jsx)(`div`,{className:m===`summary`||m===`table`||m===`value`?void 0:`h-52`,children:(0,q.jsx)(BO,{type:m,result:te,label:U.title,unit:n})})})]}),(0,q.jsxs)(`div`,{className:`rounded-lg border border-border/70 bg-muted/20`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_WQL_DISCLOSURE,"aria-expanded":O,onClick:()=>k(e=>!e),className:`flex w-full items-center justify-between px-3 py-2 text-xs font-medium text-muted-foreground hover:text-foreground`,children:[(0,q.jsx)(`span`,{children:`Generated YAML & WQL`}),O?(0,q.jsx)(It,{className:`size-3.5`}):(0,q.jsx)(rt,{className:`size-3.5`})]}),O&&(0,q.jsxs)(`div`,{className:`border-t border-border/60 p-3 space-y-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground truncate`,children:U.wql}),(0,q.jsxs)(`button`,{type:`button`,onClick:ue,className:`inline-flex items-center gap-1 rounded border border-border bg-background px-2 py-1 text-[11px] font-medium text-foreground hover:bg-muted shrink-0`,children:[A?(0,q.jsx)(zr,{className:`size-3 text-emerald-600`}):(0,q.jsx)(Gi,{className:`size-3`}),A?`Copied`:`Copy`]})]}),(0,q.jsx)(`pre`,{className:`overflow-x-auto rounded bg-card p-2 text-[11px] font-mono text-foreground border border-border/60`,children:U.yaml})]})]})]}):(0,q.jsxs)(`div`,{className:`space-y-4`,children:[(0,q.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-2`,children:[(0,q.jsxs)(`button`,{type:`button`,disabled:u.length===0,"data-testid":Q.ADD_DASHBOARD_MODE_EXISTING,"aria-pressed":M===`existing`,onClick:()=>N(`existing`),className:`rounded-xl border p-3 text-left transition-colors disabled:opacity-40 ${M===`existing`?`border-primary bg-primary/10 text-foreground`:`border-border bg-card text-muted-foreground hover:text-foreground`}`,children:[(0,q.jsx)(`div`,{className:`text-xs font-semibold`,children:`Existing Vault Board`}),(0,q.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:[u.length,` editable board`,u.length===1?``:`s`]})]}),(0,q.jsxs)(`button`,{type:`button`,disabled:d.length===0,"data-testid":Q.ADD_DASHBOARD_MODE_CLONE,"aria-pressed":M===`clone`,onClick:()=>N(`clone`),className:`rounded-xl border p-3 text-left transition-colors disabled:opacity-40 ${M===`clone`?`border-primary bg-primary/10 text-foreground`:`border-border bg-card text-muted-foreground hover:text-foreground`}`,children:[(0,q.jsx)(`div`,{className:`text-xs font-semibold`,children:`Clone Prebuilt & Add`}),(0,q.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:[d.length,` seed template`,d.length===1?``:`s`]})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_MODE_NEW,"aria-pressed":M===`new`,onClick:()=>N(`new`),className:`rounded-xl border p-3 text-left transition-colors ${M===`new`?`border-primary bg-primary/10 text-foreground`:`border-border bg-card text-muted-foreground hover:text-foreground`}`,children:[(0,q.jsx)(`div`,{className:`text-xs font-semibold`,children:`New Workout Dashboard`}),(0,q.jsx)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:`Scaffolds 4 linked workout panels`})]})]}),s&&(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading dashboard library…`}),M===`existing`&&(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Select Editable Dashboard`}),(0,q.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2`,children:u.map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-pressed":P===e.slug,onClick:()=>F(e.slug),className:`rounded-lg border px-3 py-2 text-left text-xs font-medium min-h-11 ${P===e.slug?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground hover:bg-muted`}`,children:e.title},e.slug))})]}),M===`clone`&&(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Select Prebuilt Dashboard to Clone`}),(0,q.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2`,children:d.map(e=>(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.ADD_DASHBOARD_CLONE_PREBUILT,"aria-pressed":I===e.slug,onClick:()=>ee(e.slug),className:`rounded-lg border px-3 py-2 text-left text-xs font-medium min-h-11 ${I===e.slug?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground hover:bg-muted`}`,children:e.title},e.slug))})]}),M===`new`&&(0,q.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border bg-muted/20 p-3`,children:[(0,q.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`New Dashboard Title`}),(0,q.jsx)(`input`,{type:`text`,"data-testid":Q.ADD_DASHBOARD_NEW_TITLE,value:L,onChange:e=>R(e.target.value),className:`min-h-11 rounded-lg border border-border bg-background px-3 text-sm text-foreground`})]}),(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground text-pretty`,children:`Creates an editable dashboard bound to this session, its workout block history, movement breakdown, and your newly configured widget.`})]}),V&&(0,q.jsx)(`p`,{role:`alert`,className:`rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:V})]})})})}function dme(e){return Xj(e,null)}function fme(){return VM.of(async()=>{let[e,t,n]=await Promise.all([X.getAllTagTypes(),X.getAllTags(),d2()]);return c2=new Map(t.map(e=>[e.label,e.type??`general`])),{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 s2=null;function pme(e,t,n){return TG(e===`effort`?{id:t,kind:`effort`,sourceNotebook:`efforts`,sourceNote:t,title:n,date:null,effort:{slug:t,label:n}}:{id:t,kind:`equipment`,sourceNotebook:`equipment`,sourceNote:t,title:n,date:null})}var c2;function mme(e,t){let n=t?.trim().toLowerCase(),r=(!n||n===`tag`||n===`tags`||n===`category`?void 0:n)??c2?.get(e)??`general`;return`/t/${encodeURIComponent(r)}/${encodeURIComponent(e)}`}function hme(e,t){let n=e.trim();if(!n)return null;let r=Sz(),i=r.resolve(n)??r.resolve(n.toLowerCase());if(!i||i.isCategory)return null;let a=i.contributions.find(e=>e.kind===`tag`&&!!r.resolve(e.slug)?.isCategory)?.slug,o=c2?.get(i.slug)??a??t;return{slug:i.slug,type:o}}function gme(e){return{resolve:(t,n)=>e.resolve(t,n),resolveEffort:t=>e.resolveEffort(t),resolveEquipment:t=>e.resolveEquipment(t),resolveTag:hme,openHref:(e,t,n)=>e===`tag`?mme(t,n):pme(e,t,t),createHref:e=>e===`effort`?`/effort/new?mode=create`:e===`equipment`?`/equipment/new?mode=create`:`/tags`}}function _me(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 l2(){let e=SP(),t=uz();if(!e.isInitialized()||!t.isInitialized())return null;let n={efforts:[...e.list()],equipment:[...t.list()]},r=_me(n);if(!s2||s2.signature!==r){let e=nf(n);s2={index:e,provider:gme(e),signature:r}}return s2.provider}function u2(){return l2(),s2?.index??null}function vme(){let e=La.fromClass(class{view;channel=null;unsubscribeTags;onReload=()=>{this.view.dispatch({effects:UM.of(null)})};constructor(e){this.view=e,typeof BroadcastChannel<`u`&&(this.channel=new BroadcastChannel(mx),this.channel.onmessage=this.onReload),this.unsubscribeTags=Ez(this.onReload)}destroy(){this.channel?.close(),this.unsubscribeTags()}});return[HM.of(l2),e]}async function d2(){return{efforts:[...SP().list()],equipment:[...uz().list()]}}function yme(e){let t=new Set;if(!e)return t;let n=e=>{if(!e)return;let n=e.trim().toLowerCase();if(n){t.add(n);for(let e of n.split(/[\s/_-]+/))e.length>=3&&t.add(e)}};n(e.notebookSlug);for(let t of e.tags)n(t);n(e.defaultEffort);for(let t of e.defaultEquipment)n(t);return t}function bme(e,t,n){if(!t)return 0;let r=0;if(t.defaultEffort&&e.slug===t.defaultEffort&&(r+=100),e.equipment?.some(e=>t.defaultEquipment.includes(e))&&(r+=40),e.baseAttributes?.discipline&&n.has(e.baseAttributes.discipline.toLowerCase())&&(r+=30),e.sourcePath){let t=e.sourcePath.toLowerCase();for(let e of n)if(e.length>=3&&t.includes(e)){r+=20;break}}let i=e.slug.toLowerCase();for(let e of n)if(e.length>=4&&i.includes(e)){r+=10;break}return r}function xme(e){return{wql:{values:async t=>(await(e?.loadWqlSuggestions??(async e=>aA(e===`tags`?`tag`:e)))(t)).map(e=>({label:e.value,detail:e.label,type:`constant`})),tagTypeValues:async e=>{let t=e.trim().toLowerCase();return(await X.getAllTags().catch(()=>[])).filter(e=>e.type?.toLowerCase()===t).map(e=>e.label)}},whiteboardScript:{efforts:async()=>{let t=e?.loadCatalog?await e.loadCatalog():await d2(),n=e?.getNotebookScope?.(),r=yme(n);return t.efforts.map(e=>{let t=bme(e,n,r),i=e.baseAttributes?.discipline,a=e.equipment?.length?{equipment:e.equipment}:{};return t>0?{value:e.slug,label:e.label,aliases:e.aliases,...a,detail:i?`In notebook · ${i}`:`In this notebook`,section:`In this notebook`,boost:Math.min(25,10+Math.round(t/10))}:{value:e.slug,label:e.label,aliases:e.aliases,...a,detail:i??e.slug,section:`Movements`}})},equipment:async()=>{let t=e?.loadCatalog?await e.loadCatalog():await d2(),n=e?.getNotebookScope?.(),r=new Set((n?.defaultEquipment??[]).map(e=>e.toLowerCase()));return t.equipment.map(e=>r.has(e.slug.toLowerCase())?{value:e.slug,label:e.label,aliases:e.aliases,detail:`In this notebook`,section:`In this notebook`,boost:12}:{value:e.slug,label:e.label,aliases:e.aliases,detail:`Equipment`,section:`Equipment`})},tags:async()=>{let t=e?.getNotebookScope?.(),n=e?.loadTags?[...await e.loadTags()]:Sz().list().map(e=>e.slug);if(!t?.tags.length)return n.map(e=>({value:e,detail:`Tag`,section:`Tags`}));let r=new Set,i=[];for(let e of t.tags){let t=e.replace(/^#/,``).trim(),n=t.toLowerCase();!t||r.has(n)||(r.add(n),i.push({value:t,detail:`In this notebook`,section:`In this notebook`,boost:12}))}for(let e of n){let t=e.replace(/^#/,``).trim(),n=t.toLowerCase();!t||r.has(n)||(r.add(n),i.push({value:t,detail:`Tag`,section:`Tags`}))}return i},sounds:()=>{if(e?.loadSounds){let t=e.loadSounds();if(Array.isArray(t))return t.map(e=>({value:e.id,label:e.name}))}return rB().map(e=>({value:e.id,label:e.name}))},...e?.getNotebookScope?{preferredUnits:()=>{let t=e.getNotebookScope?.();return[t?.preferredMassUnit,t?.preferredDistanceUnit].filter(e=>typeof e==`string`&&e.length>0)}}:{},...e?.onCreateEffort?{onCreateEffort:e.onCreateEffort}:{},...e?.onCreateTag?{onCreateTag:e.onCreateTag}:{}}}}function Sme(){return async e=>{let t=uM(e.state);if(t&&t.type!==`markdown`)return null;let n=e.state.doc.lineAt(e.pos);if(n.number>1&&e.state.doc.line(1).text.trim()===`---`){let t=!1;for(let r=2;r<n.number;r++)if(/^(?:---|\.\.\.)\s*$/.test(e.state.doc.line(r).text)){t=!0;break}if(!t)return null}let r=n.text.slice(0,e.pos-n.from),i=/\[\[([^\]]*)$/.exec(r);if(i){let t=await X.getAllNotes().catch(()=>[]),n=new Set,r=[];for(let e of t){let t=e.title?.trim();!t||n.has(t.toLowerCase())||(n.add(t.toLowerCase()),r.push({label:t,detail:e.tags?.slice(0,2).map(e=>`#${e}`).join(` `)||`Note`,type:`class`,apply:(e,n,r,i)=>{let a=e.state.doc.sliceString(i,i+2)===`]]`,o=`${t}${a?``:`]]`}`;e.dispatch({changes:{from:r,to:i,insert:o},selection:{anchor:r+o.length},userEvent:`input.complete`})}}))}return r.length===0?null:{from:e.pos-i[1].length,options:r.slice(0,40),validFor:/^[^\]]*$/}}if(/^\s*#{1,6}(?:\s|$)/.test(r))return null;let a=/(?:^#([a-zA-Z][a-zA-Z0-9-]*)|(?<=\s)#([a-zA-Z0-9-]*))$/.exec(r);if(a){let t=r.lastIndexOf(`#`),i=n.from+t,o=Sz().list().filter(e=>!e.isCategory);if(o.length===0)return null;let s=o.map(e=>{let t=e.contributions[0],n=t?.kind===`metric`?t.type:t?.kind===`function`?t.name:t?.kind===`tag`?`#${t.slug}`:`Tag`;return{label:`#${e.slug}`,detail:n,type:`keyword`,apply:`#${e.slug} `}}),c=/^[a-zA-Z0-9-]*/.exec(n.text.slice(e.pos-n.from))[0];if(c.length>0){let t=(a[1]??a[2]??``).toLowerCase(),n=s.filter(e=>e.label.toLowerCase().includes(`#${t}`));return n.length>0?{from:i,to:e.pos+c.length,options:n,filter:!1}:null}return{from:i,options:s,validFor:/^#[a-zA-Z0-9-]*$/}}return null}}function f2(e){let{meta:t}=ac(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 p2(e,t){return{id:`reference:${e}`,label:e===`effort`?`Effort`:`Equipment`,search:async n=>{let r=await d2(),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 m2(e){let t=e.replace(/^#/,``).trim();return t?t.includes(` `)||/[A-Z]/.test(t)?t:t.replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Custom`}async function h2(e){let t=af(e)||`effort-${Date.now().toString(36)}`,n=m2(e),r=e.trim().toLowerCase()!==n.toLowerCase()&&e.trim().toLowerCase()!==t?[e.trim()]:[],i=new Date().toISOString();return await h$({kind:`effort`,slug:t,rawContent:Rd({id:`effort-user-${Br()}`,slug:t,label:n,aliases:r,baseAttributes:{met:5},registrySource:`user`,createdAt:i,updatedAt:i}),title:n,expectedSourceRevision:0}),await vP(SP()),{slug:t,label:n}}async function g2(e,t){let n=SP(),r=await $d(n,e,t);return await vP(n),r}async function _2(e){let t=af(e)||`equipment-${Date.now().toString(36)}`,n=m2(e),r=e.trim().toLowerCase()!==n.toLowerCase()&&e.trim().toLowerCase()!==t?[e.trim()]:[];return await h$({kind:`equipment`,slug:t,rawContent:Vd({id:`equipment-user-${Br()}`,slug:t,label:n,aliases:r,registrySource:`user`}),title:n,expectedSourceRevision:0}),await az(uz()),{slug:t,label:n}}async function v2(e,t=`general`){let n=e.replace(/^#/,``).trim();if(!n)throw Error(`Tag name cannot be empty.`);return await h$({kind:`tag`,slug:n,rawContent:Ud({id:`tag-${n}`,slug:n,label:n,category:t,aliases:[],metrics:{},summaries:{},tags:[],functions:[]}),title:n,expectedSourceRevision:0,category:t}),c2?.set(n,t),await Tz(),{slug:n}}function Cme(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 y2(e){let t=Cme(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 b2(e,t){let n=y2(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 wme(e,t){return t||(e.current||=new $L,e.current)}function x2(e,t,n,r,i){Array.from(e).forEach(e=>{let a=Br(),o=new FileReader;o.onload=async()=>{let s=o.result;if(r)try{await i.mutateNote(r,{attachments:{add:[{id:a,file:new File([s],e.name||`paste-${a.slice(0,8)}`,{type:e.type})}]}})}catch(e){dR(`NoteEditor`,`Attachment persist skipped:`,e)}let c=e.type.startsWith(`image/`),l=`\n${c?`!`:``}[${e.name||(c?`Pasted image`:`Attachment`)}](${a})\n`,u=Math.min(t,n.state.doc.length);n.dispatch({changes:{from:u,insert:l},selection:{anchor:u+l.length}})},o.readAsArrayBuffer(e)})}function Tme(e){let t=new Map,n=La.fromClass(class{destroy(){for(let e of t.values())URL.revokeObjectURL(e);t.clear()}});return[LM.of(async n=>{let r=t.get(n);if(r)return r;if(!e)return null;try{let r=(await X.getAttachmentsForNote(e)).find(e=>e.id===n);if(!r)return null;if(typeof r.data==`string`&&/^(https?:\/\/|data:|blob:)/i.test(r.data))return r.data;let i=new Blob([r.data],{type:r.mimeType||`application/octet-stream`}),a=URL.createObjectURL(i);return t.set(n,a),a}catch{return null}}),n]}function Eme(e,t){return mo.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&&(x2(i,a,r,e,t),!0)},paste:(n,r)=>{let i=n.clipboardData?.files;if(!i||i.length===0)return!1;n.preventDefault();let a=r.state.selection.main.to;return x2(i,a,r,e,t),!0}})}var S2=eo.define(),Dme=La.fromClass(class{unsubscribes;constructor(e){let t=()=>e.dispatch({effects:[S2.of(null)]});this.unsubscribes=[Ez(t),bP(t),sz(t)]}update(e){}destroy(){for(let e of this.unsubscribes)e()}}),Ome={[Y.Duration]:`cm-metric-underline-duration`,[Y.Rep]:`cm-metric-underline-rep`,[Y.Effort]:`cm-metric-underline-effort`,[Y.Rounds]:`cm-metric-underline-rounds`,[Y.Distance]:`cm-metric-underline-distance`,[Y.Resistance]:`cm-metric-underline-resistance`,[Y.Action]:`cm-metric-underline-action`,[Y.Equipment]:`cm-metric-underline-equipment`};function kme(e){return e?.soundProfileId?`cm-tag-reference-sound`:`cm-tag-reference`}function C2(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=u2(),i=Sz();return r?nu({references:r,defaults:f2(t.doc.toString()),tags:i}).read(n,e.sport).statements:nu({tags:i}).read(n,e.sport).statements}catch{return null}}function Ame(e,t,n,r){let i=[];for(let a of e){if(a.contentFrom===void 0||a.contentTo===void 0)continue;let e=C2(a,r);if(e)for(let o of e){let e=a.startLine+(o.meta?.line??0),s=t===a&&e===n,c=[];for(let e of o.metrics){if(e.type!==Y.Equipment)continue;let t=Xo(e.metadata);if(t?.matched===`whole`||t?.matched==="default")continue;let n=o.metricMeta?.get(e);n&&c.push({from:a.contentFrom+n.startOffset,to:a.contentFrom+n.endOffset})}for(let e of o.metrics){let t=as(e.metadata),n=typeof e.type==`string`&&e.type.startsWith(`tag.`);if(t&&!n)continue;if(e.type===Y.Equipment){let t=Xo(e.metadata);if(t?.matched===`whole`||t?.matched==="default")continue}let l=e.type===Y.Custom&&typeof e.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(e.value.trim()),u=e.type===Y.Choice?e.alternatives[0]?.type:e.type,d=n?kme(t):l?`cm-tag-unresolved`:Ome[u];if(!d)continue;let f=o.metricMeta?.get(e);if(!f)continue;let p=a.contentFrom+f.startOffset,m=a.contentFrom+f.endOffset;if(e.type===Y.Effort){for(let e of c)if(e.from===p&&e.to<m)for(p=e.to;p<m&&/\s/.test(r.doc.sliceString(p,p+1));)p++;else if(e.to===m&&e.from>p)for(m=e.from;m>p&&/\s/.test(r.doc.sliceString(m-1,m));)m--}if(!Number.isFinite(p)||!Number.isFinite(m)||p>=m||p<0||m>r.doc.length)continue;let h=(Xo(e.metadata)?.diagnostics?.length??0)>0,g=s?d:`${d}-dim`,_=h?`${g} cm-metric-unresolved`:g;i.push(Ca.mark({class:_}).range(p,m))}}}return i.sort((e,t)=>e.from-t.from),Ca.set(i)}function w2(e){let{sections:t}=e.field(cM),{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;if(a){let t=e.doc.line(r),i=C2(a,e),c=r-a.startLine,l=i?.findIndex(e=>e.meta?.line===c&&e.metrics.some(t=>{let r=e.metricMeta.get(t),i=n-(a.contentFrom??0);return r&&i>=r.startOffset&&i<=r.endOffset}))??-1;l<0&&(l=i?.findIndex(e=>e.meta?.line===c)??-1),s=l>=0&&i?i[l]:null,o={sectionId:a.id,section:a,statement:s,statementIndex:l,cursorLine:r,docLine:r,lineFrom:t.from,lineTo:t.to,focusedMetric:null,focusedMetricIndex:-1,allStatements:i??[]}}let c=null,l=-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===Y.Sound||t.type===Y.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){c=t,l=e;break}}o&&(o.focusedMetric=c,o.focusedMetricIndex=l);let u=Ame(i,a,r,e);return{focus:o,decos:u}}var T2=Qa.define({create(e){return w2(e)},update(e,t){return t.effects.some(e=>e.is(UM)||e.is(S2))?w2(t.state):!t.docChanged&&t.startState.selection.eq(t.state.selection)?e:w2(t.state)},provide:e=>mo.decorations.from(e,e=>e.decos)});function E2(e){try{return e.field(T2).focus}catch{return null}}function D2(e,t){let n=E2(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=C2(r,e.state)??[],s=[];for(let e of o)for(let t of e.metrics){if(t.type===Y.Sound||t.type===Y.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 jme=po.high(no.of([{key:`Ctrl-ArrowRight`,run:e=>D2(e,1)},{key:`Ctrl-ArrowLeft`,run:e=>D2(e,-1)}])),Mme=[T2,mo.baseTheme({".cm-metric-underline-duration, .cm-metric-underline-duration *":{borderBottom:`2px solid hsl(var(--metric-time))`,color:`hsl(var(--metric-time)) !important`},".cm-metric-underline-rep, .cm-metric-underline-rep *":{borderBottom:`2px solid hsl(var(--metric-rep))`,color:`hsl(var(--metric-rep)) !important`},".cm-metric-underline-effort, .cm-metric-underline-effort *":{borderBottom:`2px solid hsl(var(--metric-effort))`,color:`hsl(var(--metric-effort)) !important`},".cm-metric-underline-rounds, .cm-metric-underline-rounds *":{borderBottom:`2px solid hsl(var(--metric-rounds))`,color:`hsl(var(--metric-rounds)) !important`},".cm-metric-underline-distance, .cm-metric-underline-distance *":{borderBottom:`2px solid hsl(var(--metric-distance))`,color:`hsl(var(--metric-distance)) !important`},".cm-metric-underline-resistance, .cm-metric-underline-resistance *":{borderBottom:`2px solid hsl(var(--metric-resistance))`,color:`hsl(var(--metric-resistance)) !important`},".cm-metric-underline-action, .cm-metric-underline-action *":{borderBottom:`2px solid hsl(var(--metric-action))`,color:`hsl(var(--metric-action)) !important`},".cm-metric-underline-equipment, .cm-metric-underline-equipment *":{borderBottom:`2px solid hsl(var(--metric-equipment))`,color:`hsl(var(--metric-equipment)) !important`},".cm-metric-underline-duration-dim, .cm-metric-underline-duration-dim *":{borderBottom:`1.5px solid hsl(var(--metric-time) / 0.35)`,color:`hsl(var(--metric-time)) !important`},".cm-metric-underline-rep-dim, .cm-metric-underline-rep-dim *":{borderBottom:`1.5px solid hsl(var(--metric-rep) / 0.35)`,color:`hsl(var(--metric-rep)) !important`},".cm-metric-underline-effort-dim, .cm-metric-underline-effort-dim *":{borderBottom:`1.5px solid hsl(var(--metric-effort) / 0.35)`,color:`hsl(var(--metric-effort)) !important`},".cm-metric-underline-rounds-dim, .cm-metric-underline-rounds-dim *":{borderBottom:`1.5px solid hsl(var(--metric-rounds) / 0.35)`,color:`hsl(var(--metric-rounds)) !important`},".cm-metric-underline-distance-dim, .cm-metric-underline-distance-dim *":{borderBottom:`1.5px solid hsl(var(--metric-distance) / 0.35)`,color:`hsl(var(--metric-distance)) !important`},".cm-metric-underline-resistance-dim, .cm-metric-underline-resistance-dim *":{borderBottom:`1.5px solid hsl(var(--metric-resistance) / 0.35)`,color:`hsl(var(--metric-resistance)) !important`},".cm-metric-underline-action-dim, .cm-metric-underline-action-dim *":{borderBottom:`1.5px solid hsl(var(--metric-action) / 0.35)`,color:`hsl(var(--metric-action)) !important`},".cm-metric-underline-equipment-dim, .cm-metric-underline-equipment-dim *":{borderBottom:`1.5px solid hsl(var(--metric-equipment) / 0.35)`,color:`hsl(var(--metric-equipment)) !important`},".cm-metric-unresolved, .cm-metric-unresolved *":{borderBottomStyle:`dashed !important`,borderBottomColor:`hsl(var(--warning)) !important`},".cm-tag-reference, .cm-tag-reference *":{color:`hsl(var(--primary)) !important`,backgroundColor:`hsl(var(--primary) / 0.10)`,borderRadius:`3px`,padding:`0 2px`},".cm-tag-reference-dim, .cm-tag-reference-dim *":{color:`hsl(var(--primary) / 0.72) !important`,backgroundColor:`hsl(var(--primary) / 0.05)`,borderRadius:`3px`,padding:`0 2px`},".cm-tag-unresolved, .cm-tag-unresolved *, .cm-tag-unresolved-dim, .cm-tag-unresolved-dim *":{color:`hsl(var(--warning)) !important`,borderBottom:`1.5px dashed hsl(var(--warning))`,borderRadius:`2px`,padding:`0 1px`},".cm-tag-reference-sound, .cm-tag-reference-sound *":{color:`hsl(var(--metric-action)) !important`,backgroundColor:`hsl(var(--metric-action) / 0.12)`,borderRadius:`3px`,padding:`0 2px`},".cm-tag-reference-sound-dim, .cm-tag-reference-sound-dim *":{color:`hsl(var(--metric-action) / 0.72) !important`,backgroundColor:`hsl(var(--metric-action) / 0.06)`,borderRadius:`3px`,padding:`0 2px`}}),jme,Dme],Nme={frontmatter:120,code:60,widget:220,embed:180},Pme={frontmatter:280,code:140,widget:220,embed:280},Fme=({view:e,widths:t,activeSectionId:n,renderSlot:r,cursorLine:i})=>{let a=(0,K.useRef)(null),o=(0,K.useRef)(null),[s,c]=(0,K.useState)(()=>e?.plugin(NM)?.rects??[]),[l,u]=(0,K.useState)(0),[d,f]=(0,K.useState)({left:0,right:0}),[p,m]=(0,K.useState)(()=>e?.plugin(NM)?.docVersion??0),[h,g]=(0,K.useState)(void 0),[_,v]=(0,K.useState)(void 0);(0,K.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,K.useEffect)(()=>{if(!e)return;let t=e.plugin(NM);if(t)return t.addListener((e,t)=>{c(e),m(t)})},[e]),(0,K.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,K.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(NM)?.rects??[]).filter(e=>{let n=t.get(e.sectionId);return n&&n.effectiveWidth>0});return!e||y.length===0?null:(0,q.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,q.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?Pme:Nme)[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,q.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)})})})},O2={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 Ime(e,t=O2){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 Lme(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 Rme={typeOverrides:{},sectionOverrides:{}};function zme(e,t,n=O2){let[r,i]=(0,K.useReducer)(Lme,Rme);return{widths:(0,K.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=Ime({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,K.useCallback)((e,t)=>i({type:`SET_SECTION_WIDTH`,sectionId:e,width:t}),[]),setTypeWidth:(0,K.useCallback)((e,t)=>i({type:`SET_TYPE_WIDTH`,sectionType:e,width:t}),[]),clearSectionOverride:(0,K.useCallback)(e=>i({type:`CLEAR_SECTION_OVERRIDE`,sectionId:e}),[])}}function Bme(e,t){let{sections:n}=e.state.field(cM);return n.find(e=>e.id===t)}function Vme(e,t){return t.contentFrom===void 0||t.contentTo===void 0?``:e.state.doc.sliceString(t.contentFrom,t.contentTo)}var Hme=({props:e,isActive:t})=>{let n=e.source_url||e.website||``,r=e.title||e.label||`Link`,i=!t;return(0,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,q.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,q.jsx)(`span`,{className:`truncate text-xs font-medium`,children:r})]}),(0,q.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,q.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.`})]})},Ume=({sectionId:e,section:t,view:n,isActive:r})=>{let i=(0,K.useMemo)(()=>t||Bme(n,e),[n,e,t]),a=i?Vme(n,i):``,o=(0,K.useMemo)(()=>gte(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=Iw(t);if(e)return(0,q.jsx)(k2,{videoId:e,title:n,isActive:r})}return(0,q.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,q.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,q.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,q.jsx)(`span`,{className:`text-xs font-medium truncate`,children:n||`Untitled`})]}),(0,q.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mb-3`,children:t}),i.embed.isImage&&(0,q.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=Iw(c);if(e)return(0,q.jsx)(k2,{videoId:e,title:o.title||`YouTube Video`,isActive:r})}return o.source_url||o.website||s===`strava`?(0,q.jsx)(Hme,{props:o,isActive:r}):null},k2=({videoId:e,title:t,isActive:n})=>(0,q.jsxs)(`div`,{className:$(`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,q.jsx)(`div`,{className:`relative flex-1 min-h-0`,children:(0,q.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,q.jsx)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground truncate border-t border-border bg-popover/90`,children:t})]});function Wme(e,t,n,r){let[i,a]=(0,K.useState)([]),[o,s]=(0,K.useState)(!0);return(0,K.useEffect)(()=>{if(!e||!t){a([]),s(!1);return}let r=!1;async function i(){if(Array.isArray(n)){let i=n.filter(n=>n.noteId===e&&n.blockId===t);if(i.length>0&&!r){a(i.sort((e,t)=>t.createdAt-e.createdAt)),s(!1);return}}try{let n=await eR.getNote(e,{projection:`history-detail`,resultSelection:{mode:`all-for-section`,blockId:t}});r||a((n?.extendedResults??[]).sort((e,t)=>t.createdAt-e.createdAt))}catch{r||a([])}finally{r||s(!1)}}return i(),()=>{r=!0}},[e,t,n,r]),{results:i,loading:o}}function Gme(e){let t=e.metrics?.find(e=>e.type===Y.Elapsed);return t?.value!==void 0&&typeof t.value==`number`?t.value:0}function Kme(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+Gme(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 qme(e,t){return(0,K.useMemo)(()=>{if(t===void 0||e.length===0)return null;let n=Kme(e,t);return n.resultCount>0?n:null},[e,t])}function A2(e,t){if(t){t(e.action,e);return}e.action.type===`call`&&e.action.handler()}var Jme=({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,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:()=>A2(e,o),className:$(`flex items-center gap-2 transition-colors active:scale-95`,n===`xs`&&`gap-0 sm:gap-2`,l?$(`bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest`,f):$(`hover:bg-accent hover:text-accent-foreground text-muted-foreground font-medium`,u)),children:[s&&(0,q.jsx)(s,{className:$(`shrink-0`,l?`size-4 fill-current sm:size-3`:`size-4 sm:h-4 sm:w-4`)}),(0,q.jsx)(`span`,{className:a,children:e.label})]}),(0,q.jsx)(`div`,{className:$(`self-stretch`,l?`w-px bg-primary-foreground/20 my-2 sm:my-1`:`w-px bg-border/60`)}),(0,q.jsx)(`button`,{type:`button`,title:t.label,"aria-label":t.label,onClick:()=>A2(t,o),className:$(`flex items-center justify-center transition-colors active:scale-95`,l?$(`bg-primary text-primary-foreground hover:bg-primary/90`,p):$(`hover:bg-accent hover:text-accent-foreground text-muted-foreground`,d)),children:c?(0,q.jsx)(c,{className:$(`shrink-0`,l?`size-4 sm:size-3.5`:`size-4 sm:h-4 sm:w-4`)}):(0,q.jsx)(`span`,{className:`sr-only`,children:t.label})})]})},Yme=new tu;function Xme(e,t){let{sections:n}=e.state.field(cM);return n.find(e=>e.id===t)??null}function Zme(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 Yme.read(n,t.sport).statements}catch{return[]}}function Qme(e,t,n){if(!e.length)return null;let r=n-t.startLine;return e.find(e=>e.meta?.line===r)??null}function $me(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 ehe={[Y.Duration]:{label:`Timer`,icon:`⏱`,color:`bg-metric-time/10 text-metric-time`},[Y.Rep]:{label:`Reps`,icon:`✕`,color:`bg-metric-rep/10 text-metric-rep`},[Y.Effort]:{label:`Exercise`,icon:`🏋`,color:`bg-metric-effort/10 text-metric-effort`},[Y.Rounds]:{label:`Rounds`,icon:`↻`,color:`bg-metric-rounds/10 text-metric-rounds`},[Y.Distance]:{label:`Distance`,icon:`📏`,color:`bg-metric-distance/10 text-metric-distance`},[Y.Resistance]:{label:`Weight`,icon:`⚖`,color:`bg-metric-resistance/10 text-metric-resistance`},[Y.Action]:{label:`Action`,icon:`⚡`,color:`bg-metric-action/10 text-metric-action`}};function the(e){return e.metrics.filter(e=>e.type!==Y.Sound&&e.type!==Y.System).map(e=>{let t=ehe[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 nhe=({summary:e})=>{let t=e.entries.slice(0,3);return(0,q.jsxs)(`div`,{className:`px-3 py-2 border-t border-border/30 bg-muted/20`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1.5`,children:[(0,q.jsx)(dn,{className:`h-3 w-3 text-muted-foreground`}),(0,q.jsx)(`span`,{className:`text-[10px] font-semibold text-muted-foreground uppercase tracking-wider`,children:`History`}),(0,q.jsxs)(`span`,{className:`ml-auto text-[10px] text-muted-foreground`,children:[e.totalHits,`× across `,e.resultCount,` run`,e.resultCount===1?``:`s`]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t.map(e=>(0,q.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,q.jsx)(`span`,{className:`font-mono font-medium text-foreground`,children:$me(e.elapsedMs)}),e.hitCount>1&&(0,q.jsxs)(`span`,{className:`text-muted-foreground`,children:[`×`,e.hitCount]}),(0,q.jsx)(`span`,{className:`text-muted-foreground/60`,children:Mw(new Date(e.createdAt))})]},e.createdAt)),e.entries.length>3&&(0,q.jsxs)(`span`,{className:`text-[10px] text-muted-foreground self-center`,children:[`+`,e.entries.length-3,` more`]})]})]})};function rhe(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 j2(e){return function({className:t}){return K.isValidElement(e)?K.cloneElement(e,{className:$(e.props.className,t)}):(0,q.jsx)(`span`,{className:$(`flex items-center`,t),children:e})}}var M2=({cmd:e,block:t})=>{let[n,r]=(0,K.useState)(!1),i=(0,K.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),a=(0,K.useMemo)(()=>j2(e.icon),[e.icon]),o=(0,K.useMemo)(()=>j2(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),s=(0,K.useMemo)(()=>({id:e.id,label:e.label,icon:a,action:{type:`call`,handler:()=>{e.onClick(t)}}}),[e,t,a]),c=(0,K.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:o,action:{type:`call`,handler:()=>{i()}}}),[e.id,o,i]),l=(0,K.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);return e.onSplitClick?(0,q.jsx)(`div`,{onClick:l,onMouseDown:l,onPointerDown:l,children:(0,q.jsx)(Jme,{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,q.jsxs)(J,{variant:e.primary?`default`:`secondary`,className:$(`scroll-mt-20 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,"data-testid":e.id===`run`||e.id===`play`?Q.EDITOR_START_WORKOUT:void 0,onClick:n=>{l(n),e.onClick(t)},onMouseDown:l,onPointerDown:l,children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:e.icon}),(0,q.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})},N2=({commands:e,section:t,view:n,compact:r})=>{if(!e.length)return null;let i=rhe(n,t);return r?(0,q.jsx)(`div`,{className:`flex flex-row items-center gap-1 p-0 sm:p-1.5`,children:e.map(e=>(0,q.jsx)(M2,{cmd:e,block:i},e.id))}):(0,q.jsx)(`div`,{className:`flex items-center gap-1.5 p-2 border-t border-border/50 flex-wrap`,children:e.map(e=>(0,q.jsx)(M2,{cmd:e,block:i},e.id))})},ihe=({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,K.useMemo)(()=>Xme(n,t),[n,t,u]),{results:h}=Wme(p,t,f,m?.contentId),g=(0,K.useMemo)(()=>m?Zme(n,m):[],[n,m?.id,u]),_=K.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,x=r?i:y??i,S=!(m&&(x===m.startLine||x===m.endLine))&&(r||y!==null),C=(0,K.useMemo)(()=>m&&S?Qme(g,m,x):null,[m,x,S,g]),w=(0,K.useMemo)(()=>C?g.filter(e=>e.meta?.line===C.meta.line).flatMap(the):[],[C,g]),T=qme(h,C?.meta?.line);if(!m)return null;let E=C?.meta?.raw??``,D=x-m.startLine,O=typeof window<`u`&&window.matchMedia(`(max-width: 639px)`).matches?44:28,k;if(c!==void 0){let e=c-l.top-100,t=o+O+4,n=l.height-200;k=Math.max(t,Math.min(e,Math.max(t,n)))}else k=o+O+4;return(0,q.jsxs)(`div`,{className:`relative w-full h-full`,style:{pointerEvents:`none`},children:[(0,q.jsx)(`div`,{className:`absolute inset-x-0 flex items-center justify-end gap-1 px-2 pointer-events-auto
|
|
863
863
|
bg-background/70 backdrop-blur-sm border-l border-b border-border/40 rounded-bl-md`,style:{top:o,height:O},children:(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h.length>0&&(0,q.jsxs)(q.Fragment,{children:[(0,q.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,q.jsx)(b,{className:`h-3 w-3`}),(0,q.jsx)(`span`,{children:h.length})]}),(0,q.jsx)(`div`,{className:`h-3 w-[1px] bg-border/40 mx-0.5`})]}),(0,q.jsx)(N2,{commands:d,section:m,view:n,compact:!0})]})}),S&&(0,q.jsxs)(`div`,{className:`absolute inset-x-0 flex flex-col bg-popover/95 backdrop-blur-md
|
|
864
|
-
border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:k,maxHeight:200},children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,q.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,q.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,q.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,D]}),(0,q.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:E,children:E||(0,q.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,q.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:w.length>0?(0,q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:w.map((e,t)=>(0,q.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,q.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,q.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,q.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),T&&(0,q.jsx)(nhe,{summary:T}),(0,q.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,q.jsx)(N2,{commands:d,section:m,view:n})})]})]})},ahe=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,K.useMemo)(()=>{let t=n.state.field(cM).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,q.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,q.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,q.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,q.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,q.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})},P2=({title:e,ariaLabel:t,onClose:n,children:r,closeButtonClassName:i,floatingClose:a=!1,variant:o=`default`,actions:s,closeLabel:c})=>{let l=o===`minimal`,u=(0,q.jsx)(la,{"aria-label":c?void 0:`Close`,title:c??`Close`,"data-testid":Q.FOCUSED_DIALOG_CLOSE,className:i??`rounded-pill border-0 transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${l?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${c?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`flex h-11 min-w-[44px] items-center justify-center p-2`}`,children:c??(0,q.jsx)(ze,{className:`h-5 w-5`,"aria-hidden":`true`})});return(0,q.jsx)(Le,{open:!0,dismissible:!1,onOpenChange:e=>{e||n()},children:(0,q.jsxs)(g,{initialFocus:`content`,"aria-label":t??e??`Workout`,className:`fixed inset-0 z-[100] m-0 w-screen max-w-none h-dvh max-h-none p-0 gap-0 rounded-none border-0 shadow-none flex flex-col bg-background text-foreground outline-none`,children:[a||l&&!e?(0,q.jsxs)(q.Fragment,{children:[e&&(0,q.jsx)(de,{className:`sr-only`,children:e}),(0,q.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[s,u]})]}):e?(0,q.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${l?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,q.jsx)(de,{className:`text-lg ${l?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s,u]})]}):null,(0,q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:r})]})})},ohe=(0,K.createContext)({updateFromSegments:()=>{},clear:()=>{}}),she=({children:e,chromecastSubscription:t=null})=>(0,q.jsx)(ohe.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),che=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?bpe(e.analyticsSegments):Spe(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 lhe(){if(!(`wakeLock`in navigator))return;let e=navigator.wakeLock;if(!(typeof e!=`object`||!e||!(`request`in e)))return e}function uhe(e){let t=(0,K.useRef)(null);(0,K.useEffect)(()=>{let n=lhe();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 F2(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 I2=``,L2=null,R2=()=>{let e=V1(),[t,n]=(0,K.useState)(e.state),[r,i]=(0,K.useState)(!1);uhe(r);let[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)(null),[l,u]=(0,K.useState)(null),d=(0,K.useRef)(null),f=U1,p=(0,K.useRef)(f.getActiveHandle()),m=(0,K.useRef)(!1),h=(0,K.useCallback)(e=>{let t=p.current;p.current=null,t&&f.dispose(e),yB(null),u(null),c(null),i(!1)},[f]),g=(0,K.useCallback)(async e=>{if(!m.current){m.current=!0;try{let t=Bz.getState().subscriptionManager,n=f.connect(e,t);p.current=n,u(n),c(n.subscription),i(!0),yB(n.transport),n.eventProvider.onEvent(e=>{if(e.name===`clock-command`){let t=ppe(e.data);if(!t){console.warn(`[CastButtonRpc] Dropped malformed clock-command payload`);return}t0(t.runId,t.command)||console.warn(`[CastButtonRpc] Clock command rejected by authority:`,t.command.kind);return}let t=$1(),n=mpe(e.name,t);n&&t&&!t0(t.runId,n)&&console.warn(`[CastButtonRpc] Legacy receiver event rejected by authority:`,e.name)});let r=Bz.getState(),a=che.resolve({viewMode:r.runtime?`track`:`plan`,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:[],selectedBlock:null,documentItems:[]});n.pushInitialWorkbench(a)}finally{m.current=!1}}},[f]),_=(0,K.useRef)(!1),v=(0,K.useCallback)(async()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0);return}if(!(p.current||_.current)&&typeof e.resumeSession==`function`){_.current=!0;try{let t=await e.resumeSession();await g(t)}catch(t){console.warn(`[CastButtonRpc] Session resume failed:`,F2(t)),h(!1),e.endSession()}finally{_.current=!1}}},[e,g,h,f]);(0,K.useEffect)(()=>e.onStateChanged(e=>{n(e),e===`session-active`?(i(!0),v()):e===`ready`||e===`unavailable`?i(!1):e===`session-ended`&&h(!1)}),[e,h,v]),(0,K.useEffect)(()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0)}else e.state===`session-active`&&v()},[e,f]),(0,K.useEffect)(()=>{let e=l?.transport;if(!e)return;let t=()=>{let t=$1(),n=JSON.stringify(t);if(n!==I2||e!==L2){I2=n,L2=e;try{e.send({type:`rpc-clock-snapshot`,snapshot:t})}catch{}}};return t(),e0(t)},[l]),(0,K.useEffect)(()=>{let e=()=>{f.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[f]),(0,K.useEffect)(()=>{let t=d.current;if(!t)return;let n=async()=>{if(y.current===`session-active`){if(b.current)return;o(!0);try{h(!0),e.endSession()}finally{setTimeout(()=>o(!1),2e3)}return}try{let t=await e.startSession();i(!0),await g(t)}catch(e){let t=F2(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):(console.error(`[CastButtonRpc] Cast failed:`,t),CQ({title:`Cast failed`,description:`Unable to start Cast session: ${t}`,variant:`destructive`})),h(!1)}},r=()=>{n()};return t.addEventListener(`click`,r),()=>t.removeEventListener(`click`,r)},[e,g,h]);let y=(0,K.useRef)(t);y.current=t;let b=(0,K.useRef)(a);b.current=a;let x=t===`unavailable`,S=t===`ready`,C=t===`session-active`,w=t===`connecting`,T=r&&C,E=w,D=E||a,O=S||C;return x?(0,q.jsxs)(J,{variant:`ghost`,size:`icon`,"aria-disabled":`true`,className:`min-h-11 min-w-11 opacity-40 cursor-not-allowed`,"aria-label":`Cast to TV (unavailable)`,title:`Cast to TV (unavailable)`,onClick:()=>{CQ({title:`Cast unavailable`,description:`No Cast receiver or device is available in this browser.`})},children:[(0,q.jsx)(Ze,{className:`h-5 w-5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Cast to TV (unavailable)`})]}):(0,q.jsx)(wB,{transport:l?.transport??null,children:(0,q.jsx)(she,{chromecastSubscription:s,children:(0,q.jsxs)(J,{ref:d,variant:`ghost`,size:`icon`,disabled:D,onClick:()=>{},className:$(`transition-all`,T&&`text-signal-positive ring-2 ring-signal-positive/30`,E&&`animate-pulse text-signal-caution`,!O&&`opacity-50`),"aria-label":T?`Stop casting`:`Cast to TV`,title:T?`Stop casting`:E?`Connecting...`:`Cast to TV`,children:[T?(0,q.jsx)(Wt,{className:`h-5 w-5`}):(0,q.jsx)(Ze,{className:`h-5 w-5`}),(0,q.jsx)(`span`,{className:`sr-only`,children:T?`Stop casting`:`Cast to TV`})]})})})};function dhe(){let{isEnabled:e,toggleAudio:t}=OB();return(0,q.jsxs)(J,{variant:`ghost`,size:`icon`,onClick:t,className:`h-11 w-11 min-h-11 min-w-11 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,q.jsx)(v,{className:`h-[1.2rem] w-[1.2rem]`}):(0,q.jsx)(ua,{className:`h-[1.2rem] w-[1.2rem]`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}var fhe=new Map,z2=({block:e,noteContent:t,prepareRun:n,view:r,onClose:i,onCompleteWorkout:a,resultId:o,noteId:s,autoStart:c,onRuntimeReady:l,onRunStarted:u,externalStop:d,adoptRuntime:f,parkOnUnmount:p,onPark:m,RuntimePanelSlot:h=G0,CastButtonSlot:g=R2,AudioToggleSlot:_=dhe})=>{let[v,y]=(0,K.useState)(n?null:e),[b,x]=(0,K.useState)(null),S=(0,K.useRef)(!1),C=(0,K.useCallback)(async()=>{if(!(!n||S.current)){S.current=!0,x(null);try{y(await n())}catch(e){x(e instanceof Error?e.message:String(e))}finally{S.current=!1}}},[n]);(0,K.useEffect)(()=>{C()},[C]);let[w,T]=(0,K.useState)(null),[E,D]=(0,K.useState)(null),{isDebugMode:O}=Ew(),k=(0,K.useMemo)(()=>C0(v??e,t),[v,e,t]).workoutTitle,A=(0,K.useRef)(Date.now()),j=(0,K.useRef)(typeof document<`u`?document.title:`Wod.Wiki`),M=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=k||e.label,n=w!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,M.current!==i&&(M.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:QR()}));let a=$R.consent;n?a&&window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):($R.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,k,w]),(0,K.useEffect)(()=>{let t=j.current,n=A.current,r=k||e.label||e.id;return()=>{let e=Date.now()-n;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:r,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label,k]);let N=(0,K.useRef)(!1),P=(0,K.useRef)(!1),F=(0,K.useRef)(!1),[I,ee]=(0,K.useState)(!1),L=(0,K.useRef)(!1),R=(0,K.useRef)(!1),z=(0,K.useRef)(null),[B,V]=(0,K.useState)(`idle`),[H,U]=(0,K.useState)(null),[te,W]=(0,K.useState)(!1),{collectionItems:ne}=P0(w??[],fhe,null),[re,ie]=(0,K.useState)(new Set),[ae,oe]=(0,K.useState)(new Set),[se,ce]=(0,K.useState)(!1),le=(0,K.useMemo)(()=>ne.filter(e=>{let t=k0(e);return!re.has(t)&&!ae.has(t)}),[ne,re,ae]),ue=w!==null&&!!o&&le.length>0&&!se,de=(0,K.useCallback)(async e=>{let t=await X.getEventsByResult(e);D(t);let{segments:n}=jh(Fy(t).map(e=>Qw(new ts(e))));T(n)},[]),fe=(0,K.useCallback)(async(e,t)=>{if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid value`);if(e.kind!==`value`)throw Error(`Unsupported entry`);if(!o)throw Error(`The saved run is unavailable.`);if(await mB({resultId:o,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.`);await de(o),ie(t=>new Set(t).add(k0(e)))},[o,de]),pe=(0,K.useCallback)(async(e,t)=>{if(await mB({resultId:e,occurrence:t.occurrence,metric:{type:t.metric.type,value:t.metric.value,image:t.metric.image}})===`not-found`)throw Error(`This result entry could not be found.`);await de(e)},[de]),me=(0,K.useCallback)(async(e,t)=>{await gB(e,t),await de(e)},[de]),he=(0,K.useCallback)(async(e,t)=>{if(await hB({resultId:e,occurrence:{blockKey:t.sourceBlockKey,sourceStatementId:t.sourceStatementId},metricType:t.metricType})===`not-found`)throw Error(`This override could not be found.`);await de(e)},[de]),ge=i2(),[_e,ve]=(0,K.useState)(null),ye=(0,K.useCallback)(e=>{oe(t=>new Set(t).add(k0(e)))},[]),be=(0,K.useMemo)(()=>w===null||ue?null:{runId:o?`result:${o}`:`review`,phase:`review`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:null,error:null,saving:!1},[w,ue,o]),xe=async()=>{let e=z.current;if(!e||L.current)return;L.current=!0,R.current=!1,V(`saving`),U(null);let t;try{t=a?.(e.blockId,e.results),await t}catch(e){R.current=!0,U(e instanceof Error?e.message:String(e)),V(`error`),L.current=!1;return}L.current=!1,V(`idle`),W(!0);let{results:n}=e;if(o)try{let e=await X.getEventsByResult(o);e.length>0&&D(e)}catch{}if(n.logs&&n.logs.length>0)try{let{segments:e}=jh(n.logs,n.startTime);T(e)}catch{T([])}else n.completed?T([]):F.current&&i()},Se=(0,K.useCallback)(()=>{N.current=!0,u?.()},[u]),Ce=()=>{if(L.current||R.current){F.current=!0;return}if(w!==null||P.current||!N.current){i();return}!I&&!d&&ype()||(F.current=!0,ee(!0))},we=(0,K.useRef)(Ce);we.current=Ce,W1(be,(0,K.useCallback)(e=>e.kind===`dismiss`&&(we.current(),!0),[]),20,{keyboard:!0});let Te=(e,t)=>{P.current||(P.current=!0,z.current={blockId:e,results:t},xe())},Ee=(0,K.useMemo)(()=>{if(w===null)return null;let e=o??`standalone-review`,t=E&&E.length>0?E:w.map((t,n)=>{let r=t.context,i=t.absoluteStartTime??Date.now(),a=t.endTime!==void 0&&t.startTime!==void 0&&t.endTime>t.startTime?t.endTime-t.startTime:t.elapsed&&t.elapsed>0?t.elapsed:t.duration??0,o=i+Math.max(0,a*1e3);return{id:`${e}:${t.id??n}`,grain:`event`,outputType:String(r?.outputType??t.type??`segment`),sourceBlockKey:String(r?.sourceBlockKey??t.name??`segment-${n}`),...typeof r?.sourceStatementId==`number`?{sourceStatementId:r.sourceStatementId}:{},stackLevel:t.depth,completionReason:typeof r?.completionReason==`string`?r.completionReason:void 0,timestamp:i,timeSpan:{started:i,ended:o},metrics:t.metrics?Array.from(t.metrics):[]}}),n=t[0]?.timeSpan?.started??Date.now(),r=z.current?.results.duration;return{parsed:{family:`find`,raw:`:session{result:${e}}`,target:`session`,filters:[{key:`result`,negate:!1,values:[{value:e,wildcard:!1}]}]},runs:[{resultId:e,noteId:``,timestamp:n,...typeof r==`number`?{durationMs:r}:{},events:t}]}},[w,E,o]),G=(0,K.useMemo)(()=>Ee?.runs?.[0],[Ee]),De=G?.summary?.blockContentId,{prHighlights:Oe}=yk(G,De,sJ,!!(G&&o)),ke=B===`idle`?null:(0,q.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:[B===`saving`&&(0,q.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),B===`error`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,H?` — ${H}`:``]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>void xe(),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 v?w===null?(0,q.jsx)(P2,{onClose:Ce,title:k??`Workout`,ariaLabel:`Workout`,closeLabel:`Exit`,actions:(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,onClick:Ce,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,q.jsx)(g,{}),(0,q.jsx)(_,{})]}),children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,"data-testid":Q.TIMER_FULLSCREEN_OVERLAY,children:[ke,b?(0,q.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,b]}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void C(),children:`Retry starting workout`})]}):v?null:(0,q.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,q.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,q.jsx)(h,{block:v,resultId:o,noteId:s,noteContent:t,view:r,onClose:Ce,onComplete:Te,isExpanded:!0,autoStart:c,onRuntimeReady:l,onRunStarted:Se,externalStop:d||I,adoptRuntime:f,parkOnUnmount:p,onPark:m})})]})}):(0,q.jsx)(P2,{title:`Workout Complete`,onClose:Ce,actions:(0,q.jsxs)(q.Fragment,{children:[te&&(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,q.jsx)(g,{}),(0,q.jsx)(_,{})]}),children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,"data-testid":Q.TIMER_FULLSCREEN_OVERLAY,children:[ke,(0,q.jsx)(`div`,{className:`min-h-0 flex-1`,children:ue?(0,q.jsx)(z0,{mode:`post-run`,items:le,onSave:fe,onSkip:ye,onClose:()=>ce(!0),runId:o?`result:${o}`:void 0,className:`mx-auto max-w-md`}):G&&o?(0,q.jsxs)(`div`,{className:`h-full space-y-5 overflow-auto p-4 sm:p-6`,children:[(0,q.jsx)(jD,{run:G,prHighlights:Oe,onCaptureRpe:me,onOpenResults:ge?e=>{i(),ge(AH(e.resultId))}:void 0,onAddToDashboard:e=>ve(e)}),(0,q.jsx)(RO,{run:G,prHighlights:Oe,tableTestId:Q.OUTPUT_STATEMENTS_TABLE,showCustomSummariesStrip:!0,onEditMetric:pe,onClearMetric:he,onCaptureRpe:me,onAddToDashboard:e=>ve(e)}),(0,q.jsx)(o2,{open:_e!==null,onOpenChange:e=>{e||ve(null)},context:_e})]}):Ee?(0,q.jsx)(`div`,{className:`h-full overflow-auto p-4 sm:p-6`,children:(0,q.jsx)(hk,{result:Ee,filter:O?``:void 0})}):null})]})}):(0,q.jsx)(P2,{title:`Starting workout`,onClose:i,children:b?(0,q.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,b,` Your draft is kept.`]}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void C(),children:`Retry start`})]}):(0,q.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},phe={play:!0,"add-to-today":!0,schedule:!0},mhe=`log`;function hhe(e,t){return e.filter(e=>e.id===mhe?t===`log`:!phe[e.id]||t===`run`)}function ghe(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:{}}}var B2=({cmd:e,block:t})=>{let[n,r]=(0,K.useState)(!1),[i,a]=(0,K.useState)(!1),o=(0,K.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,K.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,K.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]),l=i?e.successIcon??e.icon:e.icon;if(!e.onSplitClick)return(0,q.jsxs)(J,{variant:e.primary?`default`:`outline`,className:$(`pointer-events-auto scroll-mt-20 h-7 max-lg:h-11 max-lg:min-h-[44px] py-0 rounded-[6px] text-xs font-medium shadow-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1`,e.iconOnly?`w-7 max-lg:w-11 max-lg:min-w-[44px] px-0`:`px-2.5 max-lg:px-3.5 gap-1.5`,e.primary?`bg-primary text-primary-foreground hover:bg-primary/90 border border-primary/90`:`bg-card/85 text-muted-foreground hover:bg-card hover:text-foreground border border-border/80`,i&&`text-success bg-success/15 border-success/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`||e.id===`play`?Q.EDITOR_START_WORKOUT:void 0,onClick:e=>{c(e),s()},onMouseDown:c,onPointerDown:c,children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:l}),!e.iconOnly&&(0,q.jsx)(`span`,{children:e.label})]});let u=n?e.splitSuccessIcon??e.splitIcon:e.splitIcon;return(0,q.jsxs)(`div`,{className:$(`pointer-events-auto scroll-mt-20 inline-flex items-stretch overflow-hidden rounded-[6px] border shadow-none`,e.primary?`border-primary/90 bg-primary`:`border-border/80 bg-card/85`),onMouseDown:c,onPointerDown:c,children:[(0,q.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:e=>{c(e),s()},className:$(`h-7 max-lg:h-11 max-lg:min-h-[44px] inline-flex items-center gap-1.5 px-2.5 max-lg:px-3 text-xs font-medium transition-colors cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`,e.primary?`text-primary-foreground hover:bg-primary/90`:`text-muted-foreground hover:bg-card hover:text-foreground`,i&&`text-success bg-success/10`),children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:l}),(0,q.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]}),(0,q.jsx)(`span`,{"aria-hidden":`true`,className:$(`w-px self-stretch`,e.primary?`bg-primary-foreground/25`:`bg-border/70`)}),(0,q.jsx)(`button`,{type:`button`,title:`Copy link`,"aria-label":`Copy link`,onClick:e=>{c(e),o()},className:$(`h-7 w-7 max-lg:h-11 max-lg:w-11 max-lg:min-h-[44px] max-lg:min-w-[44px] inline-flex items-center justify-center transition-colors cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`,e.primary?`text-primary-foreground hover:bg-primary/90`:`text-muted-foreground hover:bg-card hover:text-foreground`,n&&`text-success bg-success/10`),children:(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:u})})]})};function _he(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.sectionId!==i.sectionId||r.top!==i.top||r.height!==i.height||r.firstLineHeight!==i.firstLineHeight||r.type!==i.type)return!1}return!0}var vhe=({view:e,commands:t})=>{let[n,r]=(0,K.useState)(()=>e?.plugin(NM)?.rects??[]),[i,a]=(0,K.useState)(0),[o,s]=(0,K.useState)(()=>e?.dom?.clientWidth??640),[c,l]=(0,K.useState)(null);(0,K.useEffect)(()=>{if(!e)return;let t=e.dom,n=()=>{let e=t?.clientWidth??640;e>0&&s(e)};if(n(),typeof ResizeObserver>`u`||!t)return;let r=new ResizeObserver(n);return r.observe(t),()=>r.disconnect()},[e]),(0,K.useEffect)(()=>{if(!c)return;let e=e=>{e.target?.closest(`[data-inline-cmd-overflow-root="true"]`)||l(null)},t=e=>{e.key===`Escape`&&l(null)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]),(0,K.useEffect)(()=>{if(!e)return;let t=e.plugin(NM);if(!t)return;let n=t=>{!t.some(e=>e.type===`time`||e.type===`log`)&&(e.state.field(cM,!1)?.sections.some(e=>e.type===`time`||e.type===`log`)??!1)||r(e=>_he(e,t)?e:[...t])};return n(t.rects),t.addListener(e=>n(e))},[e]),(0,K.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 u=e?e.plugin(NM):null,d=(n.length>0?n:u?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(d.length===0||!e)return null;let{sections:f}=e.state.field(cM),p=new Map(f.map(e=>[e.id,e])),m=(e.dom?.offsetTop??0)+(e.scrollDOM?.offsetTop??0)+(e.contentDOM?.offsetTop??0),h=o>0&&o<520;return(0,q.jsx)(q.Fragment,{children:d.map(n=>{let r=p.get(n.sectionId);if(!r)return null;let a=ghe(e,r),o=hhe(t,hs(r.type));if(o.length===0)return null;let s=h?o.find(e=>e.primary)??o[0]:null,u=h&&s?o.filter(e=>e!==s):[],d=c===n.sectionId;return(0,q.jsx)(`div`,{className:`absolute right-2.5 z-20 flex items-center gap-1.5 pointer-events-none`,style:{top:m+n.top-i,height:Math.max(36,Math.min(n.firstLineHeight??40,64))},children:!h||!s?o.map(e=>(0,q.jsx)(B2,{cmd:e,block:a},e.id)):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(B2,{cmd:s,block:a}),u.length>0&&(0,q.jsxs)(`div`,{className:`relative pointer-events-auto`,"data-inline-cmd-overflow-root":`true`,children:[(0,q.jsx)(J,{variant:`outline`,type:`button`,"data-testid":Q.EDITOR_OVERFLOW_ACTIONS_BTN,"aria-label":`More block actions`,"aria-expanded":d,className:`h-7 w-7 max-lg:h-11 max-lg:w-11 max-lg:min-h-[44px] max-lg:min-w-[44px] rounded-[6px] px-0 py-0 text-muted-foreground hover:text-foreground bg-card/85 hover:bg-card border border-border/80 shadow-none`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),l(e=>e===n.sectionId?null:n.sectionId)},children:(0,q.jsx)(Ar,{className:`h-4 w-4`,"aria-hidden":`true`})}),d&&(0,q.jsx)(`div`,{role:`menu`,"aria-label":`Block actions`,"data-testid":Q.EDITOR_OVERFLOW_ACTIONS_MENU,className:`absolute right-0 top-full mt-1 z-40 min-w-[168px] rounded-[6px] border border-border bg-card p-1 shadow-md flex flex-col gap-0.5`,children:u.map(e=>(0,q.jsxs)(K.Fragment,{children:[(0,q.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`w-full min-h-[36px] max-lg:min-h-[44px] px-2.5 py-1.5 rounded-[4px] flex items-center gap-2 text-left text-xs font-medium text-foreground hover:bg-muted transition-colors`,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(null),e.onClick(a)},children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 text-muted-foreground`,children:e.icon}),(0,q.jsx)(`span`,{children:e.label})]}),e.onSplitClick&&(0,q.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`w-full min-h-[36px] max-lg:min-h-[44px] px-2.5 py-1.5 rounded-[4px] flex items-center gap-2 text-left text-xs font-medium text-foreground hover:bg-muted transition-colors`,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(null),e.onSplitClick?.(a)},children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 text-muted-foreground`,children:e.splitIcon??e.icon}),(0,q.jsx)(`span`,{children:`Copy share link`})]})]},e.id))})]})]})},n.sectionId)})})},yhe=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=CB(),a=(0,K.useRef)(``);return(0,K.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(`
|
|
864
|
+
border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:k,maxHeight:200},children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,q.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,q.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,q.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,D]}),(0,q.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:E,children:E||(0,q.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,q.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:w.length>0?(0,q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:w.map((e,t)=>(0,q.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,q.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,q.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,q.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),T&&(0,q.jsx)(nhe,{summary:T}),(0,q.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,q.jsx)(N2,{commands:d,section:m,view:n})})]})]})},ahe=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,K.useMemo)(()=>{let t=n.state.field(cM).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,q.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,q.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,q.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,q.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,q.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})},P2=({title:e,ariaLabel:t,onClose:n,children:r,closeButtonClassName:i,floatingClose:a=!1,variant:o=`default`,actions:s,closeLabel:c})=>{let l=o===`minimal`,u=(0,q.jsx)(la,{"aria-label":c?void 0:`Close`,title:c??`Close`,"data-testid":Q.FOCUSED_DIALOG_CLOSE,className:i??`rounded-pill border-0 transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${l?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${c?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`flex h-11 min-w-[44px] items-center justify-center p-2`}`,children:c??(0,q.jsx)(ze,{className:`h-5 w-5`,"aria-hidden":`true`})});return(0,q.jsx)(Le,{open:!0,dismissible:!1,onOpenChange:e=>{e||n()},children:(0,q.jsxs)(g,{initialFocus:`content`,"aria-label":t??e??`Workout`,className:`fixed inset-0 z-[100] m-0 w-screen max-w-none h-dvh max-h-none p-0 gap-0 rounded-none border-0 shadow-none flex flex-col bg-background text-foreground outline-none`,children:[a||l&&!e?(0,q.jsxs)(q.Fragment,{children:[e&&(0,q.jsx)(de,{className:`sr-only`,children:e}),(0,q.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[s,u]})]}):e?(0,q.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${l?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,q.jsx)(de,{className:`text-lg ${l?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s,u]})]}):null,(0,q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:r})]})})},ohe=(0,K.createContext)({updateFromSegments:()=>{},clear:()=>{}}),she=({children:e,chromecastSubscription:t=null})=>(0,q.jsx)(ohe.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),che=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?bpe(e.analyticsSegments):Spe(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 lhe(){if(!(`wakeLock`in navigator))return;let e=navigator.wakeLock;if(!(typeof e!=`object`||!e||!(`request`in e)))return e}function uhe(e){let t=(0,K.useRef)(null);(0,K.useEffect)(()=>{let n=lhe();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 F2(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 I2=``,L2=null,R2=()=>{let e=V1(),[t,n]=(0,K.useState)(e.state),[r,i]=(0,K.useState)(!1);uhe(r);let[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)(null),[l,u]=(0,K.useState)(null),d=(0,K.useRef)(null),f=U1,p=(0,K.useRef)(f.getActiveHandle()),m=(0,K.useRef)(!1),h=(0,K.useCallback)(e=>{let t=p.current;p.current=null,t&&f.dispose(e),yB(null),u(null),c(null),i(!1)},[f]),g=(0,K.useCallback)(async e=>{if(!m.current){m.current=!0;try{let t=Bz.getState().subscriptionManager,n=f.connect(e,t);p.current=n,u(n),c(n.subscription),i(!0),yB(n.transport),n.eventProvider.onEvent(e=>{if(e.name===`clock-command`){let t=ppe(e.data);if(!t){console.warn(`[CastButtonRpc] Dropped malformed clock-command payload`);return}t0(t.runId,t.command)||console.warn(`[CastButtonRpc] Clock command rejected by authority:`,t.command.kind);return}let t=$1(),n=mpe(e.name,t);n&&t&&!t0(t.runId,n)&&console.warn(`[CastButtonRpc] Legacy receiver event rejected by authority:`,e.name)});let r=Bz.getState(),a=che.resolve({viewMode:r.runtime?`track`:`plan`,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:[],selectedBlock:null,documentItems:[]});n.pushInitialWorkbench(a)}finally{m.current=!1}}},[f]),_=(0,K.useRef)(!1),v=(0,K.useCallback)(async()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0);return}if(!(p.current||_.current)&&typeof e.resumeSession==`function`){_.current=!0;try{let t=await e.resumeSession();await g(t)}catch(t){console.warn(`[CastButtonRpc] Session resume failed:`,F2(t)),h(!1),e.endSession()}finally{_.current=!1}}},[e,g,h,f]);(0,K.useEffect)(()=>e.onStateChanged(e=>{n(e),e===`session-active`?(i(!0),v()):e===`ready`||e===`unavailable`?i(!1):e===`session-ended`&&h(!1)}),[e,h,v]),(0,K.useEffect)(()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0)}else e.state===`session-active`&&v()},[e,f]),(0,K.useEffect)(()=>{let e=l?.transport;if(!e)return;let t=()=>{let t=$1(),n=JSON.stringify(t);if(n!==I2||e!==L2){I2=n,L2=e;try{e.send({type:`rpc-clock-snapshot`,snapshot:t})}catch{}}};return t(),e0(t)},[l]),(0,K.useEffect)(()=>{let e=()=>{f.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[f]),(0,K.useEffect)(()=>{let t=d.current;if(!t)return;let n=async()=>{if(y.current===`session-active`){if(b.current)return;o(!0);try{h(!0),e.endSession()}finally{setTimeout(()=>o(!1),2e3)}return}try{let t=await e.startSession();i(!0),await g(t)}catch(e){let t=F2(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):(console.error(`[CastButtonRpc] Cast failed:`,t),CQ({title:`Cast failed`,description:`Unable to start Cast session: ${t}`,variant:`destructive`})),h(!1)}},r=()=>{n()};return t.addEventListener(`click`,r),()=>t.removeEventListener(`click`,r)},[e,g,h]);let y=(0,K.useRef)(t);y.current=t;let b=(0,K.useRef)(a);b.current=a;let x=t===`unavailable`,S=t===`ready`,C=t===`session-active`,w=t===`connecting`,T=r&&C,E=w,D=E||a,O=S||C;return x?(0,q.jsxs)(J,{variant:`ghost`,size:`icon`,"aria-disabled":`true`,className:`min-h-11 min-w-11 opacity-40 cursor-not-allowed`,"aria-label":`Cast to TV (unavailable)`,title:`Cast to TV (unavailable)`,onClick:()=>{CQ({title:`Cast unavailable`,description:`No Cast receiver or device is available in this browser.`})},children:[(0,q.jsx)(Ze,{className:`h-5 w-5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Cast to TV (unavailable)`})]}):(0,q.jsx)(wB,{transport:l?.transport??null,children:(0,q.jsx)(she,{chromecastSubscription:s,children:(0,q.jsxs)(J,{ref:d,variant:`ghost`,size:`icon`,disabled:D,onClick:()=>{},className:$(`transition-all`,T&&`text-signal-positive ring-2 ring-signal-positive/30`,E&&`animate-pulse text-signal-caution`,!O&&`opacity-50`),"aria-label":T?`Stop casting`:`Cast to TV`,title:T?`Stop casting`:E?`Connecting...`:`Cast to TV`,children:[T?(0,q.jsx)(Wt,{className:`h-5 w-5`}):(0,q.jsx)(Ze,{className:`h-5 w-5`}),(0,q.jsx)(`span`,{className:`sr-only`,children:T?`Stop casting`:`Cast to TV`})]})})})};function dhe(){let{isEnabled:e,toggleAudio:t}=OB();return(0,q.jsxs)(J,{variant:`ghost`,size:`icon`,onClick:t,className:`h-11 w-11 min-h-11 min-w-11 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,q.jsx)(v,{className:`h-[1.2rem] w-[1.2rem]`}):(0,q.jsx)(ua,{className:`h-[1.2rem] w-[1.2rem]`}),(0,q.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}var fhe=new Map,z2=({block:e,noteContent:t,prepareRun:n,view:r,onClose:i,onCompleteWorkout:a,resultId:o,noteId:s,autoStart:c,onRuntimeReady:l,onRunStarted:u,externalStop:d,adoptRuntime:f,parkOnUnmount:p,onPark:m,RuntimePanelSlot:h=G0,CastButtonSlot:g=R2,AudioToggleSlot:_=dhe})=>{let[v,y]=(0,K.useState)(n?null:e),[b,x]=(0,K.useState)(null),S=(0,K.useRef)(!1),C=(0,K.useCallback)(async()=>{if(!(!n||S.current)){S.current=!0,x(null);try{y(await n())}catch(e){x(e instanceof Error?e.message:String(e))}finally{S.current=!1}}},[n]);(0,K.useEffect)(()=>{C()},[C]);let[w,T]=(0,K.useState)(null),[E,D]=(0,K.useState)(null),{isDebugMode:O}=Ew(),k=(0,K.useMemo)(()=>C0(v??e,t),[v,e,t]).workoutTitle,A=(0,K.useRef)(Date.now()),j=(0,K.useRef)(typeof document<`u`?document.title:`Wod.Wiki`),M=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=k||e.label,n=w!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,M.current!==i&&(M.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:QR()}));let a=$R.consent;n?a&&window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):($R.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,k,w]),(0,K.useEffect)(()=>{let t=j.current,n=A.current,r=k||e.label||e.id;return()=>{let e=Date.now()-n;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:r,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label,k]);let N=(0,K.useRef)(!1),P=(0,K.useRef)(!1),F=(0,K.useRef)(!1),[I,ee]=(0,K.useState)(!1),L=(0,K.useRef)(!1),R=(0,K.useRef)(!1),z=(0,K.useRef)(null),[B,V]=(0,K.useState)(`idle`),[H,U]=(0,K.useState)(null),[te,W]=(0,K.useState)(!1),{collectionItems:ne}=P0(w??[],fhe,null),[re,ie]=(0,K.useState)(new Set),[ae,oe]=(0,K.useState)(new Set),[se,ce]=(0,K.useState)(!1),le=(0,K.useMemo)(()=>ne.filter(e=>{let t=k0(e);return!re.has(t)&&!ae.has(t)}),[ne,re,ae]),ue=w!==null&&!!o&&le.length>0&&!se,de=(0,K.useCallback)(async e=>{let t=await X.getEventsByResult(e);D(t);let{segments:n}=jh(Fy(t).map(e=>Qw(new ts(e))));T(n)},[]),fe=(0,K.useCallback)(async(e,t)=>{if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid value`);if(e.kind!==`value`)throw Error(`Unsupported entry`);if(!o)throw Error(`The saved run is unavailable.`);if(await mB({resultId:o,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.`);await de(o),ie(t=>new Set(t).add(k0(e)))},[o,de]),pe=(0,K.useCallback)(async(e,t)=>{if(await mB({resultId:e,occurrence:t.occurrence,metric:{type:t.metric.type,value:t.metric.value,image:t.metric.image}})===`not-found`)throw Error(`This result entry could not be found.`);await de(e)},[de]),me=(0,K.useCallback)(async(e,t)=>{await gB(e,t),await de(e)},[de]),he=(0,K.useCallback)(async(e,t)=>{if(await hB({resultId:e,occurrence:{blockKey:t.sourceBlockKey,sourceStatementId:t.sourceStatementId},metricType:t.metricType})===`not-found`)throw Error(`This override could not be found.`);await de(e)},[de]),ge=i2(),[_e,ve]=(0,K.useState)(null),ye=(0,K.useCallback)(e=>{oe(t=>new Set(t).add(k0(e)))},[]),be=(0,K.useMemo)(()=>w===null||ue?null:{runId:o?`result:${o}`:`review`,phase:`review`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:null,error:null,saving:!1},[w,ue,o]),xe=async()=>{let e=z.current;if(!e||L.current)return;L.current=!0,R.current=!1,V(`saving`),U(null);let t;try{t=a?.(e.blockId,e.results),await t}catch(e){R.current=!0,U(e instanceof Error?e.message:String(e)),V(`error`),L.current=!1;return}L.current=!1,V(`idle`),a&&W(!0);let{results:n}=e;if(o)try{let e=await X.getEventsByResult(o);e.length>0&&D(e)}catch{}if(n.logs&&n.logs.length>0)try{let{segments:e}=jh(n.logs,n.startTime);T(e)}catch{T([])}else n.completed?T([]):F.current&&i()},Se=(0,K.useCallback)(()=>{N.current=!0,u?.()},[u]),Ce=()=>{if(L.current||R.current){F.current=!0;return}if(w!==null||P.current||!N.current){i();return}!I&&!d&&ype()||(F.current=!0,ee(!0))},we=(0,K.useRef)(Ce);we.current=Ce,W1(be,(0,K.useCallback)(e=>e.kind===`dismiss`&&(we.current(),!0),[]),20,{keyboard:!0});let Te=(e,t)=>{P.current||(P.current=!0,z.current={blockId:e,results:t},xe())},Ee=(0,K.useMemo)(()=>{if(w===null)return null;let e=o??`standalone-review`,t=E&&E.length>0?E:w.map((t,n)=>{let r=t.context,i=t.absoluteStartTime??Date.now(),a=t.endTime!==void 0&&t.startTime!==void 0&&t.endTime>t.startTime?t.endTime-t.startTime:t.elapsed&&t.elapsed>0?t.elapsed:t.duration??0,o=i+Math.max(0,a*1e3);return{id:`${e}:${t.id??n}`,grain:`event`,outputType:String(r?.outputType??t.type??`segment`),sourceBlockKey:String(r?.sourceBlockKey??t.name??`segment-${n}`),...typeof r?.sourceStatementId==`number`?{sourceStatementId:r.sourceStatementId}:{},stackLevel:t.depth,completionReason:typeof r?.completionReason==`string`?r.completionReason:void 0,timestamp:i,timeSpan:{started:i,ended:o},metrics:t.metrics?Array.from(t.metrics):[]}}),n=t[0]?.timeSpan?.started??Date.now(),r=z.current?.results.duration;return{parsed:{family:`find`,raw:`:session{result:${e}}`,target:`session`,filters:[{key:`result`,negate:!1,values:[{value:e,wildcard:!1}]}]},runs:[{resultId:e,noteId:``,timestamp:n,...typeof r==`number`?{durationMs:r}:{},events:t}]}},[w,E,o]),G=(0,K.useMemo)(()=>Ee?.runs?.[0],[Ee]),De=G?.summary?.blockContentId,{prHighlights:Oe}=yk(G,De,sJ,!!(G&&o)),ke=B===`idle`?null:(0,q.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:[B===`saving`&&(0,q.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),B===`error`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,H?` — ${H}`:``]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>void xe(),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 v?w===null?(0,q.jsx)(P2,{onClose:Ce,title:k??`Workout`,ariaLabel:`Workout`,closeLabel:`Exit`,actions:(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,onClick:Ce,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,q.jsx)(g,{}),(0,q.jsx)(_,{})]}),children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,"data-testid":Q.TIMER_FULLSCREEN_OVERLAY,children:[ke,b?(0,q.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,b]}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void C(),children:`Retry starting workout`})]}):v?null:(0,q.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,q.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,q.jsx)(h,{block:v,resultId:o,noteId:s,noteContent:t,view:r,onClose:Ce,onComplete:Te,isExpanded:!0,autoStart:c,onRuntimeReady:l,onRunStarted:Se,externalStop:d||I,adoptRuntime:f,parkOnUnmount:p,onPark:m})})]})}):(0,q.jsx)(P2,{title:`Workout Complete`,onClose:Ce,actions:(0,q.jsxs)(q.Fragment,{children:[te&&(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,q.jsx)(g,{}),(0,q.jsx)(_,{})]}),children:(0,q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,"data-testid":Q.TIMER_FULLSCREEN_OVERLAY,children:[ke,(0,q.jsx)(`div`,{className:`min-h-0 flex-1`,children:ue?(0,q.jsx)(z0,{mode:`post-run`,items:le,onSave:fe,onSkip:ye,onClose:()=>ce(!0),runId:o?`result:${o}`:void 0,className:`mx-auto max-w-md`}):G&&o?(0,q.jsxs)(`div`,{className:`h-full space-y-5 overflow-auto p-4 sm:p-6`,children:[(0,q.jsx)(jD,{run:G,prHighlights:Oe,onCaptureRpe:me,onOpenResults:ge?e=>{i(),ge(AH(e.resultId))}:void 0,onAddToDashboard:e=>ve(e)}),(0,q.jsx)(RO,{run:G,prHighlights:Oe,tableTestId:Q.OUTPUT_STATEMENTS_TABLE,showCustomSummariesStrip:!0,onEditMetric:pe,onClearMetric:he,onCaptureRpe:me,onAddToDashboard:e=>ve(e)}),(0,q.jsx)(o2,{open:_e!==null,onOpenChange:e=>{e||ve(null)},context:_e})]}):Ee?(0,q.jsx)(`div`,{className:`h-full overflow-auto p-4 sm:p-6`,children:(0,q.jsx)(hk,{result:Ee,filter:O?``:void 0})}):null})]})}):(0,q.jsx)(P2,{title:`Starting workout`,onClose:i,children:b?(0,q.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,b,` Your draft is kept.`]}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void C(),children:`Retry start`})]}):(0,q.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},phe={play:!0,"add-to-today":!0,schedule:!0},mhe=`log`;function hhe(e,t){return e.filter(e=>e.id===mhe?t===`log`:!phe[e.id]||t===`run`)}function ghe(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:{}}}var B2=({cmd:e,block:t})=>{let[n,r]=(0,K.useState)(!1),[i,a]=(0,K.useState)(!1),o=(0,K.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,K.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,K.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]),l=i?e.successIcon??e.icon:e.icon;if(!e.onSplitClick)return(0,q.jsxs)(J,{variant:e.primary?`default`:`outline`,className:$(`pointer-events-auto scroll-mt-20 h-7 max-lg:h-11 max-lg:min-h-[44px] py-0 rounded-[6px] text-xs font-medium shadow-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1`,e.iconOnly?`w-7 max-lg:w-11 max-lg:min-w-[44px] px-0`:`px-2.5 max-lg:px-3.5 gap-1.5`,e.primary?`bg-primary text-primary-foreground hover:bg-primary/90 border border-primary/90`:`bg-card/85 text-muted-foreground hover:bg-card hover:text-foreground border border-border/80`,i&&`text-success bg-success/15 border-success/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`||e.id===`play`?Q.EDITOR_START_WORKOUT:void 0,onClick:e=>{c(e),s()},onMouseDown:c,onPointerDown:c,children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:l}),!e.iconOnly&&(0,q.jsx)(`span`,{children:e.label})]});let u=n?e.splitSuccessIcon??e.splitIcon:e.splitIcon;return(0,q.jsxs)(`div`,{className:$(`pointer-events-auto scroll-mt-20 inline-flex items-stretch overflow-hidden rounded-[6px] border shadow-none`,e.primary?`border-primary/90 bg-primary`:`border-border/80 bg-card/85`),onMouseDown:c,onPointerDown:c,children:[(0,q.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:e=>{c(e),s()},className:$(`h-7 max-lg:h-11 max-lg:min-h-[44px] inline-flex items-center gap-1.5 px-2.5 max-lg:px-3 text-xs font-medium transition-colors cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`,e.primary?`text-primary-foreground hover:bg-primary/90`:`text-muted-foreground hover:bg-card hover:text-foreground`,i&&`text-success bg-success/10`),children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:l}),(0,q.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]}),(0,q.jsx)(`span`,{"aria-hidden":`true`,className:$(`w-px self-stretch`,e.primary?`bg-primary-foreground/25`:`bg-border/70`)}),(0,q.jsx)(`button`,{type:`button`,title:`Copy link`,"aria-label":`Copy link`,onClick:e=>{c(e),o()},className:$(`h-7 w-7 max-lg:h-11 max-lg:w-11 max-lg:min-h-[44px] max-lg:min-w-[44px] inline-flex items-center justify-center transition-colors cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`,e.primary?`text-primary-foreground hover:bg-primary/90`:`text-muted-foreground hover:bg-card hover:text-foreground`,n&&`text-success bg-success/10`),children:(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 shrink-0`,children:u})})]})};function _he(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.sectionId!==i.sectionId||r.top!==i.top||r.height!==i.height||r.firstLineHeight!==i.firstLineHeight||r.type!==i.type)return!1}return!0}var vhe=({view:e,commands:t})=>{let[n,r]=(0,K.useState)(()=>e?.plugin(NM)?.rects??[]),[i,a]=(0,K.useState)(0),[o,s]=(0,K.useState)(()=>e?.dom?.clientWidth??640),[c,l]=(0,K.useState)(null);(0,K.useEffect)(()=>{if(!e)return;let t=e.dom,n=()=>{let e=t?.clientWidth??640;e>0&&s(e)};if(n(),typeof ResizeObserver>`u`||!t)return;let r=new ResizeObserver(n);return r.observe(t),()=>r.disconnect()},[e]),(0,K.useEffect)(()=>{if(!c)return;let e=e=>{e.target?.closest(`[data-inline-cmd-overflow-root="true"]`)||l(null)},t=e=>{e.key===`Escape`&&l(null)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]),(0,K.useEffect)(()=>{if(!e)return;let t=e.plugin(NM);if(!t)return;let n=t=>{!t.some(e=>e.type===`time`||e.type===`log`)&&(e.state.field(cM,!1)?.sections.some(e=>e.type===`time`||e.type===`log`)??!1)||r(e=>_he(e,t)?e:[...t])};return n(t.rects),t.addListener(e=>n(e))},[e]),(0,K.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 u=e?e.plugin(NM):null,d=(n.length>0?n:u?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(d.length===0||!e)return null;let{sections:f}=e.state.field(cM),p=new Map(f.map(e=>[e.id,e])),m=(e.dom?.offsetTop??0)+(e.scrollDOM?.offsetTop??0)+(e.contentDOM?.offsetTop??0),h=o>0&&o<520;return(0,q.jsx)(q.Fragment,{children:d.map(n=>{let r=p.get(n.sectionId);if(!r)return null;let a=ghe(e,r),o=hhe(t,hs(r.type));if(o.length===0)return null;let s=h?o.find(e=>e.primary)??o[0]:null,u=h&&s?o.filter(e=>e!==s):[],d=c===n.sectionId;return(0,q.jsx)(`div`,{className:`absolute right-2.5 z-20 flex items-center gap-1.5 pointer-events-none`,style:{top:m+n.top-i,height:Math.max(36,Math.min(n.firstLineHeight??40,64))},children:!h||!s?o.map(e=>(0,q.jsx)(B2,{cmd:e,block:a},e.id)):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(B2,{cmd:s,block:a}),u.length>0&&(0,q.jsxs)(`div`,{className:`relative pointer-events-auto`,"data-inline-cmd-overflow-root":`true`,children:[(0,q.jsx)(J,{variant:`outline`,type:`button`,"data-testid":Q.EDITOR_OVERFLOW_ACTIONS_BTN,"aria-label":`More block actions`,"aria-expanded":d,className:`h-7 w-7 max-lg:h-11 max-lg:w-11 max-lg:min-h-[44px] max-lg:min-w-[44px] rounded-[6px] px-0 py-0 text-muted-foreground hover:text-foreground bg-card/85 hover:bg-card border border-border/80 shadow-none`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),l(e=>e===n.sectionId?null:n.sectionId)},children:(0,q.jsx)(Ar,{className:`h-4 w-4`,"aria-hidden":`true`})}),d&&(0,q.jsx)(`div`,{role:`menu`,"aria-label":`Block actions`,"data-testid":Q.EDITOR_OVERFLOW_ACTIONS_MENU,className:`absolute right-0 top-full mt-1 z-40 min-w-[168px] rounded-[6px] border border-border bg-card p-1 shadow-md flex flex-col gap-0.5`,children:u.map(e=>(0,q.jsxs)(K.Fragment,{children:[(0,q.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`w-full min-h-[36px] max-lg:min-h-[44px] px-2.5 py-1.5 rounded-[4px] flex items-center gap-2 text-left text-xs font-medium text-foreground hover:bg-muted transition-colors`,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(null),e.onClick(a)},children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 text-muted-foreground`,children:e.icon}),(0,q.jsx)(`span`,{children:e.label})]}),e.onSplitClick&&(0,q.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`w-full min-h-[36px] max-lg:min-h-[44px] px-2.5 py-1.5 rounded-[4px] flex items-center gap-2 text-left text-xs font-medium text-foreground hover:bg-muted transition-colors`,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(null),e.onSplitClick?.(a)},children:[(0,q.jsx)(`span`,{className:`flex items-center justify-center size-3.5 text-muted-foreground`,children:e.splitIcon??e.icon}),(0,q.jsx)(`span`,{children:`Copy share link`})]})]},e.id))})]})]})},n.sectionId)})})},yhe=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=CB(),a=(0,K.useRef)(``);return(0,K.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(`
|
|
865
865
|
`).filter(e=>e.trim().length>0),i=r.slice(0,3).join(`
|
|
866
866
|
`),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,K.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,K.useEffect)(()=>{t||(a.current=``)},[t]),(0,K.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},bhe=Array.from({length:61},(e,t)=>({id:`min-${t}`,label:`${t}m`,value:String(t)})),V2=[`00`,`05`,`10`,`15`,`20`,`30`,`45`],xhe=V2.map(e=>({id:`sec-${e}`,label:`${e}s`,value:e})),H2=[...[`21-15-9`,`15-12-9`,`12-9-6`,`10-8-6-4-2`,`5-5-5-5-5`].map(e=>({id:`scheme-${e}`,label:e,sublabel:`Scheme`,value:e})),...Array.from({length:50},(e,t)=>{let n=String(t+1);return{id:`rep-${n}`,label:n,value:n}}),...[`60`,`75`,`100`].map(e=>({id:`rep-${e}`,label:e,value:e}))],U2=Array.from({length:12},(e,t)=>{let n=t+1,r=`(${n})`;return{id:`rounds-${n}`,label:`${n} ${n===1?`round`:`rounds`}`,sublabel:r,value:r}}),W2=`5,7.5,10,12,15,16,20,22.5,24,25,30,32,35,40,42.5,45,50,52.5,60,65,70,75,80,85,90,95,100,105,115,120,135,140,155,160,185,205,225,245,275,315`.split(`,`),G2=`10,15,20,25,30,40,50,75,100,150,200,250,300,400,500,600,800,1000,1200,1600,2000,5000,1,1.5,2,3,5,10`.split(`,`),K2=[`kg`,`lb`,`pood`,`%`],q2=[`m`,`km`,`cal`,`ft`,`mi`,`yd`],J2=[{id:`act-rest`,label:`Rest`,sublabel:`[:rest]`,value:`[:rest]`},{id:`act-emom`,label:`EMOM`,sublabel:`1:00`,value:`1:00`},{id:`act-buyin`,label:`Buy-in`,sublabel:`Header`,value:`Buy-in:`},{id:`act-cashout`,label:`Cash-out`,sublabel:`Header`,value:`Cash-out:`}],She=[`Air Squat`,`Back Squat`,`Front Squat`,`Deadlift`,`Kettlebell Swing`,`Pull-up`,`Push-up`,`Burpee`,`Thruster`,`Wall Ball`,`Box Jump`,`Row`,`Run`,`Double Under`],Y2=[{id:`md-blocks`,label:`Blocks`,options:[{id:`blk-time`,label:`Timer Block`,sublabel:"```time",value:`block:time`},{id:`blk-log`,label:`Log Block`,sublabel:"```log",value:`block:log`},{id:`blk-query`,label:`Query Block`,sublabel:"```query",value:`block:query`},{id:`blk-table`,label:`Table (3x2)`,sublabel:`| Col |`,value:`block:table`},{id:`blk-divider`,label:`Divider`,sublabel:`---`,value:`block:divider`}]},{id:`md-format`,label:`Format`,options:[{id:`fmt-h1`,label:`Heading 1`,sublabel:`# Title`,value:`prefix:# `},{id:`fmt-h2`,label:`Heading 2`,sublabel:`## Section`,value:`prefix:## `},{id:`fmt-h3`,label:`Heading 3`,sublabel:`### Detail`,value:`prefix:### `},{id:`fmt-quote`,label:`Blockquote`,sublabel:`> Quote`,value:`prefix:> `},{id:`fmt-bold`,label:`Bold`,sublabel:`**text**`,value:`wrap:**`},{id:`fmt-code`,label:`Inline Code`,sublabel:"`code`",value:"wrap:`"}]},{id:`md-lists`,label:`Lists & Links`,options:[{id:`lst-task`,label:`Task Checkbox`,sublabel:`- [ ]`,value:`prefix:- [ ] `},{id:`lst-bullet`,label:`Bullet Item`,sublabel:`- `,value:`prefix:- `},{id:`lst-number`,label:`Numbered Item`,sublabel:`1. `,value:`prefix:1. `},{id:`lst-link`,label:`External Link`,sublabel:`[Label](url)`,value:`insert:[Link](https://)`},{id:`lst-wiki`,label:`Note Link`,sublabel:`[[Note]]`,value:`insert:[[Note]]`}]}],X2=[{id:`wql-metric`,label:`Query`,options:[{id:`q-reps`,label:`Total Reps`,sublabel:`:sum{metric:reps}`,value:`replace::sum{metric:reps} by {week} last 4w | :bar{}`},{id:`q-vol`,label:`Total Volume`,sublabel:`:sum{metric:volume}`,value:`replace::sum{metric:volume} by {week} last 12w | :timeseries{}`},{id:`q-dur`,label:`Total Duration`,sublabel:`:sum{metric:duration}`,value:`replace::sum{metric:duration} by {week} last 4w | :bar{}`},{id:`q-sessions`,label:`Find Sessions`,sublabel:`:session{}`,value:`replace::session{} last 4w`},{id:`q-notes`,label:`Find Notes`,sublabel:`:note{}`,value:`replace::note{tags:benchmark} last 8w`}]},{id:`wql-scope`,label:`Scope`,options:[{id:`s-journal`,label:`Journal Notebook`,sublabel:`notebook:journal`,value:`append: notebook:journal`},{id:`s-bench`,label:`Benchmark Tag`,sublabel:`tags:benchmark`,value:`append: tags:benchmark`},{id:`s-all`,label:`All History`,sublabel:`Global`,value:`noop:`}]},{id:`wql-window`,label:`Window`,options:[{id:`w-week`,label:`By Week`,sublabel:`by {week}`,value:`append: by {week}`},{id:`w-month`,label:`By Month`,sublabel:`by {month}`,value:`append: by {month}`},{id:`w-4w`,label:`Last 4 Weeks`,sublabel:`last 4w`,value:`append: last 4w`},{id:`w-12w`,label:`Last 12 Weeks`,sublabel:`last 12w`,value:`append: last 12w`}]},{id:`wql-chart`,label:`Chart`,options:[{id:`c-bar`,label:`Bar Chart`,sublabel:`| :bar{}`,value:`append: | :bar{}`},{id:`c-line`,label:`Timeseries`,sublabel:`| :timeseries{}`,value:`append: | :timeseries{}`},{id:`c-table`,label:`Table`,sublabel:`| :table{}`,value:`append: | :table{}`}]}];function Che(e){return e.trim().toLowerCase()}function whe(e,t){let n=new Set,r=e=>{if(!e)return;let t=Che(e);if(t){n.add(t);for(let e of t.split(/[\s/_-]+/))e.length>=3&&n.add(e)}};r(e.notebookSlug);for(let t of e.tags)r(t);r(e.defaultEffort);for(let t of e.defaultEquipment)r(t);let i=D0(t);for(let e of i.activeTags)r(e);if(t.trimStart().startsWith(`---`)){let{meta:e}=ac(t);for(let t of[`tags`,`domain`,`discipline`,`category`,`equipment`,`format`,`intent`]){let n=e[t];if(typeof n==`string`)r(n);else if(Array.isArray(n))for(let e of n)typeof e==`string`&&r(e)}}return n}async function Z2(e,t){let n=f2(t),r=D0(t,{noteId:e}),i=new Set(r.activeTags),a,o,s=n.effort,c=[...n.equipment??[]],l,u,d=[];if(e)try{let t=await X.getNote(e);if(t){if(a=t.notebookId,a){o=a.replace(/^notebook\//,``);let e=await X.getNote(a).catch(()=>null);if(e?.rawContent){let t=f2(e.rawContent);!s&&t.effort&&(s=t.effort);for(let e of t.equipment??[])c.includes(e)||c.push(e);let n=D0(e.rawContent);for(let e of n.activeTags)i.add(e)}if(e?.tags)for(let t of e.tags)i.add(t)}if(t.tags)for(let e of t.tags)i.add(e)}}catch{}let f=Sz(),p=new Set,m=new Set([`duration`,`time`,`rep`,`reps`,`effort`,`rounds`,`distance`,`resistance`,`weight`,`action`,`equipment`,`sound`,`system`,`label`]),h=e=>{let t=f.resolve(e);if(t)for(let e of t.contributions){if(e.kind!==`metric`)continue;let t=e.type.toLowerCase();if(t===`resistance`&&e.unit&&!l)l=e.unit;else if(t===`distance`&&e.unit&&!u)u=e.unit;else if(!m.has(t)&&!p.has(t)){p.add(t);let n=e.value===void 0?`1`:String(e.value);d.push({type:e.type,starterValue:n})}}};for(let e of i)h(e);for(let e of r.propertySources)for(let[t,n]of Object.entries(e.metrics??{})){let e=t.toLowerCase();if(!m.has(e)&&!p.has(e)){p.add(e);let r=typeof n==`object`&&n&&`value`in n?String(n.value??`1`):`1`;d.push({type:t,starterValue:r})}}return{notebookId:a,notebookSlug:o,tags:[...i],defaultEffort:s,defaultEquipment:c,preferredMassUnit:l,preferredDistanceUnit:u,customMetricTypes:d}}function The(e,t,n){let r=0;if(t.defaultEffort&&e.slug===t.defaultEffort&&(r+=100),e.equipment?.some(e=>t.defaultEquipment.includes(e))&&(r+=40),e.baseAttributes?.discipline&&n.has(e.baseAttributes.discipline.toLowerCase())&&(r+=30),e.sourcePath){let t=e.sourcePath.toLowerCase();for(let e of n)if(e.length>=3&&t.includes(e)){r+=20;break}}let i=e.slug.toLowerCase();for(let e of n)if(e.length>=4&&i.includes(e)){r+=10;break}return r}function Q2(e,t,n){let r=SP(),i=r.isInitialized()?[...r.list()]:[],a=whe(t,n);if(i.length===0){let t=She.map(e=>({id:`eff-${e.toLowerCase().replace(/\s+/g,`-`)}`,label:e,value:e}));return e&&!t.some(t=>t.value.toLowerCase()===e.toLowerCase())?[{id:`eff-current`,label:e,value:e},...t]:t}let o=i.map(e=>({effort:e,score:The(e,t,a)})).sort((e,t)=>t.score===e.score?e.effort.label.localeCompare(t.effort.label):t.score-e.score).slice(0,80).map(({effort:e,score:t})=>({id:`eff-${e.slug}`,label:e.label,sublabel:t>0?`Scoped`:e.baseAttributes?.discipline,value:e.label})),s=e.trim();return s&&!o.some(e=>e.value.toLowerCase()===s.toLowerCase())&&o.unshift({id:`eff-current`,label:s,value:s}),o}function Ehe(e,t){let n=uz(),r=[...n.isInitialized()?n.list():[]].sort((e,n)=>{let r=+!!t.defaultEquipment.includes(e.slug),i=+!!t.defaultEquipment.includes(n.slug);return i===r?e.label.localeCompare(n.label):i-r}),i=r.length>0?r.map(e=>({id:`eq-${e.slug}`,label:e.label,value:e.label})):[{id:`eq-kb`,label:`Kettlebell`,value:`KB`},{id:`eq-db`,label:`Dumbbell`,value:`DB`},{id:`eq-bb`,label:`Barbell`,value:`Barbell`},{id:`eq-rig`,label:`Pull-up Bar`,value:`Pull-up Bar`}],a=e.trim();return a&&!i.some(e=>e.value.toLowerCase()===a.toLowerCase())&&i.unshift({id:`eq-current`,label:a,value:a}),i}function $2(e,t){let n=Sz().list(),r=new Set(t.tags.map(e=>e.toLowerCase())),i=[...n].filter(e=>!e.isCategory).sort((e,t)=>{let n=+!!r.has(e.slug.toLowerCase()),i=+!!r.has(t.slug.toLowerCase());return i===n?e.slug.localeCompare(t.slug):i-n}).map(e=>({id:`tag-${e.slug}`,label:`#${e.slug}`,value:`#${e.slug}`}));i.length===0&&i.push({id:`tag-emom`,label:`#emom`,value:`#emom`},{id:`tag-amrap`,label:`#amrap`,value:`#amrap`},{id:`tag-for-time`,label:`#for-time`,value:`#for-time`});let a=e.trim();return a&&!i.some(e=>e.value.toLowerCase()===a.toLowerCase())&&i.unshift({id:`tag-current`,label:a,value:a}),i}function Dhe(e){let t=e.trim().match(/^(\d+):(\d{2})(?::(\d{2}))?$/);if(t){if(t[3]!==void 0){let e=parseInt(t[1],10)*60+parseInt(t[2],10);return{minutes:String(Math.min(60,e)),seconds:t[3]}}return{minutes:String(Math.min(60,parseInt(t[1],10))),seconds:V2.includes(t[2])?t[2]:`00`}}return{minutes:`1`,seconds:`00`}}function e4(e,t,n){let r=e.trim().match(/^(@?\d+(?:\.\d+)?)\s*([a-zA-Z%]+)?$/);return r?{amount:r[1].replace(/^@/,``),unit:r[2]||n}:{amount:t,unit:n}}function Ohe(e,t,n){let r=e.metricType??``;if(r===Y.Duration){let{minutes:t,seconds:n}=Dhe(e.rawText);return[{id:`duration-min`,label:`Minutes`,options:bhe,selectedValue:t},{id:`duration-sec`,label:`Seconds`,options:xhe,selectedValue:n}]}if(r===Y.Rep){let t=e.rawText.trim();return[{id:`rep-value`,label:`Reps / Scheme`,options:H2.some(e=>e.value===t)?H2:[{id:`rep-cur`,label:t,value:t},...H2],selectedValue:t||`10`}]}if(r===Y.Rounds){let t=e.rawText.trim();return[{id:`rounds-value`,label:`Rounds`,options:U2.some(e=>e.value===t)?U2:[{id:`rounds-cur`,label:t,value:t},...U2],selectedValue:t||`(3)`}]}if(r===Y.Resistance){let n=t.preferredMassUnit??`kg`,{amount:r,unit:i}=e4(e.rawText,`20`,n),a=t.preferredMassUnit&&!K2.includes(t.preferredMassUnit)?[t.preferredMassUnit,...K2]:[n,...K2.filter(e=>e!==n)],o=(W2.includes(r)?W2:[r,...W2]).map(e=>({id:`wt-${e}`,label:e,value:e})),s=(a.includes(i)?a:[i,...a]).map(e=>({id:`wt-u-${e}`,label:e,value:e}));return[{id:`unit-amount`,label:`Load`,options:o,selectedValue:r},{id:`unit-suffix`,label:`Unit`,options:s,selectedValue:i}]}if(r===Y.Distance){let n=t.preferredDistanceUnit??`m`,{amount:r,unit:i}=e4(e.rawText,`400`,n),a=t.preferredDistanceUnit&&!q2.includes(t.preferredDistanceUnit)?[t.preferredDistanceUnit,...q2]:[n,...q2.filter(e=>e!==n)],o=(G2.includes(r)?G2:[r,...G2]).map(e=>({id:`dist-${e}`,label:e,value:e})),s=(a.includes(i)?a:[i,...a]).map(e=>({id:`dist-u-${e}`,label:e,value:e}));return[{id:`unit-amount`,label:`Distance`,options:o,selectedValue:r},{id:`unit-suffix`,label:`Unit`,options:s,selectedValue:i}]}if(r===Y.Equipment){let n=Ehe(e.rawText,t);return[{id:`equipment-value`,label:`Equipment`,options:n,selectedValue:n[0]?.value??e.rawText}]}if(r===`tag`){let n=$2(e.rawText,t);return[{id:`tag-value`,label:`Tag`,options:n,selectedValue:n.find(t=>t.value.toLowerCase()===e.rawText.trim().toLowerCase())?.value??n[0]?.value??e.rawText}]}if(r===Y.Action){let t=e.rawText.trim();return[{id:`action-value`,label:`Action`,options:J2.some(e=>e.value===t)?J2:[{id:`act-cur`,label:t,value:t},...J2],selectedValue:t}]}let i=Q2(e.rawText,t,n);return[{id:`effort-value`,label:`Movement / Effort`,options:i,selectedValue:i.find(t=>t.value.toLowerCase()===e.rawText.trim().toLowerCase())?.value??e.rawText.trim()}]}function khe(e,t){let n=Q2(``,e,t)[0]?.value??`Air Squat`,r=e.preferredMassUnit??`kg`,i=e.preferredDistanceUnit??`m`,a=$2(``,e)[0]?.value??`#emom`,o=[{id:`add-duration`,label:`Duration / Timer`,sublabel:`1:00`,value:`1:00`},{id:`add-rep`,label:`Reps / Scheme`,sublabel:`10`,value:`10`},{id:`add-effort`,label:`Movement / Effort`,sublabel:n,value:n},{id:`add-weight`,label:`Weight / Load`,sublabel:`20${r}`,value:`20${r}`},{id:`add-distance`,label:`Distance`,sublabel:`400${i}`,value:`400${i}`},{id:`add-rounds`,label:`Rounds`,sublabel:`(3)`,value:`(3)`},{id:`add-rest`,label:`Rest / Action`,sublabel:`[:rest]`,value:`[:rest]`},{id:`add-tag`,label:`Tag (#)`,sublabel:a,value:a},...e.customMetricTypes.map(e=>({id:`add-custom-${e.type}`,label:e.type,sublabel:e.starterValue,value:e.starterValue}))];return{id:`add-metric-type`,label:`Select Metric Type to Insert`,options:o,selectedValue:o[0].value}}function Ahe(e){let t=E2(e),n=e.selection.main.head,r=e.doc.lineAt(n),i=[];if(t?.statement&&t.section.contentFrom!==void 0){let n=t.section.contentFrom,a=t.statement,o=[];for(let e of a.metrics){if(e.type!==Y.Equipment)continue;let t=Xo(e.metadata);if(t?.matched===`whole`||t?.matched==="default")continue;let r=a.metricMeta?.get(e);r&&o.push({from:n+r.startOffset,to:n+r.endOffset})}let s=new Set;Array.from(a.metrics).forEach((t,c)=>{if(t.type===Y.Sound||t.type===Y.System)return;let l=as(t.metadata),u=typeof t.type==`string`&&t.type.startsWith(`tag.`);if(l&&!u)return;if(t.type===Y.Equipment){let e=Xo(t.metadata);if(e?.matched===`whole`||e?.matched==="default")return}let d=a.metricMeta?.get(t);if(!d)return;let f=n+d.startOffset,p=n+d.endOffset;if(t.type===Y.Effort){for(let t of o)if(t.from===f&&t.to<p)for(f=t.to;f<p&&/\s/.test(e.doc.sliceString(f,f+1));)f++;else if(t.to===p&&t.from>f)for(p=t.from;p>f&&/\s/.test(e.doc.sliceString(p-1,p));)p--}if(f<r.from||p>r.to||f>=p)return;let m=`${f}:${p}`;if(s.has(m))return;s.add(m);let h=e.doc.sliceString(f,p),g=u||/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(h.trim())?`tag`:t.type===Y.Choice?String(t.alternatives[0]?.type??Y.Effort):String(t.type);i.push({id:`metric-${c}-${f}`,kind:`metric`,label:h.trim(),metricType:g,from:f,to:p,rawText:h})}),i.sort((e,t)=>e.from-t.from)}return i.push({id:`add-metric`,kind:`add-metric`,label:`+ Add`,from:r.to,to:r.to,rawText:``}),i}function jhe(e,t,n){let r=e.selection.main.head,i=e.doc.lineAt(r),a=e.doc.toString(),o=e.field(cM,!1)?.sections.find(e=>(e.type===`time`||e.type===`log`||e.type===`query`)&&i.number>=e.startLine&&i.number<=e.endLine)??null;if(!o)try{o=uM(e)}catch{o=e.field(cM,!1)?.sections.find(e=>i.number>=e.startLine&&i.number<=e.endLine)??null}if((o?.type===`time`||o?.type===`log`)&&i.number>o.startLine&&i.number<o.endLine){let o=Ahe(e),s=o.findIndex(e=>e.kind===`metric`&&r>=e.from&&r<=e.to);n!=null&&n>=0&&n<o.length?s=n:s<0&&(s=o.length-1);let c=o[s]??o[o.length-1],l=c.kind===`add-metric`?[khe(t,a)]:Ohe(c,t,a);return{context:`workout`,lineNumber:i.number,lineFrom:i.from,lineTo:i.to,slots:o,activeSlotIndex:s,drums:l}}if(o?.type===`query`&&i.number>o.startLine&&i.number<o.endLine){let e=X2.map(e=>({id:e.id,kind:`query-stage`,label:e.label,from:i.from,to:i.to,rawText:i.text})),t=n!=null&&n>=0&&n<e.length?n:0,r=X2[t];return{context:`query`,lineNumber:i.number,lineFrom:i.from,lineTo:i.to,slots:e,activeSlotIndex:t,drums:[{id:r.id,label:r.label,options:r.options,selectedValue:r.options[0].value}]}}let s=Y2.map(e=>({id:e.id,kind:`markdown-group`,label:e.label,from:i.from,to:i.to,rawText:i.text})),c=n!=null&&n>=0&&n<s.length?n:0,l=Y2[c];return{context:`markdown`,lineNumber:i.number,lineFrom:i.from,lineTo:i.to,slots:s,activeSlotIndex:c,drums:[{id:l.id,label:l.label,options:l.options,selectedValue:l.options[0].value}]}}var Mhe=ou.map(e=>({id:e.name,name:e.label,desc:e.detail,lines:su(e.template).trimEnd().split(`
|
|
867
867
|
`)})),Nhe=[{code:`[:rest]`,label:`Rest Cue`,desc:`Mark an active rest transition`},{code:`[:next]`,label:`Advance Segment`,desc:`Skip forward on completion`},{code:`[:done]`,label:`Complete Block`,desc:`Finish timer when reached`},{code:`[:mark]`,label:`Split / Lap`,desc:`Record a split timestamp`}],Phe=[{mode:`countdown`,label:`Countdown`,sample:`1:00`,desc:`Fixed work countdown`},{mode:`rest`,label:`Rest`,sample:`*1:00`,desc:`Rest interval (*m:ss)`},{mode:`countup`,label:`Count-up`,sample:`^5:00`,desc:`AMRAP / cap clock`},{mode:`collectible`,label:`Measure`,sample:`:?`,desc:`Count until athlete finishes`}],t4=[0,5,10,15,20,30,45],Fhe=Array.from({length:61},(e,t)=>t),n4=`5,7.5,10,12,15,16,20,22.5,24,25,30,32,35,40,42.5,45,50,52.5,60,65,70,75,80,85,90,95,100,105,115,120,135,140,155,160,185,205,225,245,275,315`.split(`,`),Ihe=[`kg`,`lb`,`pood`,`%`],Lhe=[`m`,`km`,`cal`,`ft`,`mi`,`yd`];function r4(e){let t=e.trim();if(t===`:?`)return{mode:`collectible`,mins:0,secs:0};let n=t.startsWith(`*`)?`rest`:t.startsWith(`^`)?`countup`:`countdown`,r=t.replace(/^[*^]/,``).split(`:`).map(e=>parseInt(e||`0`,10)||0);return r.length===3?{mode:n,mins:r[0]*60+r[1],secs:r[2]}:r.length===2?{mode:n,mins:r[0],secs:r[1]}:{mode:n,mins:1,secs:0}}function i4(e){if(e.mode===`collectible`)return`:?`;let t=Math.max(0,e.mins*60+e.secs),n=Math.floor(t/60),r=t%60,i=`${n}:${String(r).padStart(2,`0`)}`;return e.mode===`rest`?`*${i}`:e.mode===`countup`?`^${i}`:i}function a4(e){let t=e.trim(),n=t.startsWith(`@`),r=/^@?(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*(kg|lbs?|pood|%)\b/i.exec(t);if(r)return{hasAt:n,amount:r[1],altAmount:r[2],unit:r[3].toLowerCase()===`lbs`?`lb`:r[3].toLowerCase()};let i=/^@?(1\/2|1\/4|\d+(?:\.\d+)?)\s*(kg|lbs?|pood|%)?\b/i.exec(t);if(i){let e=(i[2]||`kg`).toLowerCase();return{hasAt:n,amount:i[1],altAmount:null,unit:e===`lbs`?`lb`:e}}return{hasAt:n,amount:`20`,altAmount:null,unit:`kg`}}function o4(e){let t=e.hasAt?`@`:``,n=e.unit===`%`?`%`:e.unit;return e.altAmount?`${t}${e.amount} | ${e.altAmount}${n}`:`${t}${e.amount}${n}`}function s4(e){let t=/^(1\/4|1\/2|3\/4|\d+(?:\.\d+)?)\s*(m|km|cal|ft|mi|mile|yd)\b/i.exec(e.trim());if(t){let e=t[2].toLowerCase()===`mile`?`mi`:t[2].toLowerCase();return{amount:t[1],unit:e}}return{amount:`400`,unit:`m`}}function c4(e,t){let n=[],r=/(?:^|\s)(:[a-zA-Z][a-zA-Z0-9-]*)\b/g,i;for(;(i=r.exec(e))!==null;){let r=i[1],a=i.index+i[0].length-r.length;if(a>0&&e[a-1]===`[`)continue;let o=r.slice(1);n.push({id:`fix-colon-${a}`,from:t+a,to:t+a+r.length,raw:r,message:`Unexpected "${r}" — use *1:00 for a timed rest interval or [:${o}] for an action cue.`,fixes:[`*1:00`,`[:${o}]`]})}let a=/(?:^|\s)(\d+(?:-\d+){2,})(?=\s|$)/g;for(;(i=a.exec(e))!==null;){let e=i[1],r=i.index+i[0].length-e.length;n.push({id:`fix-ladder-${r}`,from:t+r,to:t+r+e.length,raw:e,message:`Rep ladders need parentheses so rounds parse cleanly — use (${e}).`,fixes:[`(${e})`]})}return n}function Rhe(e,t,n,r,i){let a=t.trim();if(r||i)return`tag`;if(e.type===Y.Custom&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(a)||n)return`unresolved`;switch(e.type){case Y.Duration:return`duration`;case Y.Rounds:return`rounds`;case Y.Rep:return`rep`;case Y.Effort:return`effort`;case Y.Equipment:return`equipment`;case Y.Resistance:return`resistance`;case Y.Distance:return`distance`;case Y.Action:return`action`;default:return`custom`}}function l4(e,t){let n=t===void 0?E2(e):t,r=e?.selection?.main?.head??n?.lineFrom??0,i=typeof e?.doc?.lineAt==`function`&&typeof e?.doc?.sliceString==`function`?e.doc.lineAt(Math.min(r,e.doc.length)):{number:n?.cursorLine??1,from:n?.lineFrom??0,to:n?.lineTo??0,text:typeof e?.doc?.sliceString==`function`?e.doc.sliceString(n?.lineFrom??0,n?.lineTo??0):``},a=n?.section??null;if(!a&&typeof e?.field==`function`&&(a=(e.field(cM,!1)?.sections??[]).find(e=>(e.type===`time`||e.type===`log`||e.type===`query`)&&i.number>=e.startLine&&i.number<=e.endLine)??null,!a))try{a=uM(e)}catch{a=null}let o=(a?.type===`time`||a?.type===`log`)&&i.number>a.startLine&&i.number<a.endLine,s=a?.type===`query`&&i.number>a.startLine&&i.number<a.endLine,c=o?`workout`:s?`query`:`markdown`;if(!o||!a)return{contextKind:c,section:a,focus:n,lineNum:i.number,lineFrom:i.from,lineTo:i.to,lineText:i.text,tokens:[],lintFixes:[]};let l=c4(i.text,i.from),u=[],d=new Set;for(let e of l){let t=`${e.from}:${e.to}`;d.add(t),u.push({id:`tok-${e.id}`,kind:`lintError`,raw:e.raw,displayLabel:e.raw,from:e.from,to:e.to,lineNum:i.number,lintMessage:e.message,lintFixes:e.fixes})}let f=a.contentFrom??i.from,p=n?.allStatements?.filter(e=>(e.meta?.line??0)===i.number-a.startLine)??(n?.statement?[n.statement]:[]);for(let t of p){let n=[];for(let e of t.metrics){if(e.type!==Y.Equipment)continue;let r=Xo(e.metadata);if(r?.matched===`whole`||r?.matched==="default")continue;let i=t.metricMeta?.get(e);i&&n.push({from:f+i.startOffset,to:f+i.endOffset})}Array.from(t.metrics).forEach((r,a)=>{if(r.type===Y.Sound||r.type===Y.System||r.type===Y.Hint)return;let o=as(r.metadata),s=typeof r.type==`string`&&r.type.startsWith(`tag.`);if(o&&!s)return;let c=Xo(r.metadata);if(r.type===Y.Equipment&&(c?.matched===`whole`||c?.matched==="default"))return;let p=t.metricMeta?.get(r);if(!p)return;let m=f+p.startOffset,h=f+p.endOffset;if(r.type===Y.Effort){for(let t of n)if(t.from===m&&t.to<h)for(m=t.to;m<h&&/\s/.test(e.doc.sliceString(m,m+1));)m++;else if(t.to===h&&t.from>m)for(h=t.from;h>m&&/\s/.test(e.doc.sliceString(h-1,h));)h--}if(m<i.from||h>i.to||m>=h||l.some(e=>m<e.to&&h>e.from))return;let g=`${m}:${h}`;if(d.has(g))return;d.add(g);let _=e.doc.sliceString(m,h),v=c?.diagnostics?.[0],y=(c?.diagnostics?.length??0)>0,b=c?.refs?.[0],x=r.type===Y.Choice?r.alternatives[0]??r:r,S=Rhe(x,_,y,s,!!o),C=_.trim(),w=S===`duration`&&C.startsWith(`*`),T=S===`tag`||S===`unresolved`&&C.startsWith(`#`),E={id:`tok-${i.number}-${m}-${a}`,kind:S,raw:_,displayLabel:S===`rep`?`${C} reps`:S===`unresolved`?`? ${C}`:C,from:m,to:h,lineNum:i.number,metric:x,refKind:b?.kind,refSlug:b?.slug,tagRef:o,isTag:T,isRest:w,diagnostic:v?{reason:v.reason,message:v.message,token:v.token,candidates:v.candidates}:T&&S===`unresolved`?{reason:`unknown-tag`,message:`Unknown tag ${C} — create it in one tap.`,token:C}:void 0};S===`duration`&&(E.durationMeta=r4(C)),S===`resistance`&&(E.resistanceMeta=a4(C)),S===`distance`&&(E.distanceMeta=s4(C)),u.push(E)})}let m=/(?:^|\s)(#[a-zA-Z0-9-]+)(?=\s|$)/g,h;for(;(h=m.exec(i.text))!==null;){let e=h[1],t=h.index+h[0].length-e.length,n=i.from+t,r=n+e.length;if(u.some(e=>n<e.to&&r>e.from))continue;let a=e.slice(1),o=Sz().resolve(a);u.push({id:`tok-${i.number}-${n}-tag`,kind:o?`tag`:`unresolved`,raw:e,displayLabel:o?e:`? ${e}`,from:n,to:r,lineNum:i.number,isTag:!0,diagnostic:o?void 0:{reason:`unknown-tag`,message:`Unknown tag ${e} — create it in one tap.`,token:e}})}return u.sort((e,t)=>e.from-t.from),{contextKind:c,section:a,focus:n,lineNum:i.number,lineFrom:i.from,lineTo:i.to,lineText:i.text,tokens:u,lintFixes:l}}function u4(e,t){if(t.type!==`time`&&t.type!==`log`)return[];let n=[];for(let r=t.startLine+1;r<t.endLine;r++){let t=e.doc.line(r),i=t.text.trim();if(!i)continue;let a=c4(t.text,t.from),o=/(?:^|\s)([*^]?\d*:\d{2}|:\?)\b/.exec(i),s=/[:*\s]\*|:rest\b|\[:rest\]/i.test(i),c=o?o[1].replace(/^[*^]/,``):s?`Rest`:`Effort`;n.push({lineNum:r,text:i,label:i.length>36?`${i.slice(0,35)}…`:i,durationLabel:a.length>0?`Fix`:c,isRest:s,hasError:a.length>0})}return n}function zhe(e,t,n){if(t.lineNum<1||t.lineNum>e.state.doc.lines)return{applied:!1,nextText:``,from:0,to:0};let r=e.state.doc.line(t.lineNum),i=Math.max(r.from,Math.min(t.from,r.to)),a=Math.max(i,Math.min(t.to,r.to)),o=n.replace(/[\r\n]+/g,` `).trim();return e.dispatch({changes:{from:i,to:a,insert:o},selection:{anchor:i,head:i+o.length},userEvent:`input.wheel`}),{applied:!0,nextText:o,from:i,to:i+o.length}}function d4(e,t){if(t.lineNum<1||t.lineNum>e.state.doc.lines)return!1;let n=e.state.doc.line(t.lineNum),r=Math.max(n.from,Math.min(t.from,n.to)),i=Math.max(r,Math.min(t.to,n.to)),a=r,o=i,s=o<n.to?e.state.doc.sliceString(o,o+1):``,c=a>n.from?e.state.doc.sliceString(a-1,a):``;return s===` `?o+=1:c===` `&&a>n.from+n.text.search(/\S|$/)&&--a,e.dispatch({changes:{from:a,to:o,insert:``},selection:{anchor:a},userEvent:`input.wheel`}),!0}function Bhe(e,t,n){if(t<1||t>e.state.doc.lines)return null;let r=e.state.doc.line(t),i=n.replace(/[\r\n]+/g,` `).trim();if(!i)return null;let a=r.text.trimEnd(),o=a.length>0,s=r.from+a.length,c=`${o?` `:``}${i}`,l=s+ +!!o,u=s+c.length;return e.dispatch({changes:{from:s,to:r.to,insert:c},selection:{anchor:l,head:u},userEvent:`input.wheel`}),{from:l,to:u,clean:i}}function f4(e,t,n){let r=e.state.doc.lineAt(Math.min(t.from,e.state.doc.length)),i=Math.max(r.from,Math.min(t.from,r.to)),a=Math.max(i,Math.min(t.to,r.to)),o=n.replace(/[\r\n]+/g,` `).trim();return e.dispatch({changes:{from:i,to:a,insert:o},selection:{anchor:i+o.length},userEvent:`input.wheel`}),!0}function Vhe(e,t,n){let r=e.state.doc.line(t.startLine),i=/^(\s*`{3,})(time|log|wod|whiteboard)(?::([a-z0-9_-]+))?(.*)$/i.exec(r.text);if(!i)return!1;let a=i[1],o=n.dialect??(t.type===`log`?`log`:`time`),s=n.sport===void 0?i[3]??``:n.sport.trim(),c=i[4]??``,l=`${a}${o}${s?`:${s}`:``}${c}`;return e.dispatch({changes:{from:r.from,to:r.to,insert:l},userEvent:`input.dialect`}),!0}function Hhe(e,t,n){if(t.contentFrom===void 0||t.contentTo===void 0)return!1;let r=e.state.doc.sliceString(t.contentFrom,t.contentTo),i=n.join(`
|
|
868
|
-
`),a=r.trim()?`${r.trimEnd()}\n${i}\n`:`${i}\n`;return e.dispatch({changes:{from:t.contentFrom,to:t.contentTo,insert:a},selection:{anchor:t.contentFrom},userEvent:`input.wheel`}),!0}function Uhe(e,t){let n=e.state.selection.main,r=`[[${t.trim()}]]`,i=n.from>0?e.state.doc.sliceString(n.from-1,n.from):``,a=`${i&&!/[\s([]/.test(i)?` `:``}${r}`;return e.dispatch({changes:{from:n.from,to:n.to,insert:a},selection:{anchor:n.from+a.length},userEvent:`input.format`}),!0}function p4(e,t){let n=e.state.selection.main,r=t.startsWith(`#`)?t:`#${t}`,i=n.from>0?e.state.doc.sliceString(n.from-1,n.from):``,a=`${i&&!/\s/.test(i)?` `:``}${r} `;return e.dispatch({changes:{from:n.from,to:n.to,insert:a},selection:{anchor:n.from+a.length},userEvent:`input.format`}),!0}function m4(e,t){let n=SP(),r=n.isInitialized()?n.list():[],i=e.trim().toLowerCase(),a=r.map(e=>{let n=!!(t?.defaultEffort&&e.slug===t.defaultEffort)||!!t?.defaultEquipment?.some(t=>e.equipment?.includes(t));return{slug:e.slug,label:e.label,aliases:e.aliases??[],discipline:e.baseAttributes?.discipline,scoped:n}}).filter(e=>!i||e.label.toLowerCase().includes(i)||e.slug.toLowerCase().includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i)));return a.sort((e,t)=>{if(i){let n=+!!e.label.toLowerCase().startsWith(i),r=+!!t.label.toLowerCase().startsWith(i);if(r!==n)return r-n}return e.scoped===t.scoped?e.label.localeCompare(t.label):Number(t.scoped)-Number(e.scoped)}),a.length>0?a.slice(0,40):[{slug:`kettlebell-swing`,label:`Kettlebell Swing`,aliases:[`swing`,`kb swing`,`kbs`],scoped:!0},{slug:`back-squat`,label:`Back Squat`,aliases:[`bs`,`squat`],scoped:!1},{slug:`pull-up`,label:`Pull-up`,aliases:[`pullup`,`kipping pullup`],scoped:!1},{slug:`push-up`,label:`Push-up`,aliases:[`pushup`],scoped:!1},{slug:`air-squat`,label:`Air Squat`,aliases:[`squat`],scoped:!1},{slug:`thruster`,label:`Thruster`,aliases:[`thrusters`],scoped:!1},{slug:`burpee`,label:`Burpee`,aliases:[`burpees`],scoped:!1},{slug:`run`,label:`Run`,aliases:[`running`],scoped:!1},{slug:`row`,label:`Row`,aliases:[`rowing`,`erg`],scoped:!1},{slug:`plank`,label:`Plank`,aliases:[`plank hold`],scoped:!1}].filter(e=>!i||e.label.toLowerCase().includes(i)||e.slug.includes(i)||e.aliases.some(e=>e.includes(i)))}function Whe(e){let t=uz(),n=t.isInitialized()?t.list():[],r=e.trim().toLowerCase(),i=n.filter(e=>!r||e.label.toLowerCase().includes(r)||e.slug.toLowerCase().includes(r)).slice(0,30).map(e=>({slug:e.slug,label:e.label}));return i.length>0?i:[{slug:`kettlebell`,label:`Kettlebell`},{slug:`barbell`,label:`Barbell`},{slug:`dumbbell`,label:`Dumbbell`},{slug:`pull-up-bar`,label:`Pull-up Bar`},{slug:`rower`,label:`Rower`}].filter(e=>!r||e.label.toLowerCase().includes(r))}function h4(e){let t=Sz().list().filter(e=>!e.isCategory),n=e.trim().replace(/^#/,``).toLowerCase(),r=e=>e?e.kind===`metric`?e.type:e.kind===`function`?e.name:e.slug:`Tag`,i=t.map(e=>({slug:e.slug,category:r(e.contributions[0])})).filter(e=>!n||e.slug.toLowerCase().includes(n)||e.category.toLowerCase().includes(n)).slice(0,40);return i.length>0?i:[{slug:`emom`,category:`Format`},{slug:`amrap`,category:`Format`},{slug:`tabata`,category:`Format`},{slug:`for-time`,category:`Format`},{slug:`strength`,category:`Focus`},{slug:`heavy`,category:`Load`}].filter(e=>!n||e.slug.includes(n))}async function Ghe(e){let t=await X.getAllNotes().catch(()=>[]),n=e.trim().toLowerCase(),r=new Set,i=[];for(let e of t){let t=e.title?.trim();if(!(!t||r.has(t.toLowerCase()))&&!(n&&!t.toLowerCase().includes(n)&&!e.tags?.some(e=>e.toLowerCase().includes(n)))&&(r.add(t.toLowerCase()),i.push({noteId:e.id,title:t,summary:e.tags?.slice(0,3).map(e=>`#${e}`).join(` `)||`Note`}),i.length>=25))break}return i}var g4=({label:e,ariaLabel:t,options:n,selectedValue:r,onSelect:i,compact:a=!1,testId:o=Q.EDITOR_INSPECTOR_SCRUBBER,optionTestIdPrefix:s})=>{let c=(0,K.useRef)(null),l=(0,K.useRef)(0),u=(0,K.useRef)(n),d=(0,K.useRef)(r),f=(0,K.useRef)(i);return u.current=n,d.current=r,f.current=i,(0,K.useEffect)(()=>{let e=c.current;if(!e)return;let t=e.querySelector(`[aria-selected="true"]`);if(!t)return;let n=Math.max(0,t.offsetTop-(e.clientHeight-t.offsetHeight)/2);l.current=Date.now()+180,e.scrollTop=n},[r,n.length]),(0,K.useEffect)(()=>{let e=c.current;if(!e)return;let t=e=>{if(!e||Date.now()<l.current||e===d.current)return;let t=u.current.find(t=>t.value===e);t&&f.current(t)};if(typeof HTMLElement<`u`&&`onscrollsnapchange`in HTMLElement.prototype){let n=e=>{let n=e.snapTargetBlock;t(n?.dataset?.optionValue)};return e.addEventListener(`scrollsnapchange`,n),()=>e.removeEventListener(`scrollsnapchange`,n)}let n=null,r=()=>{if(e.clientHeight<=0)return;let t=e.scrollTop+e.clientHeight/2,n,r=1/0;return e.querySelectorAll(`[data-option-value]`).forEach(e=>{let i=e.offsetTop+e.offsetHeight/2,a=Math.abs(i-t);a<r&&(r=a,n=e.dataset.optionValue)}),n},i=()=>{Date.now()<l.current||(n&&clearTimeout(n),n=setTimeout(()=>{t(r())},140))};return e.addEventListener(`scroll`,i,{passive:!0}),()=>{n&&clearTimeout(n),e.removeEventListener(`scroll`,i)}},[]),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,"data-testid":o,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground px-0.5 truncate`,children:e}),(0,q.jsxs)(`div`,{className:$(`relative rounded-md border border-border bg-popover overflow-hidden`,a?`h-[144px]`:`h-[172px]`),style:{containerType:`size`},children:[(0,q.jsx)(`div`,{"aria-hidden":`true`,className:`pointer-events-none absolute inset-x-1.5 top-1/2 -translate-y-1/2 h-11 rounded-[6px] bg-primary/10 border border-primary/40 z-[1]`}),(0,q.jsx)(`div`,{ref:c,role:`listbox`,tabIndex:0,"aria-label":t??e,onKeyDown:e=>{if(e.key!==`ArrowUp`&&e.key!==`ArrowDown`||n.length===0)return;e.preventDefault();let t=n.findIndex(e=>e.value===r),a=t>=0?t:0,o=n[Math.max(0,Math.min(n.length-1,a+(e.key===`ArrowDown`?1:-1)))];o&&o.value!==r&&i(o)},className:`relative z-[2] h-full overflow-y-auto snap-y snap-mandatory overscroll-contain flex flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50`,style:{paddingBlock:`calc(50cqh - 22px)`},children:n.map(e=>{let t=e.value===r;return(0,q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,"data-option-value":e.value,"data-testid":s?`${s}-${e.id}`:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>i(e),className:$(`shrink-0 h-11 snap-center w-full px-3 flex items-center justify-center gap-1.5 font-mono tabular-nums text-sm transition-colors cursor-pointer`,t?`font-bold text-primary`:`font-medium text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(`span`,{className:`truncate`,children:e.label}),e.sublabel&&(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.sublabel})]},e.id)})})]})]})},_4=`inline-flex items-center justify-center rounded-full border text-xs font-medium transition-colors cursor-pointer whitespace-nowrap tabular-nums`,Khe=[{label:`Total Reps`,val:`:sum{metric:reps} by {week} last 4w | :bar{}`},{label:`Total Volume`,val:`:sum{metric:volume} by {week} last 12w | :timeseries{}`},{label:`Weekly TIS`,val:`:sum{metric:tis} by {week} last 8w | :timeseries{}`},{label:`Find Sessions`,val:`:session{} last 4w`},{label:`Find Notes`,val:`:note{tags:benchmark} last 8w`}],qhe=[{label:`Bar Chart`,suffix:`| :bar{}`},{label:`Timeseries`,suffix:`| :timeseries{}`},{label:`Table`,suffix:`| :table{}`},{label:`No Chart`,suffix:``}];function Jhe(e,t){let n=e.replace(/\s*\|\s*:(?:bar|timeseries|table|pie)\{[^}]*\}\s*$/i,``).trim()||`:sum{metric:reps} by {week} last 4w`;return t?`${n} ${t}`:n}var Yhe=/^\s*(?:view|limit|title|chart|span|unit|range|groupBy|columns|sort)\s*:/m,Xhe=e=>Fg(e)?sJ.runFind(e):sJ.runQuery(e.raw),v4=({view:e,mode:t,inspection:n,token:r,scope:i,useScrubber:o=!1,onToggleScrubber:s,compact:c=!1,showHeader:l=!0,showFooter:u=!0,showStepButtons:d=!1,showClose:f=!1,showDockButton:p=!1,onDockDrawer:m,onMutate:h,onModeChange:g,onStepToken:_,onClose:v,activeQueryStageId:y,queryStageRequestToken:b})=>{let[x,S]=(0,K.useState)(``),[C,w]=(0,K.useState)(!1),[T,E]=(0,K.useState)([]),[D,O]=(0,K.useState)(!1),k=n.section?.type===`query`?n.section:null,A=!!(e&&k&&k.contentFrom!==void 0&&k.contentTo!==void 0),M=A&&e&&k?e.state.doc.sliceString(k.contentFrom,k.contentTo):n.lineText,N=(0,K.useMemo)(()=>{let e=Ck(M),t=/^\s*query\s*:/m.test(M),n=Yhe.test(M),r;return r=t||e.length>0&&!n?e[0]?.query??``:n?``:M.trim(),{extracted:e,hasYamlQueryKey:t,hasOtherYamlConfig:n,currentQuery:r}},[M]),[P,F]=(0,K.useState)(()=>!N.currentQuery.trim()),I=(0,K.useRef)(N.currentQuery);I.current=N.currentQuery,(0,K.useEffect)(()=>{S(``),w(!1)},[r?.id,t]),(0,K.useEffect)(()=>{t===`query`&&F(!I.current.trim())},[t,k?.id]),(0,K.useEffect)(()=>{t===`query`&&y===`wql-metric`&&b&&F(!0)},[t,y,b]);let L=(0,K.useMemo)(()=>{if(!(t!==`query`||!b||b<=0)){if(y===`wql-metric`){let e=I.current.trim();return{type:/^:(?:session|note|block|effort|notebook|tag|equipment)\b/i.test(e)?`target`:`metric`,token:b}}if(y===`wql-scope`)return{type:`notebook`,token:b};if(y===`wql-window`)return{type:`time`,token:b}}},[t,y,b]);(0,K.useEffect)(()=>{if(t!==`wiki`)return;let e=!1;return Ghe(x).then(t=>{e||E(t)}),()=>{e=!0}},[t,x]);let R=c?`min-h-[44px] px-3.5 py-2`:`min-h-[32px] px-2.5 py-1`,B=c?`min-h-[44px] px-3 py-2`:`min-h-[36px] px-2.5 py-1.5`,V=(t,n)=>{if(!e||!r)return;let i=r.raw,a=zhe(e,r,t);a.applied&&h?.({from:i,to:a.nextText},n??`Updated -> ${a.nextText}`)},H=()=>{if(!e||!r)return;let t=r.raw;d4(e,r)&&h?.({from:t,to:`removed`},`Removed ${t}`)},U=(t,r)=>{if(!e)return;let i=Bhe(e,n.lineNum,t);i&&(h?.({from:`+ add`,to:i.clean},r??`Added ${i.clean}`),g?.(`token`))},te=()=>{e&&e.dispatch({effects:[S2.of(null)]})},W=async(e,t)=>{if(!(!t.trim()||D)){O(!0);try{if(e===`tag`){let e=t.replace(/^#/,``).trim();await v2(e),te(),h?.({from:t,to:`#${e}`},`Created tag #${e}`)}else if(e===`effort`){let e=await h2(t);te(),h?.({from:t,to:e.label},`Defined effort "${e.label}"`)}else{let e=await _2(t);te(),h?.({from:t,to:e.label},`Defined equipment "${e.label}"`)}}finally{O(!1)}}},ne=async(t,i,a)=>{if(!D){O(!0);try{if(await g2(t,a),te(),e&&r&&y2(n.lineText).jsonFrom>=0){let r=b2(n.lineText,{effort:t});e.dispatch({changes:{from:n.lineFrom,to:n.lineTo,insert:r},userEvent:`input.wheel`})}w(!1),h?.({from:a,to:i},`Aliased "${a}" -> ${i}`)}finally{O(!1)}}},re=(0,K.useMemo)(()=>m4(x,i),[x,i]),ie=(0,K.useMemo)(()=>Whe(x),[x]),ae=(0,K.useMemo)(()=>h4(x),[x]),se=(0,K.useMemo)(()=>{let e=new Map;for(let t of ae){let n=e.get(t.category)??[];n.push(t),e.set(t.category,n)}return[...e.entries()]},[ae]),ce=(0,K.useMemo)(()=>e&&n.section?u4(e.state,n.section):[],[e,n]),le=`Edit Token`,ue=r?.raw??``,de=``;if(t===`block`&&n.section){let e=n.section.sport?`:${n.section.sport}`:``;le=`Timer Block Settings`,ue=`\`\`\`${n.section.type}${e}`,de="Switch fence dialect (`time` vs `log`) or insert a grammar-verified template."}else t===`wiki`?(le=`Insert [[Wiki Link]]`,ue=`Note Graph`,de=`Link directly to another Note in your workspace.`):t===`prose-tag`?(le=`Insert #Tag`,ue=`#taxonomy`,de=`Insert a canonical tag or create a new tag inline.`):t===`add`?(le=`Add Syntax Element`,ue=`+ Element`,de=`Append a structured token to the active workout line.`):t===`markdown`?(le=`Markdown & Blocks`,ue=`Line ${n.lineNum}`,de=`Insert workout fences, WQL queries, headings, or wiki links.`):t===`query`?(le=`WQL Query Stage`,ue="```query",de=`Build a WQL query clause without leaving the note.`):r&&(r.kind===`duration`?(le=`Timer & Duration`,de=`Change timer mode without losing duration or surrounding line text.`):r.kind===`rounds`?(le=`Rounds & Structure`,de=`Switch round count, set scheme, ladder, or interval keyword.`):r.kind===`rep`?(le=`Repetitions`,de=`Adjust target rep count with presets or steppers.`):r.kind===`resistance`?(le=`Resistance & Load`,de=`Toggle @ prefix, unit (kg/lb/pood/%), or target load.`):r.kind===`distance`?(le=`Distance & Calories`,de=`Pick standard distances or convert units.`):r.kind===`effort`||r.kind===`equipment`?(le=r.kind===`effort`?`Movement / Effort`:`Equipment`,de=`Search catalog & aliases — rewrites clean Whiteboard Script text.`):r.kind===`tag`?(le=`Tag (#tag)`,de=`Replace with a workspace tag or create a new tag inline.`):r.kind===`unresolved`?(le=r.isTag?`Unrecognized Tag`:`Unrecognized Term`,de=r.diagnostic?.message??`Define "${r.raw}" in your catalog or replace from suggestions.`):r.kind===`lintError`?(le=`Syntax Repair`,de=r.lintMessage??`Fix invalid Whiteboard Script syntax.`):r.kind===`action`&&(le=`Action Cue`,de=`Replace with a structured bracketed timer cue.`));let fe=(e,t)=>(0,q.jsxs)(`div`,{className:`relative flex items-center`,children:[(0,q.jsx)(Yr,{className:`h-3.5 w-3.5 text-muted-foreground absolute left-2.5 pointer-events-none`,"aria-hidden":`true`}),(0,q.jsx)(`input`,{type:`search`,value:x,onChange:e=>S(e.target.value),placeholder:e,"aria-label":t,className:$(`w-full pl-8 pr-2.5 rounded-md border border-field-border bg-background text-foreground placeholder:text-muted-foreground text-base lg:text-xs focus:outline-none focus:ring-2 focus:ring-ring`,c?`min-h-[44px]`:`h-8`)})]});return(0,q.jsxs)(`div`,{className:`flex flex-col min-h-0 min-w-0`,children:[l&&(0,q.jsxs)(`div`,{className:`px-3 py-2.5 border-b border-border bg-popover/70 flex items-start justify-between gap-2 shrink-0`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,q.jsx)(`span`,{className:`text-[13px] font-bold text-foreground tracking-tight`,children:le}),ue&&(0,q.jsx)(`span`,{className:`font-mono text-[11.5px] font-semibold px-2 py-0.5 rounded bg-muted border border-border text-foreground max-w-[160px] truncate`,children:ue})]}),de&&(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5 leading-snug`,children:de})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Delete token`,"data-testid":Q.EDITOR_TOKEN_DELETE_BTN,onClick:H,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-transparent hover:border-destructive/30 hover:bg-destructive/10 text-destructive transition-colors cursor-pointer`,children:(0,q.jsx)(Me,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),d&&_&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,"aria-label":`Previous token`,"data-testid":Q.EDITOR_TOKEN_PREV_BTN,onClick:()=>_(-1),className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(j,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Next token`,"data-testid":Q.EDITOR_TOKEN_NEXT_BTN,onClick:()=>_(1),className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ee,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]}),p&&m&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Dock inspector drawer`,title:`Open Option B Right Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,onClick:m,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ia,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),f&&v&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Close inspector`,onClick:v,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ze,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]})]}),(0,q.jsx)(`div`,{className:$(`flex flex-col gap-3 min-h-0 min-w-0`,u?`p-3 overflow-y-auto max-h-[380px]`:c?`py-1`:`p-3`),children:(()=>{if(t===`block`&&n.section){let t=n.section;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Block Dialect`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`time`,`log`].map(n=>{let r=t.type===n;return(0,q.jsx)(`button`,{type:`button`,onClick:()=>{e&&(Vhe(e,t,{dialect:n}),h?.({from:t.type,to:n},`Switched block to \`\`\`${n}`))},className:$(_4,R,r?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:n===`time`?"TIMER (```time)":"LOG (```log)"},n)})})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Insert Starter Template`}),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-44 overflow-y-auto pr-0.5`,children:Mhe.map(n=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{e&&Hhe(e,t,n.lines)&&h?.({from:`block`,to:n.name},`Inserted ${n.name} template`)},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 transition-colors cursor-pointer`,B),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:n.name}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:n.desc})]}),(0,q.jsxs)(`span`,{className:`text-[11px] font-mono text-primary shrink-0 flex items-center gap-1`,children:[(0,q.jsx)(a,{className:`h-3 w-3`,"aria-hidden":`true`}),`Insert`]})]},n.id))})]}),ce.length>0&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Block Statements`}),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-36 overflow-y-auto`,children:ce.map(t=>{let r=t.lineNum===n.lineNum;return(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_TIMELINE_ROW,onClick:()=>{if(!e)return;let n=e.state.doc.line(t.lineNum);e.dispatch({selection:{anchor:n.from}}),e.focus()},className:$(`w-full rounded-md border px-2.5 py-1.5 min-h-[34px] flex items-center justify-between gap-2 text-left text-xs transition-colors cursor-pointer`,r?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsx)(`span`,{className:`truncate font-mono`,children:t.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono tabular-nums px-1.5 py-0.5 rounded bg-card border border-border shrink-0`,children:t.durationLabel})]},t.lineNum)})})]})]})}if(t===`wiki`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search workspace notes...`,`Search workspace notes`),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1 max-h-52 overflow-y-auto`,children:[T.map(t=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_WIKI_PICKER_ITEM,onClick:()=>{e&&Uhe(e,t.title)&&h?.(null,`Linked [[${t.title}]]`)},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:t.title}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:t.summary})]}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-primary shrink-0`,children:`[[Link]]`})]},t.noteId)),T.length===0&&(0,q.jsxs)(`p`,{className:`text-xs text-muted-foreground py-2`,children:[`No matching workspace notes found. Type `,(0,q.jsx)(`code`,{children:`[[Title]]`}),` directly to create a new link.`]})]})]});if(t===`prose-tag`){let t=x.trim().replace(/^#/,``),n=ae.some(e=>e.slug.toLowerCase()===t.toLowerCase());return(0,q.jsxs)(q.Fragment,{children:[fe(`Filter or create #tag...`,`Filter or create tag`),t&&!n&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,onClick:async()=>{await W(`tag`,t),e&&p4(e,t)},className:`inline-flex items-center gap-1.5 min-h-[36px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create & insert #`,t]}),(0,q.jsx)(`div`,{className:`flex flex-col gap-2 max-h-48 overflow-y-auto`,children:se.map(([t,n])=>(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wide text-muted-foreground`,children:t}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:n.map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{e&&p4(e,t.slug)&&h?.(null,`Inserted #${t.slug}`)},className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted font-mono`),children:[`#`,t.slug]},t.slug))})]},t))})]})}if(t===`markdown`)return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsx)(`div`,{className:`flex flex-col gap-1`,children:[{label:`Timer Block`,sub:"```time",insert:"\n```time\n10:00 EMOM\n 10 Air Squat\n```\n"},{label:`Log Block`,sub:"```log",insert:"\n```log\n5x5 Back Squat @100kg\n```\n"},{label:`Query Block`,sub:"```query",insert:"\n```query\n:sum{metric:reps} by {week} last 4w | :bar{}\n```\n"},{label:`Task Item`,sub:`- [ ]`,prefix:`- [ ] `},{label:`Heading 2`,sub:`## Title`,prefix:`## `}].map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{if(!e)return;let r=e.state.doc.line(n.lineNum);if(t.insert)e.dispatch({changes:{from:r.to,to:r.to,insert:t.insert},selection:{anchor:r.to+t.insert.length},userEvent:`input.wheel`}),h?.(null,`Inserted ${t.label}`);else if(t.prefix){let n=r.text.replace(/^(#{1,6}\s+|-\s+\[[ xX]\]\s+)/,``),i=`${t.prefix}${n}`;e.dispatch({changes:{from:r.from,to:r.to,insert:i},selection:{anchor:r.from+i.length},userEvent:`input.wheel`}),h?.(null,`Applied ${t.label}`)}},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:t.label}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-muted-foreground`,children:t.sub})]},t.label))}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>g?.(`wiki`),className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted`),children:`[[Wiki Link]]`}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>g?.(`prose-tag`),className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted`),children:`#Tag`})]})]});if(t===`query`){let t=(t,r)=>{if(!(!e||t===N.currentQuery)){if(A&&k){let n;if(N.extracted.length>0&&(N.hasYamlQueryKey||!N.hasOtherYamlConfig))n=wk(M,t,0);else if(N.hasOtherYamlConfig){let e=M.trimEnd();n=e?`${e}\nquery: ${t}\n`:`query: ${t}\n`}else{let e=M.trimEnd();n=e?`${e}\n${t}\n`:t?`${t}\n`:``}e.dispatch({changes:{from:k.contentFrom,to:k.contentTo,insert:n},userEvent:`input.wheel`})}else{let r=e.state.doc.line(n.lineNum);e.dispatch({changes:{from:r.from,to:r.to,insert:t},userEvent:`input.wheel`})}h?.(r?{from:N.currentQuery||`empty`,to:t}:null,r??`Updated query`)}};return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2.5 min-w-0`,children:[(0,q.jsx)(vj,{surface:`sheet`,defaultExpanded:!0,query:N.currentQuery,onQueryChange:e=>t(e),execute:Xhe,showDiagnostics:!0,compact:c,segmentEditRequest:L}),y===`wql-chart`&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0 border-t border-border/60 pt-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Chart stage`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:qhe.map(e=>{let n=Jhe(N.currentQuery,e.suffix),r=e.suffix===``?!/\|\s*:(?:bar|timeseries|table|pie)\{/i.test(N.currentQuery):N.currentQuery.toLowerCase().includes(e.suffix.slice(2).trim().toLowerCase());return(0,q.jsx)(`button`,{type:`button`,onClick:()=>t(n,`Chart -> ${e.label}`),className:$(_4,R,r?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e.label},e.label)})})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0 border-t border-border/60 pt-2`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>F(e=>!e),"aria-expanded":P,className:$(`inline-flex items-center justify-between gap-2 text-xs font-semibold text-muted-foreground hover:text-foreground cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:[(0,q.jsx)(`span`,{children:`Quick-seed presets`}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono`,children:P?`Hide`:`Show`})]}),P&&(0,q.jsx)(`div`,{className:`grid grid-cols-2 gap-1.5 min-w-0`,children:Khe.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>t(e.val,`Applied ${e.label}`),className:$(`min-w-0 rounded-md border border-border bg-popover hover:bg-muted text-left flex flex-col gap-0.5 cursor-pointer px-2.5 py-1.5`,c?`min-h-[44px]`:`min-h-[36px]`),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground truncate`,children:e.val})]},e.label))})]})]})}if(t===`add`||!r){let e=i.preferredMassUnit??`kg`,t=i.preferredDistanceUnit??`m`,n=m4(``,i)[0]?.label??`Kettlebell Swing`,r=`#${h4(``)[0]?.slug??`emom`}`,a=[{id:`effort`,label:`Movement / Effort`,raw:n,testId:`wheel-option-add-effort`},{id:`weight`,label:`Weight / Load`,raw:`20${e}`,testId:`wheel-option-add-weight`},{id:`duration`,label:`Countdown Timer`,raw:`1:00`},{id:`rest`,label:`Rest Interval`,raw:`*1:00`},{id:`rep`,label:`Reps`,raw:`10`},{id:`distance`,label:`Distance`,raw:`400${t}`},{id:`rounds`,label:`Rounds`,raw:`(3)`},{id:`action`,label:`Action Cue`,raw:`[:rest]`},{id:`tag`,label:`Tag (#)`,raw:r}];return(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-60 overflow-y-auto`,children:a.map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":e.testId,onClick:()=>U(e.raw),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-primary font-semibold`,children:e.raw})]},e.id))})}if(r.kind===`duration`){let e=r.durationMeta??r4(r.raw),t=String(e.mins),n=String(e.secs),i=e.mode===`rest`?`*`:e.mode===`countup`?`^`:``,a=e.mode===`collectible`?[`:?`]:[`${i}:20`,`${i}:30`,`${i}1:00`,`${i}2:00`,`${i}5:00`,`${i}10:00`],l=t=>{let n=Math.max(5,e.mins*60+e.secs+t);V(i4({mode:e.mode===`collectible`?`countdown`:e.mode,mins:Math.floor(n/60),secs:n%60}))},u=Fhe.map(e=>({id:`min-${e}`,label:`${e}m`,value:String(e)})),d=(t4.includes(e.secs)?t4:[...t4,e.secs].sort((e,t)=>e-t)).map(e=>({id:`sec-${e}`,label:`:${String(e).padStart(2,`0`)}`,value:String(e)}));return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Timer Mode`}),s&&e.mode!==`collectible`&&(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_SCRUBBER_TOGGLE_BTN,onClick:s,className:$(`inline-flex items-center rounded-md px-2 text-xs font-semibold text-primary hover:bg-primary/10 hover:underline cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:o?`Use Presets`:`Use Scrubber`})]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Phe.map(t=>{let n=e.mode===t.mode,r=t.mode===`collectible`?`:?`:i4({mode:t.mode,mins:e.mode===`collectible`?1:e.mins,secs:e.mode===`collectible`?0:e.secs});return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(r,`Mode -> ${t.label}`),className:$(_4,R,n?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[t.label,` (`,t.sample,`)`]},t.mode)})})]}),e.mode!==`collectible`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Quick Presets`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:a.map(e=>{let t=r.raw.trim()===e;return(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e)})})]}),o?(0,q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,q.jsx)(g4,{label:`Minutes`,options:u,selectedValue:t,compact:c,onSelect:t=>V(i4({mode:e.mode,mins:parseInt(t.value,10)||0,secs:e.secs}))}),(0,q.jsx)(g4,{label:`Seconds`,options:d,selectedValue:n,compact:c,onSelect:t=>V(i4({mode:e.mode,mins:e.mins,secs:parseInt(t.value,10)||0}))})]}):(0,q.jsx)(`div`,{className:`grid grid-cols-4 gap-1.5`,children:[-15,-5,5,15].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>l(e),className:$(_4,R,`font-mono bg-popover text-foreground border-border hover:bg-muted rounded-md`),children:e>0?`+${e}s`:`${e}s`},e))})]})]})}if(r.kind===`rounds`){let e=/^\((\d+)\)$/.exec(r.raw.trim()),t=e?parseInt(e[1],10):null;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Rounds / Keyword`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`(3)`,`(4)`,`(5)`,`(8)`,`(10)`,`(21-15-9)`,`5x5`,`EMOM`,`AMRAP`,`Tabata`].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,r.raw.trim().toUpperCase()===e.toUpperCase()?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e))})]}),t!==null&&(0,q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`(${Math.max(1,t-1)})`),className:$(_4,R,`rounded-md bg-popover text-foreground border-border hover:bg-muted gap-1`),children:[(0,q.jsx)(z,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),` 1 Round`]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`(${t+1})`),className:$(_4,R,`rounded-md bg-popover text-foreground border-border hover:bg-muted gap-1`),children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),` 1 Round`]})]})]})}if(r.kind===`rep`){let e=parseInt(r.raw.replace(/^@/,``),10)||10;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Common Rep Targets`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`5`,`8`,`10`,`12`,`15`,`20`,`21`,`30`].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,r.raw.trim()===e?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e))})]}),(0,q.jsx)(`div`,{className:`grid grid-cols-4 gap-1.5`,children:[-5,-1,1,5].map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(String(Math.max(1,e+t))),className:$(_4,R,`rounded-md font-mono bg-popover text-foreground border-border hover:bg-muted`),children:t>0?`+${t}`:String(t)},t))})]})}if(r.kind===`resistance`){let e=r.resistanceMeta??a4(r.raw),t=(n4.includes(e.amount)?n4:[e.amount,...n4]).map(t=>({id:`amt-${t}`,label:`${e.hasAt?`@`:``}${t}${e.unit}`,value:t}));return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(o4({...e,hasAt:!e.hasAt})),className:$(_4,R,`font-mono`,e.hasAt?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e.hasAt?`@ Prefix On`:`Add @ Prefix`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:Ihe.map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(o4({...e,unit:t})),className:$(_4,R,`font-mono`,e.unit===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:t},t))})]}),(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Load Amount`}),s&&(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_SCRUBBER_TOGGLE_BTN,onClick:s,className:$(`inline-flex items-center rounded-md px-2 text-xs font-semibold text-primary hover:bg-primary/10 hover:underline cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:o?`Use Presets`:`Use Scrubber`})]}),o?(0,q.jsx)(g4,{label:`Load (${e.unit})`,options:t,selectedValue:e.amount,compact:c,testId:`wheel-drum-unit-amount`,onSelect:t=>V(o4({...e,amount:t.value,altAmount:null}))}):(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`16`,`20`,`24`,`32`,`60`,`100`].map(t=>{let n=o4({...e,amount:t,altAmount:null});return(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(n),className:$(_4,R,`font-mono`,e.amount===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:n},t)})})]})}if(r.kind===`distance`){let e=r.distanceMeta??s4(r.raw),t=e.unit===`cal`?[`10`,`15`,`20`,`30`,`50`]:[`100`,`200`,`400`,`800`,`1000`,`2000`];return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:Lhe.map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(`${e.amount}${t}`),className:$(_4,R,`font-mono`,e.unit===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:t},t))}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`${t}${e.unit}`),className:$(_4,R,`font-mono`,e.amount===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[t,e.unit]},t))})]})}if(r.kind===`effort`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search movement or alias (e.g. swing, kbs)...`,`Search effort catalog`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-48 overflow-y-auto`,children:re.map(e=>{let t=e.label.toLowerCase()===r.raw.trim().toLowerCase()||e.slug===r.refSlug;return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border text-left flex items-center justify-between gap-2 cursor-pointer`,B,t?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold truncate`,children:e.label}),e.aliases.length>0&&(0,q.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:[`Aliases: `,e.aliases.slice(0,3).join(`, `)]})]}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground shrink-0`,children:e.scoped?`Scoped`:e.discipline||e.slug})]},e.slug)})})]});if(r.kind===`equipment`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search equipment...`,`Search equipment catalog`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-48 overflow-y-auto`,children:ie.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground`,children:e.slug})]},e.slug))})]});if(r.kind===`tag`){let e=x.trim().replace(/^#/,``),t=ae.some(t=>t.slug.toLowerCase()===e.toLowerCase());return(0,q.jsxs)(q.Fragment,{children:[fe(`Filter or create #tag...`,`Search or create tag`),e&&!t&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,onClick:async()=>{await W(`tag`,e),V(`#${e}`)},className:`inline-flex items-center gap-1.5 min-h-[36px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create & apply #`,e]}),(0,q.jsx)(`div`,{className:`flex flex-col gap-2 max-h-44 overflow-y-auto`,children:se.map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wide text-muted-foreground`,children:e}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>{let t=r.raw.trim().toLowerCase()===`#${e.slug}`.toLowerCase();return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`#${e.slug}`),className:$(_4,R,`font-mono`,t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[`#`,e.slug]},e.slug)})})]},e))})]})}if(r.kind===`action`)return(0,q.jsx)(`div`,{className:`flex flex-col gap-1`,children:Nhe.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.code),className:$(`w-full rounded-md border text-left flex items-center justify-between gap-2 cursor-pointer`,B,r.raw.trim()===e.code?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.desc})]}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-primary font-semibold shrink-0`,children:e.code})]},e.code))});if(r.kind===`lintError`)return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`p-2.5 rounded-md border border-destructive/40 bg-destructive/10 text-destructive text-xs flex items-start gap-2`,children:[(0,q.jsx)(oe,{className:`h-4 w-4 shrink-0 mt-0.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r.lintMessage})]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:(r.lintFixes??[]).map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:()=>V(e,`Fixed -> ${e}`),className:$(_4,R,`bg-primary text-primary-foreground border-primary font-semibold`),children:[`Fix: `,e]},e))})]});if(r.kind===`unresolved`){if(r.isTag){let e=r.raw.replace(/^#/,``).trim();return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,disabled:D,onClick:()=>void W(`tag`,e),className:`inline-flex items-center gap-1.5 min-h-[38px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create Tag #`,e]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:h4(``).slice(0,8).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`#${e.slug}`),className:$(_4,R,`font-mono bg-popover text-foreground border-border hover:bg-muted`),children:[`#`,e.slug]},e.slug))})]})}return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`p-2 rounded-md border border-warning/40 bg-warning/10 text-warning text-xs flex items-start gap-2`,children:[(0,q.jsx)(aa,{className:`h-4 w-4 shrink-0 mt-0.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r.diagnostic?.message??`"${r.raw}" is not in your catalog yet.`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_EFFORT_BTN,disabled:D,onClick:()=>void W(`effort`,r.raw),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Effort`]}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_ALIAS_BTN,disabled:D,onClick:()=>w(e=>!e),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md border border-border bg-popover text-foreground hover:bg-muted text-xs font-medium cursor-pointer`,children:`+ Alias`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_EQUIPMENT_BTN,disabled:D,onClick:()=>void W(`equipment`,r.raw),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md border border-border bg-popover text-foreground hover:bg-muted text-xs font-medium cursor-pointer`,children:`+ Equipment`})]}),C&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 pt-1 border-t border-border`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:[`Link "`,r.raw,`" as alias to:`]}),fe(`Search target effort...`,`Search target effort for alias`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-36 overflow-y-auto`,children:re.slice(0,12).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>void ne(e.slug,e.label,r.raw),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-primary`,children:`Link alias`})]},e.slug))})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Or replace with existing movement:`}),!C&&fe(`Search known movements...`,`Search known movements`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-32 overflow-y-auto`,children:re.slice(0,6).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground`,children:`Replace`})]},e.slug))})]})]})}return(0,q.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Token `,(0,q.jsx)(`code`,{className:`font-mono text-foreground`,children:r.raw}),` can be edited inline in the editor.`]})})()}),u&&(0,q.jsxs)(`div`,{className:`px-3 py-2 border-t border-border bg-popover/70 flex items-center justify-between gap-2 text-[11.5px] text-muted-foreground shrink-0`,children:[(0,q.jsx)(`span`,{children:`Line-safe transaction`}),(0,q.jsx)(`span`,{children:`Esc closes inspector`})]})]})},y4=340,b4=12,x4=({open:e,anchorRect:t,editorDom:n,view:r,mode:i,inspection:a,token:o,scope:s,docText:c,onClose:l,onMutate:u,onModeChange:d,onStepToken:f,onDockDrawer:p})=>{let m=(0,K.useRef)(null),[h,g]=(0,K.useState)(!1);(0,K.useEffect)(()=>{g(!1)},[o?.id,i]),(0,K.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),l(),typeof r?.focus==`function`&&r.focus())},n=e=>{let t=e.target;t&&(m.current?.contains(t)||t.closest(`[data-inspector-trigger="true"]`)||l())};return document.addEventListener(`keydown`,t,!0),document.addEventListener(`pointerdown`,n),()=>{document.removeEventListener(`keydown`,t,!0),document.removeEventListener(`pointerdown`,n)}},[e,l,r]);let _=(0,K.useMemo)(()=>{let e=typeof window<`u`?window.innerWidth:1024,r=typeof window<`u`?window.innerHeight:768;if(t&&t.width>0&&t.height>0&&t){let n=r-t.bottom<340&&t.top>280,i=Math.max(b4,Math.min(t.left,e-y4-b4));return n?{left:i,bottom:Math.max(b4,r-t.top+8)}:{left:i,top:Math.max(b4,Math.min(t.bottom+8,r-140))}}let i=n?.getBoundingClientRect();return i&&(i.width>0||i.height>0||i.top>0||i.left>0)&&i?{top:Math.max(b4,Math.min(i.top+48,r-200)),left:Math.max(b4,Math.min(i.left+16,e-y4-b4))}:{top:72,left:24}},[t,n]);return e?(0,q.jsx)(`div`,{ref:m,role:`dialog`,"aria-label":`Syntax Token Inspector`,"data-testid":Q.EDITOR_INSPECTOR_POPOVER,style:_,className:`fixed z-40 flex max-h-[min(540px,calc(100vh-28px))] w-[340px] max-w-[calc(100vw-24px)] flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-xl`,children:(0,q.jsx)(v4,{view:r,mode:i,inspection:a,token:o,scope:s,docText:c,useScrubber:h,onToggleScrubber:()=>g(e=>!e),compact:!1,showHeader:!0,showFooter:!0,showStepButtons:i===`token`,showClose:!0,showDockButton:!!p,onDockDrawer:p,onMutate:u,onModeChange:d,onStepToken:f,onClose:()=>{l(),typeof r?.focus==`function`&&r.focus()}})}):null},Zhe={[Y.Duration]:{label:`Timer`,Icon:nr,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[Y.Rep]:{label:`Reps`,Icon:F,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[Y.Effort]:{label:`Exercise`,Icon:Pr,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[Y.Rounds]:{label:`Rounds`,Icon:Ue,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[Y.Distance]:{label:`Distance`,Icon:Aee,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[Y.Resistance]:{label:`Weight`,Icon:Hn,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[Y.Equipment]:{label:`Equipment`,Icon:Ui,textClass:`text-metric-equipment`,bgClass:`bg-metric-equipment/10`,borderClass:`border-metric-equipment/30`},[Y.Action]:{label:`Action`,Icon:Eee,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[Y.Label]:{label:`Label`,Icon:On,textClass:`text-muted-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border`}},Qhe={tags:[],defaultEquipment:[],customMetricTypes:[]};function S4(e){switch(e){case Y.Duration:return`duration`;case Y.Rep:return`rep`;case Y.Rounds:return`rounds`;case Y.Effort:return`effort`;case Y.Equipment:return`equipment`;case Y.Resistance:return`resistance`;case Y.Distance:return`distance`;case Y.Action:return`action`;default:return`custom`}}function $he(e,t,n,r){let i=t.tokens.find(t=>t.metric===e);if(i)return i;let a=S4(e.type),o=String(e.image??e.value??``).trim(),s=t.tokens.find(e=>e.kind===a&&(o===``||e.raw.trim().toLowerCase()===o.toLowerCase()||e.raw.toLowerCase().includes(o.toLowerCase())));if(s)return s;let c=S4(e.type),l=o||String(e.type),u={id:`fallback-${c}-${n}`,kind:c,raw:l,displayLabel:c===`rep`?`${l} reps`:l,from:r.lineFrom,to:r.lineTo,lineNum:r.cursorLine,metric:e};return c===`duration`&&(u.durationMeta=r4(l)),c===`resistance`&&(u.resistanceMeta=a4(l)),c===`distance`&&(u.distanceMeta=s4(l)),u}var ege=({metric:e,tooltip:t,isFocused:n,isSelected:r,onClick:i})=>{let a=Zhe[e.type],o=e.type===Y.Hint,s=e.name??e.image??(e.value===void 0?``:String(e.value)),c=a?.label??String(e.type),l=a?.Icon,u=$(`inline-flex items-center gap-1 px-2 py-0.5 min-h-[24px] rounded-full border text-[11px] leading-tight font-medium whitespace-nowrap tabular-nums`,`pointer-events-auto transition-colors`,a?.bgClass??`bg-muted/40`,a?.textClass??`text-muted-foreground`,a?.borderClass??`border-border`,n&&`font-bold ring-1 ring-foreground/20`,r&&`ring-2 ring-primary/50 border-primary`);return o?(0,q.jsx)(`span`,{title:t,className:u,children:(0,q.jsx)(`span`,{children:e.icon})}):(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:t,onClick:i,className:$(u,`hover:opacity-90 focus-visible:outline-2 focus-visible:outline-ring cursor-pointer`),children:[l?(0,q.jsx)(l,{weight:`bold`,className:`h-3 w-3 shrink-0`}):null,(0,q.jsx)(`span`,{className:`sr-only`,children:c}),(0,q.jsx)(`span`,{className:`font-semibold`,children:s||c})]})};function C4(e){let t=Xo(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function tge(e,t,n){try{let r=e.coordsAtPos(t.lineFrom);if(!r)return null;let i=typeof t.lineTo==`number`?e.coordsAtPos(t.lineTo)??r:r,a=e.dom?.getBoundingClientRect?.()??{top:0,left:0,width:600},o=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:600},s=Math.max(0,o.left-a.left),c=s+Math.max(240,o.width),l=i.left-a.left+12,u=c-l;if(n?u>210:u>=160){let e=typeof i.top==`number`?i.top:i.bottom-20;return{top:Math.max(0,e-a.top-1),left:l,maxWidth:u-4,belowLine:!1}}return{top:i.bottom-a.top+3,left:s,maxWidth:Math.max(220,o.width),belowLine:!0}}catch{return null}}var nge=({view:e,cursorVersion:t,getCursorFocusState:n,noteId:r,hidden:i=!1,activeTokenId:a=null,drawerOpen:o=!1,onOpenInspector:s,onToggleDrawer:c,onPeekEntity:l,onClosePeek:u})=>{let[d,f]=(0,K.useState)(null),[p,m]=(0,K.useState)(null),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(Qhe),[y,b]=(0,K.useState)(null),x=(0,K.useRef)(null),S=(0,K.useRef)(void 0),C=(0,K.useCallback)(()=>{if(!e||i){S.current=void 0,m(null),f(null);return}let t=(n??E2)(e.state);m(t);let r=t?tge(e,t,S.current):null;S.current=r?.belowLine,f(r)},[e,n,i]);(0,K.useEffect)(()=>{C()},[C,t]),(0,K.useEffect)(()=>{if(!e||i)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,i]);let w=e?.state?.doc&&typeof e.state.doc.toString==`function`?e.state.doc.toString():``;(0,K.useEffect)(()=>{if(s||!y||!w)return;let e=!1;return Z2(r,w).then(t=>{e||v(t)}),()=>{e=!0}},[s,y,r,w]);let T=(0,K.useMemo)(()=>{if(!e?.state||!p)return{contextKind:`markdown`,section:null,focus:null,lineNum:1,lineFrom:0,lineTo:0,lineText:``,tokens:[],lintFixes:[]};try{return l4(e.state,p)}catch{return{contextKind:`markdown`,section:p.section,focus:p,lineNum:p.cursorLine,lineFrom:p.lineFrom,lineTo:p.lineTo,lineText:typeof e.state.doc?.sliceString==`function`?e.state.doc.sliceString(p.lineFrom,p.lineTo):``,tokens:[],lintFixes:[]}}},[e,p]),E=(0,K.useMemo)(()=>{if(!p?.section)return{lineKey:null,lineText:``,lineRefs:null,visibleMetrics:[],tokens:[],refs:[],tagRefs:[],diagnostics:[],unresolvedTagSlugs:[],lintFixes:[],malformed:!1};let t=`${p.section.id}:${p.cursorLine}`,n=typeof e?.state?.doc?.sliceString==`function`?e.state.doc.sliceString(p.lineFrom,p.lineTo):T.lineText??``,r=p.allStatements?.filter(e=>e.meta?.line===p.cursorLine-p.section.startLine)??(p.statement?[p.statement]:[]),i=r.flatMap(e=>e.metrics.toArray()).filter(e=>{if(e.type===Y.Sound||e.type===Y.System||e.type===Y.Hint&&!e.icon||e.type===Y.Custom&&typeof e.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(e.value.trim()))return!1;if(e.type===Y.Effort||e.type===Y.Equipment){let t=C4(e);if(t.refs.length>0||t.diagnostics.length>0)return!1}return!0}),a=O1(i,`runtime-badge`),o=r.flatMap(e=>e.metrics.toArray()),s=[],c=[],l=[];for(let e of o){let t=C4(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;s.includes(t)||(s.push(t),c.push(e))}l.push(...t.diagnostics)}let u=[],d=[];for(let e of o){let t=as(e.metadata);if(t){u.some(e=>e.slug===t.slug)||u.push(t);continue}if(e.type===Y.Custom&&typeof e.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(e.value.trim())){let t=e.value.trim().slice(1);d.includes(t)||d.push(t)}}let f=typeof e?.state?.doc?.sliceString==`function`?y2(e.state.doc.sliceString(p.lineFrom,p.lineTo)):null;return{lineKey:t,lineText:n,lineRefs:f,visibleMetrics:i,tokens:a,refs:c,tagRefs:u,diagnostics:l,unresolvedTagSlugs:d,lintFixes:T.lintFixes,malformed:!!f?.malformed}},[p,e,T.lineText,T.lintFixes]),[D,O]=(0,K.useState)({lineKey:null,lineText:``,diagKeys:[],tagSlugs:[],lintIds:[],malformed:!1}),[k,A]=(0,K.useState)(null),j=(0,K.useRef)(null),M=(0,K.useMemo)(()=>E.diagnostics.map((e,t)=>`${e.reason}-${e.token?.trim()??t}`),[E.diagnostics]),N=(0,K.useMemo)(()=>E.lintFixes.map(e=>e.id),[E.lintFixes]),P=`${E.lineKey??``}\u0000${E.lineText}\u0000${M.join(`,`)}\u0000${E.unresolvedTagSlugs.join(`,`)}\u0000${N.join(`,`)}\u0000${E.malformed?`1`:`0`}`;(0,K.useEffect)(()=>{if(!E.lineKey)return;if(D.lineKey!==E.lineKey||D.lineText===E.lineText){O({lineKey:E.lineKey,lineText:E.lineText,diagKeys:M,tagSlugs:E.unresolvedTagSlugs,lintIds:N,malformed:E.malformed});return}let e=setTimeout(()=>{O({lineKey:E.lineKey,lineText:E.lineText,diagKeys:M,tagSlugs:E.unresolvedTagSlugs,lintIds:N,malformed:E.malformed})},320);return()=>clearTimeout(e)},[P]);let F=E.visibleMetrics.length>0||E.refs.length>0||E.tagRefs.length>0;(0,K.useEffect)(()=>{if(!E.lineKey||F||E.lineText.trim()===``){E.lineKey&&F?j.current={lineKey:E.lineKey,visibleMetrics:E.visibleMetrics,tokens:E.tokens,refs:E.refs,tagRefs:E.tagRefs}:(!E.lineKey||E.lineText.trim()===``)&&(j.current=null),A(null);return}let e=j.current;if(!e||e.lineKey!==E.lineKey){A(null);return}A(e);let t=setTimeout(()=>{j.current=null,A(null)},220);return()=>clearTimeout(t)},[E.lineKey,E.lineText,F,E.visibleMetrics,E.tokens,E.refs,E.tagRefs]);let I=e?.state&&typeof e.state.field==`function`?Da(e.state):null,ee=I===`active`,L=I!==null;if(i||!d||!p?.section||ee)return null;let R=!F&&k!==null&&k.lineKey===E.lineKey&&E.lineText.trim()!==``,z=R?k.visibleMetrics:E.visibleMetrics,B=R?k.tokens:E.tokens,V=R?k.refs:E.refs,H=R?k.tagRefs:E.tagRefs,U=D.lineKey!==null&&D.lineKey===E.lineKey&&D.lineText!==E.lineText,te=U?new Set(D.diagKeys):null,W=U?new Set(D.tagSlugs):null,ne=U?new Set(D.lintIds):null,re=te?E.diagnostics.filter((e,t)=>te.has(`${e.reason}-${e.token?.trim()??t}`)):E.diagnostics,ie=W?E.unresolvedTagSlugs.filter(e=>W.has(e)):E.unresolvedTagSlugs,ae=ne?E.lintFixes.filter(e=>ne.has(e.id)):E.lintFixes,oe=U?D.malformed&&E.malformed:E.malformed,se=E.lineRefs,ce=typeof e?.state?.facet==`function`?e.state.facet(HM)?.()??null:null,le=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&se?.equipment.includes(e.token)?`equipment`:`effort`,ue=e=>typeof e==`string`&&e.trim()?e:null,de=(e,t,n)=>{let r=n?.getBoundingClientRect?.()??null;if(s){s({mode:e,token:t,anchorRect:r});return}b(n=>n&&n.mode===e&&n.token?.id===t?.id?null:{mode:e,token:t,anchorRect:r})},fe=async t=>{if(!e)return;let n=e.state.doc.sliceString(p.lineFrom,p.lineTo),r=jQ.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort...`,sources:[p2(`effort`)]});if(t.dismissed)return;let i=ue(t.item.payload);if(!i)return;e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(n,{effort:i})}});return}let i=[...se?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)...`:`Set equipment...`,sources:[p2(`equipment`)]});if(e.dismissed)break;let t=ue(e.item.payload);t&&!i.includes(t)&&i.push(t)}((se?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(n,{equipment:i})}})},pe=async()=>{if(!e)return;let t=e.state.doc.sliceString(p.lineFrom,p.lineTo),n=jQ.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)...`,sources:[p2(`effort`)]});i.dismissed||(r=ue(i.item.payload)??void 0);let a=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)...`,sources:[p2(`equipment`)]});if(e.dismissed)break;let t=ue(e.item.payload);t&&!a.includes(t)&&a.push(t)}!r&&a.length===0||e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(t,{effort:r,equipment:a})}})},me=()=>{e&&typeof e.dispatch==`function`&&e.dispatch({effects:[S2.of(null)]}),C()},he=async t=>{if(!e||!t.token)return;let n=le(t),r=await jQ.getState().open({placeholder:`Replace "${t.token}"...`,sources:[p2(n,t.candidates)]});if(r.dismissed)return;let i=ue(r.item.payload);if(!i)return;let a=e.state.doc.sliceString(p.lineFrom,p.lineTo).indexOf(t.token);a<0||e.dispatch({changes:{from:p.lineFrom+a,to:p.lineFrom+a+t.token.length,insert:i}})},ge=async(e,t)=>{t.trim()&&(e===`effort`?await h2(t):await _2(t),me())},_e=async e=>{if(!e.trim())return;let t=await jQ.getState().open({placeholder:`Link "${e}" as alias to effort...`,sources:[p2(`effort`)]});if(t.dismissed)return;let n=ue(t.item.payload);n&&(await g2(n,e),me())},ve=async e=>{e.trim()&&(await v2(e),me())},ye=(t,n,r)=>{if(!e)return;let i=t.type===Y.Effort?`effort`:t.type===Y.Equipment?`equipment`:null;if(i&&l){let e=String(t.name??t.image??t.value??``).trim(),n=af(e)||e;if(n){l({kind:i,slug:n,label:e||n});return}}if(i&&se?.jsonFrom!==void 0&&se.jsonFrom>=0){fe(i);return}let a=$he(t,T,n,p);de(`token`,a,r.currentTarget)},be=(e,t)=>{if(l){l({kind:e.kind,slug:e.slug,label:e.label});return}if(se?.jsonFrom!==void 0&&se.jsonFrom>=0){fe(e.kind);return}let n=T.tokens.find(t=>t.refSlug===e.slug||t.kind===e.kind&&t.raw.toLowerCase().includes(e.label.toLowerCase()))??{id:`ref-${e.kind}-${e.slug}`,kind:e.kind,raw:e.label,displayLabel:e.label,from:p.lineFrom,to:p.lineTo,lineNum:p.cursorLine,refKind:e.kind,refSlug:e.slug};de(`token`,n,t.currentTarget)},xe=z.length>0||V.length>0||H.length>0||re.length>0||ie.length>0||ae.length>0||oe,Se=!!(e?.state?.doc&&typeof e.state.doc.lineAt==`function`),Ce=p.section.type===`time`||p.section.type===`log`,we=p.section.type===`log`?`log`:`time`,Te=y?.token&&T.tokens.find(e=>e.id===y.token?.id||e.from===y.token?.from&&e.kind===y.token?.kind);return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{ref:x,className:$(`cm-metric-inline-panel`,`absolute z-[15]`,`inline-flex items-center gap-1 px-1.5 py-0.5 min-h-[24px]`,d.belowLine?`pointer-events-auto bg-card/95 border border-border rounded-md shadow-xs`:`pointer-events-none bg-transparent`,`transition-opacity duration-100 max-w-full`),style:{top:d.top,left:d.left,maxWidth:d.maxWidth},role:`region`,"aria-live":L?`off`:`polite`,"aria-label":`Metric inline panel`,children:xe?(0,q.jsxs)(`div`,{"data-testid":Q.EDITOR_TOKEN_STRIP,className:$(`flex items-center gap-1`,d.belowLine?`flex-wrap`:`flex-nowrap overflow-x-auto max-w-full scrollbar-none`),children:[z.map((e,t)=>{let n=T.tokens.find(t=>t.metric===e),r=!!(a&&n?.id===a);return(0,q.jsx)(ege,{metric:e,tooltip:e.type===Y.Hint?String(e.value??``):B[t]?.tooltip,isFocused:p.focusedMetric===e,isSelected:r,onClick:n=>ye(e,t,n)},`${e.type}-${t}`)}),V.map(e=>{let t=e.kind===`effort`&&p.focusedMetric?.type===Y.Effort||e.kind===`equipment`&&p.focusedMetric?.type===Y.Equipment,n=e.kind===`effort`?Pr:Ui;return(0,q.jsxs)(`div`,{className:$(`pointer-events-auto inline-flex items-center gap-0.5 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium whitespace-nowrap`,e.kind===`effort`?`bg-metric-effort/10 text-metric-effort border-metric-effort/30`:`bg-metric-equipment/10 text-metric-equipment border-metric-equipment/30`,t&&`font-bold ring-1 ring-foreground/20`),children:[(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:`${e.kind===`effort`?`Effort`:`Equipment`}: ${e.label} (${e.slug})${e.matchedAlias?` · matched alias "${e.matchedAlias}"`:``} · click to edit or change`,onClick:t=>be(e,t),className:`inline-flex items-center gap-1 cursor-pointer hover:opacity-80`,children:[(0,q.jsx)(n,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{className:`sr-only`,children:e.kind===`effort`?`Exercise`:`Equipment`}),(0,q.jsx)(`span`,{className:`font-semibold`,children:e.label})]}),ce&&(0,q.jsx)(`a`,{href:ce.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`opacity-70 hover:opacity-100 ml-0.5 inline-flex items-center`,onClick:e=>e.stopPropagation(),children:(0,q.jsx)(Ye,{weight:`bold`,className:`h-2.5 w-2.5`})})]},`${e.kind}:${e.slug}`)}),H.map(e=>(0,q.jsxs)(`div`,{className:`pointer-events-auto inline-flex items-center gap-0.5 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium bg-primary/10 text-primary border-primary/30 whitespace-nowrap`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:e.soundProfileId?`Tag ${e.label} · names the ${e.soundProfileId} sound profile`:`Tag ${e.label}`,onClick:t=>{if(l){l({kind:`tag`,label:e.slug||e.label});return}de(`token`,T.tokens.find(t=>t.isTag&&t.raw.includes(e.slug))??{id:`tag-${e.slug}`,kind:`tag`,raw:`#${e.slug}`,displayLabel:`#${e.slug}`,from:p.lineFrom,to:p.lineTo,lineNum:p.cursorLine,tagRef:e,isTag:!0},t.currentTarget)},className:`inline-flex items-center gap-0.5 cursor-pointer hover:opacity-80`,children:[(0,q.jsx)(`span`,{children:`#`}),(0,q.jsx)(`span`,{className:`font-semibold font-mono`,children:e.label})]}),ce&&(0,q.jsx)(`a`,{href:ce.openHref(`tag`,e.slug),title:`Open the ${e.label} tag`,"aria-label":`Open the ${e.label} tag`,className:`opacity-70 hover:opacity-100 ml-0.5 inline-flex items-center`,onClick:e=>e.stopPropagation(),children:(0,q.jsx)(Ye,{weight:`bold`,className:`h-2.5 w-2.5`})})]},`tag:${e.slug}`)),ae.map(t=>(0,q.jsxs)(`span`,{className:`pointer-events-auto inline-flex items-center gap-1 px-1.5 py-0.5 min-h-[22px] rounded-full border border-dashed text-[11px] leading-tight font-medium bg-destructive/10 text-destructive border-destructive/30 whitespace-nowrap`,title:t.message,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{className:`font-mono`,children:t.raw}),t.fixes.slice(0,2).map(n=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:r=>{r.stopPropagation(),e&&f4(e,t,n)},className:`rounded-full bg-background/80 px-1.5 py-0.5 font-mono text-[10px] font-semibold text-foreground hover:bg-primary hover:text-primary-foreground cursor-pointer transition-colors`,children:[`Fix: `,n]},n))]},t.id)),oe&&(0,q.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-[4px] border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:`Malformed reference JSON`})]}),ie.map(e=>(0,q.jsxs)(`span`,{"data-testid":`editor-tag-unknown`,title:`Unknown tag #${e} — click to define`,className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-dashed text-[11px] leading-tight font-medium bg-warning/10 text-warning border-warning/40 whitespace-nowrap`,children:[l?(0,q.jsxs)(`button`,{type:`button`,onClick:()=>l({kind:`unrecognized`,term:`#${e}`}),className:`font-mono font-semibold cursor-pointer hover:text-foreground`,children:[`#`,e]}):(0,q.jsxs)(`span`,{className:`font-mono font-semibold`,children:[`#`,e]}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-create-tag-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold ml-0.5`,onClick:t=>{t.stopPropagation(),l?l({kind:`unrecognized`,term:`#${e}`}):ve(e)},children:`+ Tag`})]},`unresolved-tag:${e}`)),re.map((e,t)=>{let n=le(e),r=e.token?.trim()??``,i=e.reason===`unknown-effort`,a=`${e.reason}-${r||t}`,o=!l&&(h===a||h===`all`);return(0,q.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,onClick:()=>{if(l&&r){l({kind:`unrecognized`,term:r});return}o||g(a)},className:$(`pointer-events-auto inline-flex flex-wrap items-center gap-1.5 px-2 py-0.5 min-h-[22px] rounded-[6px] border border-dashed text-[11px] leading-tight font-medium bg-warning/10 text-warning border-warning/40 max-w-full`,!o&&`rounded-full whitespace-nowrap cursor-pointer hover:bg-warning/15`),children:[(0,q.jsx)(`span`,{children:`?`}),(0,q.jsx)(`span`,{className:`font-semibold`,children:e.token??e.reason}),o?(0,q.jsxs)(`span`,{className:`inline-flex flex-wrap items-center gap-1.5 pl-1 border-l border-warning/30`,children:[r&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":`editor-create-${n}-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),ge(n,r)},children:[`+ `,n===`effort`?`Effort`:`Equipment`]}),r&&i&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-link-alias-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),_e(r)},children:`+ Alias`}),r&&i&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-create-equipment-from-token`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),ge(`equipment`,r)},children:`+ Equipment`}),(0,q.jsx)(`button`,{type:`button`,className:`underline cursor-pointer hover:text-foreground`,onClick:t=>{t.stopPropagation(),he(e)},children:`Select existing`}),ce&&(0,q.jsx)(`a`,{href:ce.createHref(n),className:`underline hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`Create page`})]}):(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-define-token`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{if(e.stopPropagation(),l&&r){l({kind:`unrecognized`,term:r});return}g(a)},children:`Define`})]},a)}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void pe(),className:`pointer-events-auto inline-flex items-center px-2 py-0.5 min-h-[22px] rounded-full border border-dashed border-border text-[11px] leading-tight text-muted-foreground hover:text-foreground hover:border-foreground cursor-pointer whitespace-nowrap`,children:`+ Metric`}),Se&&Ce&&(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,title:`Configure ${we.toUpperCase()} block header or templates`,onClick:e=>de(`block`,T.tokens[0]??null,e.currentTarget),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-border bg-muted/40 text-[11px] leading-tight font-medium text-muted-foreground hover:text-foreground cursor-pointer whitespace-nowrap`,children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:we===`log`?`LOG`:`TIMER`})]}),c&&(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_INSPECTOR_DRAWER_TOGGLE,"aria-pressed":o,title:`Toggle Right Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,onClick:()=>{o||u?.(),c()},className:$(`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium cursor-pointer whitespace-nowrap transition-colors`,o?`border-primary bg-primary/10 text-primary`:`border-border bg-muted/40 text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(Nee,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:`Drawer`})]})]}):(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground/70 italic select-none`,children:`No metrics on this line`}),Se&&Ce&&(0,q.jsx)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,onClick:e=>de(`add`,null,e.currentTarget),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-dashed border-border bg-card/70 text-[11px] text-muted-foreground hover:bg-card hover:text-foreground hover:border-foreground/40 transition-colors cursor-pointer`,children:`+ Token`})]})}),!s&&y&&(0,q.jsx)(x4,{open:!0,anchorRect:y.anchorRect,editorDom:e?.dom??null,view:e,mode:y.mode,inspection:T,token:Te??y.token,scope:_,docText:w,onClose:()=>b(null),onMutate:(e,t)=>{C()},onModeChange:e=>b(t=>t&&{...t,mode:e}),onStepToken:e=>{if(!y||T.tokens.length===0)return;let t=T.tokens.findIndex(e=>e.id===(Te?.id??y.token?.id)),n=((t>=0?t:0)+e+T.tokens.length)%T.tokens.length;b(e=>e&&{...e,token:T.tokens[n]})}})]})},rge=`[data-page-sticky-boundary="true"]`;function ige(e){if(e)return e;let t=document.querySelector(`[data-mobile-editor-deck="true"]`);if(t)return t;for(let e of document.querySelectorAll(`[data-testid]`)){let t=e.getAttribute(`data-testid`);if(t===Q.MOBILE_WHEEL_COMPOSER||t===Q.MOBILE_TYPING_BAR)return e}return null}function age(e){let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){let e=t.getAttribute(`data-testid`);if(e===`tour-runway`||e===`scroll-runway-section`||e?.startsWith(`guide-runway-`))return!0;t=t.parentElement}return!1}function oge(e,t){if(typeof window>`u`||typeof document>`u`)return{safeTop:14,safeBottom:58,idealCenterY:36,vvHeight:0,keyboardOffsetBottom:0};let n=window.visualViewport,r=n?.offsetTop??0,i=n?.height??window.innerHeight,a=r+i,o=Math.max(0,window.innerHeight-a),s=0,c=document.querySelectorAll(rge);for(let t of c){if(t.contains(e.dom))continue;let n=t.getBoundingClientRect();n.height<=0||n.bottom<=0||(s=Math.max(s,n.bottom))}let l=s>0?s:r,u=a,d=ige(t);if(d){let e=d.getBoundingClientRect();e.height>0&&e.top>0&&(u=Math.min(a,e.top))}let f=Math.max(r,l)+14,p=Math.max(f+44,u-14);return{safeTop:f,safeBottom:p,idealCenterY:f+(p-f)*.46,vvHeight:i,keyboardOffsetBottom:o}}function sge(e){if(typeof window>`u`)return null;let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){if(window.getComputedStyle(t).position===`sticky`)return t;t=t.parentElement}return null}function cge(e){let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t).overflowY;if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight+1)return t;t=t.parentElement}return null}function w4(e,t,n){let r=cge(e);if(r&&typeof r.scrollBy==`function`){let e=r.scrollTop;return r.scrollBy({top:t,behavior:n}),r.scrollTop-e}if(typeof window.scrollBy==`function`){let e=window.scrollY;return window.scrollBy({top:t,behavior:n}),window.scrollY-e}return 0}function T4(e,t){if(typeof window>`u`||!e||!e.dom||window.visualViewport&&window.visualViewport.scale>1.05)return!1;let n=t?.pos??e.state.selection.main.head,r;try{r=e.coordsAtPos(n)}catch{return!1}if(!r||r.top===0&&r.bottom===0)return!1;let{safeTop:i,safeBottom:a,idealCenterY:o}=oge(e,t?.overlayEl);if(r.top>=i&&r.bottom<=a&&!t?.forceCenter)return!1;let s=(r.top+r.bottom)/2-o;if(Math.abs(s)<=1)return!1;let c=age(e.dom),l=sge(e.dom),u=t?.behavior??`auto`;if(!c&&l){let t=l.getBoundingClientRect();if(t.height>0){let n=Number.parseFloat(window.getComputedStyle(l).top),r=Number.isFinite(n)?n:0;if(s>0&&t.top>r+1){let n=Math.max(s,t.bottom-a),i=Math.min(n,t.top-r);if(i>2){let t=w4(e.dom,i,u);s-=t===0?i:t}}else if(s<0&&t.top<r-1){let n=Math.max(s,t.top-r);if(n<-2){let t=w4(e.dom,n,u);s-=t===0?n:t}}}}let d=e.scrollDOM;if(d&&Math.abs(s)>1){let e=window.getComputedStyle(d),t=d.scrollHeight-d.clientHeight;if(t>1&&e.overflowY!==`hidden`&&e.overflowY!==`visible`){let e=d.scrollTop,n=Math.max(0,Math.min(t,e+s)),r=n-e;Math.abs(r)>.5&&(d.scrollTop=n,s-=r)}}return Math.abs(s)>2&&!c&&!l&&w4(e.dom,s,u),!0}var lge={tags:[],defaultEquipment:[],customMetricTypes:[]},uge=[{label:`#`,ariaLabel:`Insert tag prefix #`,insert:`#`,triggerComplete:!0},{label:`@`,ariaLabel:`Insert resistance prefix @`,insert:`@`},{label:`*`,ariaLabel:`Insert rest prefix *`,insert:`*`},{label:`:`,ariaLabel:`Insert timer separator :`,insert:`:`},{label:`[:`,ariaLabel:`Insert action cue [:`,insert:`[:`,triggerComplete:!0},{label:`()`,ariaLabel:`Insert rounds parentheses ()`,insert:`()`,cursorOffset:1},{label:`[[`,ariaLabel:`Insert wiki link [[`,insert:`[[`,triggerComplete:!0},{label:`|`,ariaLabel:`Insert WQL pipe |`,insert:` | `}];function dge(e){switch(e.type){case`variable`:return`bg-metric-effort`;case`unit`:return`bg-metric-resistance`;case`constant`:return`bg-metric-action`;case`keyword`:return`bg-metric-time`;case`property`:return`bg-muted-foreground`;default:return`bg-primary`}}function fge(e){let t=e.metricType?.toLowerCase();if(t===`duration`)return`duration`;if(t===`rep`)return`rep`;if(t===`rounds`)return`rounds`;if(t===`effort`)return`effort`;if(t===`equipment`)return`equipment`;if(t===`resistance`)return`resistance`;if(t===`distance`)return`distance`;if(t===`action`)return`action`;let n=e.rawText.trim();return n.startsWith(`#`)?`tag`:/^\*?\d+:\d{2}$/.test(n)||n.startsWith(`:`)?`duration`:`custom`}function pge(e,t,n){if(!e||e.kind!==`metric`)return n[0]??null;let r=n.find(t=>Math.max(t.from,e.from)<Math.min(t.to,e.to)||t.from===e.from&&t.to===e.to);if(r)return r;let i=e.rawText.trim()||e.label,a=fge(e),o={id:`slot-${e.id}`,kind:a,raw:i,displayLabel:a===`rep`?`${i} reps`:e.label||i,from:e.from,to:e.to,lineNum:t,isTag:i.startsWith(`#`),isRest:a===`duration`&&i.startsWith(`*`)};return a===`duration`&&(o.durationMeta=r4(i)),a===`resistance`&&(o.resistanceMeta=a4(i)),a===`distance`&&(o.distanceMeta=s4(i)),o}var mge=({view:e,noteId:t,cursorVersion:n,isOpen:r,isTypingMode:i,onSwitchToTyping:a,onDeckInteract:o,onClose:s})=>{let[l,u]=(0,K.useState)(lge),[d,f]=(0,K.useState)(null),[p,m]=(0,K.useState)(!1),[h,g]=(0,K.useState)(`token`),_=(0,K.useRef)(-1),v=(0,K.useRef)(null),y=(0,K.useRef)(null),[b,x]=(0,K.useState)(null),S=(0,K.useCallback)(e=>{y.current=e,x(e)},[]),C=(0,K.useRef)(0),w=(0,K.useRef)(null),[T,E]=(0,K.useState)({height:null,offsetTop:0,keyboardOffsetBottom:0}),[D,O]=(0,K.useState)(0),k=e?.state.doc.toString()??``;(0,K.useEffect)(()=>{if(!(typeof document>`u`))return r&&e?document.documentElement.dataset.mobileEditorOpen=`true`:delete document.documentElement.dataset.mobileEditorOpen,()=>{delete document.documentElement.dataset.mobileEditorOpen}},[r,e]),(0,K.useEffect)(()=>{if(!r||!e)return;let n=!1;return Z2(t,k).then(e=>{n||u(e)}),()=>{n=!0}},[r,t,k,e]),(0,K.useEffect)(()=>{if(!r||typeof window>`u`){E({height:null,offsetTop:0,keyboardOffsetBottom:0});return}let e=window.visualViewport;if(!e){E({height:window.innerHeight,offsetTop:0,keyboardOffsetBottom:0});return}let t=0,n=()=>{t=0;let n=Math.max(0,window.innerHeight-(e.height+e.offsetTop));E(t=>t.height===e.height&&t.offsetTop===e.offsetTop&&t.keyboardOffsetBottom===n?t:{height:e.height,offsetTop:e.offsetTop,keyboardOffsetBottom:n})},i=()=>{t||=requestAnimationFrame(n)};return n(),e.addEventListener(`resize`,i),e.addEventListener(`scroll`,i),()=>{t&&cancelAnimationFrame(t),e.removeEventListener(`resize`,i),e.removeEventListener(`scroll`,i)}},[r]),(0,K.useEffect)(()=>{if(typeof document>`u`)return;if(!r||!e||!b){document.documentElement.style.removeProperty(`--mobile-editor-inset`);return}let t=()=>{let e=Math.round(b.getBoundingClientRect().height)+T.keyboardOffsetBottom;document.documentElement.style.setProperty(`--mobile-editor-inset`,`${e}px`)};t();let n=typeof ResizeObserver<`u`?new ResizeObserver(t):null;return n?.observe(b),()=>{n?.disconnect(),document.documentElement.style.removeProperty(`--mobile-editor-inset`)}},[r,e,b,T.keyboardOffsetBottom]),(0,K.useEffect)(()=>{if(!e)return;let t=e.state.doc.lineAt(e.state.selection.main.head).number;t!==_.current&&(_.current=t,f(null),g(`token`),m(!1))},[e,n]);let A=(0,K.useMemo)(()=>!e||!r?null:jhe(e.state,l,d),[e,r,l,d,n]),j=(0,K.useMemo)(()=>!e||!r?null:l4(e.state),[e,r,n]),M=(0,K.useCallback)(t=>{if(!e||!r)return;C.current&&cancelAnimationFrame(C.current),w.current!==null&&(window.clearTimeout(w.current),w.current=null);let n=()=>{T4(e,{pos:t?.pos,overlayEl:y.current,forceCenter:t?.forceCenter})};C.current=requestAnimationFrame(()=>{C.current=0,n()}),t?.followUp&&(w.current=window.setTimeout(()=>{w.current=null,n()},120))},[e,r]);(0,K.useEffect)(()=>()=>{C.current&&cancelAnimationFrame(C.current),w.current!==null&&window.clearTimeout(w.current)},[]),(0,K.useEffect)(()=>{!r||!e||M({forceCenter:!0,followUp:!0})},[r,e,i,T.keyboardOffsetBottom,T.height,h,p,M]),(0,K.useEffect)(()=>{!r||!e||M()},[r,e,n,M]);let N=(0,K.useCallback)(t=>{if(!e||!A||A.slots.length===0)return;let n=Math.max(0,Math.min(A.slots.length-1,t)),r=A.slots[n];f(n),g(`token`),m(!1),r.kind===`metric`?(e.dispatch({selection:{anchor:r.from,head:r.to}}),M({pos:r.from})):r.kind===`add-metric`?(e.dispatch({selection:{anchor:r.from,head:r.from}}),M({pos:r.from})):r.kind===`query-stage`&&O(e=>e+1)},[e,A,M]),P=(0,K.useCallback)(e=>{A&&N(A.activeSlotIndex+e)},[A,N]),F=(0,K.useCallback)((t,n)=>{if(!e||!A)return;let r=A.slots[A.activeSlotIndex];if(r){if(A.context===`workout`&&r.kind===`add-metric`){let t=e.state.doc.lineAt(e.state.selection.main.head),r=t.text.length>0&&!/\s$/.test(t.text),i=`${r?` `:``}${n.value}`,a=t.to+ +!!r,o=t.to+i.length;f(null),g(`token`),m(n.id===`add-weight`||n.id===`add-duration`),e.dispatch({changes:{from:t.to,to:t.to,insert:i},selection:{anchor:a,head:o},userEvent:`input.wheel`}),M({pos:a});return}if(A.context===`workout`){let i=n.value;(t.id===`duration-min`||t.id===`duration-sec`)&&(i=n.value);let a=r.from+i.length;e.dispatch({changes:{from:r.from,to:r.to,insert:i},selection:{anchor:r.from,head:a},userEvent:`input.wheel`}),M({pos:r.from})}}},[e,A,M]),I=(0,K.useCallback)(()=>{if(!e)return;let t=e.state.selection.main.head,n=e.state.doc.lineAt(t),r=n.text.match(/^(\s*)/),i=`\n${r?r[1]:``}`,a=n.to+i.length;f(null),g(`token`),e.dispatch({changes:{from:n.to,to:n.to,insert:i},selection:{anchor:a},userEvent:`input.wheel`}),M({pos:a})},[e,M]),ee=(0,K.useCallback)(()=>{e&&(e.contentDOM.setAttribute(`inputmode`,`text`),a(!0),e.focus())},[e,a]),L=(0,K.useCallback)(()=>{e&&(_a(e),e.contentDOM.setAttribute(`inputmode`,`none`),a(!1),e.focus())},[e,a]),R=(0,K.useCallback)(()=>{e&&_a(e),typeof document<`u`&&(delete document.documentElement.dataset.mobileEditorOpen,document.documentElement.style.removeProperty(`--mobile-editor-inset`)),e?.contentDOM.blur(),s()},[e,s]),z=(0,K.useCallback)(t=>{if(!e)return;let n=e.state.selection.main,r=n.from+(t.cursorOffset??t.insert.length);e.dispatch({changes:{from:n.from,to:n.to,insert:t.insert},selection:{anchor:r},userEvent:`input`}),e.focus(),M({pos:r}),t.triggerComplete&&queueMicrotask(()=>{va(e)})},[e,M]),B=(0,K.useCallback)(e=>{if(e.target?.closest(`[role="listbox"], input, textarea, select`)){v.current=null;return}if(e.currentTarget.scrollWidth>e.currentTarget.clientWidth+4){v.current=null;return}v.current={x:e.clientX,y:e.clientY}},[]),V=(0,K.useCallback)((e,t)=>{let n=v.current;if(v.current=null,!n)return;let r=e-n.x,i=t-n.y;Math.abs(r)>=28&&Math.abs(r)>Math.abs(i)*1.2&&P(r<0?1:-1)},[P]);if(!r||!e||!A||!j)return null;let H=A.slots[A.activeSlotIndex],U=pge(H,A.lineNumber,j.tokens),te=h===`block`||h===`add`||h===`wiki`||h===`prose-tag`?h:A.context===`query`?`query`:A.context===`markdown`?`markdown`:`token`,W=A.context===`workout`&&H?.kind===`metric`&&U!==null&&te===`token`,{height:ne,keyboardOffsetBottom:re}=T;if(i){let t=Da(e.state)===`active`?io(e.state).slice(0,18):[],n=t=>{e.dispatch({effects:Ta(t)}),ja(e),e.focus()};return(0,q.jsxs)(`div`,{ref:S,"data-testid":`mobile-typing-bar`,"data-mobile-editor-deck":`true`,onPointerDownCapture:()=>o?.(),style:{bottom:`${re}px`,...re>0?{paddingBottom:0}:{}},className:`fixed inset-x-0 z-40 flex flex-col border-t border-border bg-card text-card-foreground shadow-lg select-none overscroll-contain pb-[env(safe-area-inset-bottom,0px)]`,children:[t.length>0&&(0,q.jsx)(`div`,{role:`listbox`,"aria-label":`Autocomplete suggestions`,className:`flex min-h-[44px] items-center gap-1.5 overflow-x-auto border-b border-border bg-muted/30 px-2 py-1 scrollbar-none`,children:t.map((e,t)=>(0,q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":!1,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),className:`inline-flex h-9 min-w-[44px] shrink-0 items-center gap-1.5 rounded-full border border-border bg-background px-3 text-xs text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(`span`,{"aria-hidden":`true`,className:$(`h-1.5 w-1.5 shrink-0 rounded-full`,dge(e))}),(0,q.jsx)(`span`,{className:`font-mono font-semibold whitespace-nowrap`,children:e.displayLabel??e.label}),e.detail&&(0,q.jsx)(`span`,{className:`max-w-[96px] truncate text-[11px] text-muted-foreground`,children:e.detail})]},`${e.label}-${t}`))}),(0,q.jsxs)(`div`,{className:`flex min-h-[48px] items-center gap-1.5 overflow-x-auto overscroll-x-contain border-b border-border bg-muted/40 px-2.5 scrollbar-none`,children:[(0,q.jsxs)(`span`,{className:`shrink-0 font-mono text-[11px] font-semibold text-muted-foreground tabular-nums`,children:[`L`,A.lineNumber]}),A.slots.map((e,t)=>{let n=t===A.activeSlotIndex;return(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>{N(t),L()},className:$(`shrink-0 min-h-[44px] rounded-full border px-3 text-xs font-mono tabular-nums transition-colors cursor-pointer`,n?`border-primary bg-primary text-primary-foreground font-semibold`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:e.label},e.id)})]}),(0,q.jsxs)(`div`,{className:`flex min-h-[48px] items-center justify-between gap-1.5 px-2 py-1`,children:[(0,q.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-x-auto overscroll-x-contain scrollbar-none`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-return-wheel-btn`,onMouseDown:e=>e.preventDefault(),onClick:L,className:`inline-flex h-11 shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Deck`})]}),uge.map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-label":e.ariaLabel,onMouseDown:e=>e.preventDefault(),onClick:()=>z(e),className:`inline-flex h-11 min-w-[44px] shrink-0 items-center justify-center rounded-md border border-border bg-background px-2 font-mono text-xs font-semibold text-foreground hover:bg-muted cursor-pointer transition-colors`,children:e.label},e.label)),(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>Za(e),"aria-label":`Outdent line`,className:`inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(vee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>za(e),"aria-label":`Indent line`,className:`inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(oee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsxs)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:I,className:`inline-flex h-11 shrink-0 items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Dt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Line`})]})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-done-btn`,onMouseDown:e=>e.preventDefault(),onClick:R,className:`inline-flex h-11 shrink-0 items-center gap-1 rounded-md bg-primary px-3 text-xs font-semibold text-primary-foreground cursor-pointer`,children:[(0,q.jsx)(tt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Done`})]})]})]})}let ie={bottom:`${re}px`,...ne!==null&&re>0?{paddingBottom:0,height:`${Math.min(276,Math.max(184,Math.round(ne*.52)))}px`,minHeight:`184px`}:ne===null?{}:{maxHeight:`${Math.min(360,Math.max(252,Math.round(ne*.44)))}px`}};return(0,q.jsxs)(`section`,{ref:S,"aria-label":`Mobile workout and note thumb deck`,"data-testid":`mobile-wheel-composer`,"data-mobile-editor-deck":`true`,onPointerDownCapture:()=>o?.(),onMouseDown:e=>{e.target.tagName!==`INPUT`&&e.preventDefault()},style:ie,className:`fixed inset-x-0 bottom-0 z-40 h-[min(42svh,360px)] max-h-[380px] min-h-[252px] flex flex-col border-t border-border bg-card text-card-foreground shadow-xl select-none overscroll-contain pb-[env(safe-area-inset-bottom,0px)]`,children:[(0,q.jsxs)(`div`,{"data-testid":`mobile-wheel-slot-rail`,onPointerDown:B,onPointerUp:e=>V(e.clientX,e.clientY),className:`flex min-h-[48px] items-center gap-1.5 overflow-x-auto overscroll-x-contain border-b border-border bg-muted/40 px-2 scrollbar-none`,children:[(0,q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 pr-1`,children:[(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-prev-slot`,"aria-label":`Previous slot`,disabled:A.activeSlotIndex<=0,onClick:()=>P(-1),className:`inline-flex h-11 w-11 items-center justify-center rounded-md border border-border bg-background text-foreground disabled:opacity-35 hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(c,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-next-slot`,"aria-label":`Next slot`,disabled:A.activeSlotIndex>=A.slots.length-1,onClick:()=>P(1),className:`inline-flex h-11 w-11 items-center justify-center rounded-md border border-border bg-background text-foreground disabled:opacity-35 hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(dee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsxs)(`span`,{className:`pl-1 font-mono text-[11px] font-semibold uppercase tracking-wide text-muted-foreground tabular-nums`,children:[`L`,A.lineNumber]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[A.slots.map((e,t)=>{let n=t===A.activeSlotIndex&&h!==`block`,r=e.kind===`add-metric`;return(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-slot-${e.kind===`add-metric`?`add`:t}`,onClick:()=>N(t),className:$(`shrink-0 min-h-[44px] rounded-full border px-3 text-xs font-mono tabular-nums transition-colors cursor-pointer`,n?`border-primary bg-primary text-primary-foreground font-semibold`:r?`border-dashed border-border bg-background text-foreground hover:bg-muted`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:e.label},e.id)}),j.lintFixes.map(t=>t.fixes.slice(0,1).map(n=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:()=>f4(e,t,n),className:`inline-flex min-h-[44px] shrink-0 items-center gap-1 rounded-full border border-dashed border-destructive/40 bg-destructive/10 px-2.5 text-xs font-mono font-semibold text-destructive hover:bg-destructive hover:text-destructive-foreground cursor-pointer transition-colors`,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3.5 w-3.5 shrink-0`}),(0,q.jsxs)(`span`,{children:[`Fix: `,n]})]},`${t.id}:${n}`))),A.context===`workout`&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,"aria-pressed":te===`block`,onClick:()=>g(e=>e===`block`?`token`:`block`),className:$(`inline-flex min-h-[44px] shrink-0 items-center gap-1 rounded-full border px-2.5 text-xs font-medium cursor-pointer transition-colors`,te===`block`?`border-primary bg-primary/15 text-primary font-semibold`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3.5 w-3.5 shrink-0`}),(0,q.jsx)(`span`,{children:`Block`})]})]})]}),(0,q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain px-3 py-2.5`,children:A.context===`workout`&&H?.kind===`add-metric`&&te!==`block`&&te!==`add`?(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:[`Append metric to line `,A.lineNumber]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>g(`add`),className:`inline-flex min-h-[44px] items-center rounded-md px-2.5 text-xs font-medium text-primary hover:bg-primary/10 cursor-pointer`,children:`Full Catalog`})]}),(0,q.jsx)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:(A.drums[0]?.options??[]).map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":`wheel-option-${e.id}`,onClick:()=>{A.drums[0]&&F(A.drums[0],e)},className:`flex min-h-[44px] w-full items-center justify-between gap-2 rounded-lg border border-border bg-popover px-3 py-2 text-left text-popover-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.label}),e.sublabel&&(0,q.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground tabular-nums`,children:e.sublabel})]},e.id))})]}):(0,q.jsx)(v4,{view:e,mode:te,inspection:j,token:U,scope:l,docText:k,useScrubber:p,onToggleScrubber:()=>m(e=>!e),compact:!0,showHeader:!1,showFooter:!1,showStepButtons:!1,showClose:!1,showDockButton:!1,activeQueryStageId:H?.kind===`query-stage`?H.id:void 0,queryStageRequestToken:D,onModeChange:e=>g(e),onMutate:()=>{M()}})}),(0,q.jsxs)(`div`,{className:`flex min-h-[52px] items-center justify-between gap-1.5 border-t border-border bg-muted/40 px-2.5 py-1`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{Ua(e),e.focus()},"aria-label":`Undo last edit`,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(ct,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Undo`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_TOKEN_DELETE_BTN,disabled:!W,onClick:()=>{U&&(d4(e,U),f(null))},className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-destructive disabled:opacity-35 hover:bg-destructive/10 cursor-pointer transition-colors`,children:[(0,q.jsx)(Wr,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Delete`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-newline-btn`,onClick:I,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Dt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Line`})]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-type-btn`,onClick:ee,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Pt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Type`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-done-btn`,onClick:R,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md bg-primary px-3 text-xs font-semibold text-primary-foreground cursor-pointer transition-colors`,children:[(0,q.jsx)(tt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Done`})]})]})]})]})},hge=({view:e,cursorVersion:t,disabled:n=!1})=>{let[r,i]=(0,K.useState)(null);if((0,K.useEffect)(()=>{if(!e||n||e.state.readOnly){i(null);return}let t=e.state.selection.main;if(t.empty||!e.hasFocus){i(null);return}let r=uM(e.state);if(!r||r.type!==`markdown`){i(null);return}let a=e.coordsAtPos(t.from),o=e.coordsAtPos(t.to),s=e.dom.getBoundingClientRect();if(!a||!o){i(null);return}let c=(a.left+o.right)/2-s.left,l=Math.max(96,Math.min(s.width-96,c)),u=e.state.doc.lineAt(t.from),d=u.number>1&&/^#{1,6}\s/.test(e.state.doc.line(u.number-1).text),f=a.top-s.top-38,p=f<48||d?o.bottom-s.top+6:f;i({top:p,left:l})},[e,t,n]),!r||!e)return null;let a=[{id:`bold`,label:`Bold (Ctrl+B)`,Icon:yr,run:()=>{TM(e,`**`),e.focus()}},{id:`italic`,label:`Italic (Ctrl+I)`,Icon:Zr,run:()=>{TM(e,`*`),e.focus()}},{id:`strike`,label:`Strikethrough`,Icon:mr,run:()=>{TM(e,`~~`),e.focus()}},{id:`code`,label:`Inline code (Ctrl+E)`,Icon:k,run:()=>{TM(e,"`"),e.focus()}},{id:`link`,label:`Insert link (Ctrl+Shift+K)`,Icon:S,run:()=>{EM(e),e.focus()}},{id:`timer`,label:`Wrap in timer block`,Icon:nr,run:()=>{let t=e.state.selection.main;if(t.empty)return;let n=e.state.doc.sliceString(t.from,t.to),r=`\n\`\`\`time\n${n}\n\`\`\`\n`;e.dispatch({changes:{from:t.from,to:t.to,insert:r},selection:{anchor:t.from+9,head:t.from+9+n.length},userEvent:`input.format`}),e.focus()}}];return(0,q.jsx)(`div`,{role:`toolbar`,"aria-label":`Text formatting`,"data-testid":`selection-format-bar`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},style:{position:`absolute`,top:`${r.top}px`,left:`${r.left}px`,transform:`translateX(-50%)`,boxShadow:`0 2px 8px rgba(0, 0, 0, 0.04)`},className:`z-30 hidden lg:inline-flex items-center gap-0.5 px-1 py-0.5 rounded-[6px] bg-card border border-border text-foreground`,children:a.map(({id:e,label:t,Icon:n,run:r})=>(0,q.jsx)(`button`,{type:`button`,title:t,"aria-label":t,"data-testid":`format-bar-${e}`,onClick:r,className:`inline-flex items-center justify-center h-6 w-6 rounded-[4px] text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:(0,q.jsx)(n,{weight:`bold`,className:`h-3.5 w-3.5`})},e))})},gge=({open:e,layout:t=`docked-right`,view:n,mode:r,inspection:i,token:a,scope:o,docText:s,lastEditDiff:c,onClose:l,onModeChange:u,onMutate:d,onStepToken:f})=>{let[p,m]=(0,K.useState)(!0),h=HY(65),g=i.section?.type,_=g===`time`||g===`log`,v=(0,K.useMemo)(()=>!n||!_||!i.section?[]:u4(n.state,i.section),[n,_,i]);if((0,K.useEffect)(()=>{if(!e||t!==`docked-right`)return;let r=e=>{e.key===`Escape`&&typeof window<`u`&&window.innerWidth<1280&&(e.preventDefault(),e.stopPropagation(),l(),n?.focus())};return document.addEventListener(`keydown`,r,!0),()=>document.removeEventListener(`keydown`,r,!0)},[e,t,l,n]),!e)return null;let y=e=>{if(!n||e<1||e>n.state.doc.lines)return;let t=n.state.doc.line(e);n.dispatch({selection:_o.cursor(t.from),scrollIntoView:!0}),n.focus()};return(0,q.jsxs)(q.Fragment,{children:[t===`docked-right`&&(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":`Close inspector drawer`,onClick:l,className:`xl:hidden fixed inset-0 z-[29] bg-black/20 cursor-default`}),(0,q.jsxs)(`aside`,{role:`complementary`,"aria-label":`Focused Token Inspector Drawer`,"data-testid":Q.EDITOR_INSPECTOR_DRAWER,style:t===`docked-right`?{"--inspector-sticky-top":`${h}px`}:void 0,className:$(`flex flex-col overflow-hidden border-l border-border bg-card text-card-foreground`,t===`docked-right`?`fixed right-0 bottom-0 z-30 w-[340px] max-w-[92vw] max-xl:top-[var(--inspector-sticky-top)] max-xl:shadow-xl xl:top-0 xl:shadow-none`:`w-[340px] max-w-full shrink-0`),children:[(0,q.jsxs)(`div`,{className:`flex items-start justify-between gap-2 border-b border-border bg-muted/40 px-3 py-2.5`,children:[(0,q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,q.jsx)(`div`,{className:`flex items-center gap-1.5`,children:(0,q.jsx)(`h2`,{className:`truncate text-xs font-semibold uppercase tracking-wide text-foreground`,children:`Focused Token Inspector`})}),(0,q.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums`,children:[(0,q.jsxs)(`span`,{children:[`Ln `,i.lineNum,` · `,i.tokens.length,` token`,i.tokens.length===1?``:`s`]}),c&&(0,q.jsxs)(`span`,{"data-testid":Q.EDITOR_INSPECTOR_DIFF_BADGE,className:`inline-flex items-center rounded bg-primary/10 px-1.5 py-0.5 font-mono text-[11px] font-medium text-primary`,title:`Last change: ${c.from} -> ${c.to}`,children:[c.from,` → `,c.to]})]})]}),(0,q.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Close inspector drawer`,title:`Close Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground cursor-pointer`,children:(0,q.jsx)(Mt,{className:`h-4 w-4`})})]}),(0,q.jsxs)(`div`,{className:`flex-1 overflow-y-auto divide-y divide-border`,children:[(0,q.jsx)(v4,{view:n,mode:r,inspection:i,token:a,scope:o,docText:s,useScrubber:p,onToggleScrubber:()=>m(e=>!e),compact:!1,showHeader:!0,showFooter:!1,showStepButtons:r===`token`,showClose:!1,showDockButton:!1,onMutate:d,onModeChange:u,onStepToken:f}),_&&v.length>0&&(0,q.jsxs)(`div`,{className:`px-3 py-2.5`,children:[(0,q.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,q.jsx)(xr,{className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Block Runtime Preview`})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>u?.(`block`),className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground cursor-pointer`,children:[(0,q.jsx)(Pi,{className:`h-3 w-3`}),(0,q.jsx)(`span`,{children:`Configure`})]})]}),(0,q.jsx)(`div`,{className:`overflow-hidden rounded-lg bg-muted/35 divide-y divide-border/60`,children:v.map(e=>{let t=e.lineNum===i.lineNum;return(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_TIMELINE_ROW,onClick:()=>y(e.lineNum),className:$(`flex w-full items-center justify-between gap-2 px-2.5 py-2 text-left text-xs transition-colors cursor-pointer`,t?`bg-primary/10 text-foreground font-medium`:`text-muted-foreground hover:bg-muted/70 hover:text-foreground`),children:[(0,q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,q.jsx)(`span`,{className:`w-5 shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums`,children:e.lineNum}),(0,q.jsx)(`span`,{className:$(`truncate`,e.isRest&&`italic text-muted-foreground`),children:e.label})]}),(0,q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[e.hasError&&(0,q.jsx)(oe,{className:`h-3.5 w-3.5 text-destructive`,"aria-label":`Line has syntax warning`}),e.durationLabel&&(0,q.jsx)(`span`,{className:`rounded bg-background/80 px-1.5 py-0.5 font-mono text-[11px] text-foreground tabular-nums`,children:e.durationLabel})]})]},e.lineNum)})})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`inline-flex items-center gap-1 font-medium text-foreground`,children:(0,q.jsx)(Ve,{className:`h-3 w-3`})}),(0,q.jsx)(`span`,{children:`Ctrl+Space Typeahead`}),(0,q.jsx)(`span`,{children:`/ Blocks`}),(0,q.jsx)(`span`,{children:`Alt+. Popover`}),(0,q.jsx)(`span`,{children:`Ctrl+Alt+I / Cmd+Alt+I Drawer`}),(0,q.jsx)(`span`,{children:`Ctrl+←/→ Step`}),(0,q.jsx)(`span`,{children:`Alt+↑/↓ Value`})]})]})]})},E4=new oo,D4=new oo,O4=new oo,k4=new oo;async function A4(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 _ge(e){let t=await A4(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function vge(e){let t=await A4(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${aE()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var j4=Ga.define();function yge(){let e=PV,t=K.useContext(MV);return e?e():t??null}var M4=({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=``,ariaLabel:g=`Note editor`,onStartWorkout:_,onCompleteWorkout:v,onBlocksChange:y,onAddToPlan:b,notePersistence:x,onViewCreated:S,mode:C=`edit`,lineWrapping:w=!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:ee,placeholder:L,defaultInspectorDrawerOpen:R=!1,inspectorDrawerLayout:z=`docked-right`,autoFocus:B=!0,onPeekEntity:V,onClosePeek:H})=>{let U=(0,K.useRef)(null),te=(0,K.useRef)(null),W=(0,K.useRef)(null),ne=(0,K.useRef)(0),re=i2(),ie=(0,K.useRef)(re);ie.current=re;let[ae,oe]=(0,K.useState)(null),se=(0,K.useRef)(null),ce=(0,K.useRef)(``),le=(0,K.useRef)([]),ue=p===`dark`||p===`vs-dark`,{isDebugMode:de}=Ew(),fe=wme(se,x),[pe,me]=(0,K.useState)(null),[he,ge]=(0,K.useState)([]),[_e,ve]=(0,K.useState)(1),[ye,be]=(0,K.useState)(0),xe=F??pe,Se=zme(he,xe),[Ce,we]=(0,K.useState)(null),[Te,Ee]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches),[G,De]=(0,K.useState)(!1),[Oe,ke]=(0,K.useState)(!1),[Ae,je]=(0,K.useState)(R),[Me,Ne]=(0,K.useState)(!1),[Pe,Fe]=(0,K.useState)(`token`),[Ie,Le]=(0,K.useState)(null),[Re,ze]=(0,K.useState)(null),[Be,Ve]=(0,K.useState)(null),[He,Ue]=(0,K.useState)({tags:[],defaultEquipment:[],customMetricTypes:[]}),We=Ce?.state.doc.toString()??c,Ge=(0,K.useRef)(void 0);(0,K.useEffect)(()=>{if(m)return;let t=!1,n=Ge.current!==e;Ge.current=e;let r=()=>{Z2(e,We).then(e=>{t||Ue(t=>JSON.stringify(t)===JSON.stringify(e)?t:e)})};if(n)return r(),()=>{t=!0};let i=setTimeout(r,300);return()=>{t=!0,clearTimeout(i)}},[e,We,m]);let Ke=(0,K.useMemo)(()=>{let e=Ce??W.current;return e?l4(e.state):{contextKind:`markdown`,section:null,focus:null,lineNum:1,lineFrom:0,lineTo:0,lineText:``,tokens:[],lintFixes:[]}},[Ce,ye]),qe=(0,K.useMemo)(()=>{if(Ke.tokens.length===0)return null;if(Ie){let e=Ke.tokens.find(e=>e.id===Ie);if(e)return e}let e=(Ce??W.current)?.state.selection.main.head??0;return Ke.tokens.find(t=>e>=t.from&&e<=t.to)??Ke.tokens[0]??null},[Ke,Ie,Ce]),Je=(0,K.useRef)(m);Je.current=m;let Ye=(0,K.useRef)(e);Ye.current=e;let Xe=(0,K.useRef)(k);Xe.current=k;let Ze=(0,K.useRef)(ue);Ze.current=ue;let Qe=(0,K.useRef)(!1),$e=(0,K.useRef)({onChange:l,onCursorPositionChange:d,onBlur:f,onDocUpdate:u,onBlocksChange:y,onIdentityChange:r,onSaveRequest:o,onCommitChange:s});$e.current={onChange:l,onCursorPositionChange:d,onBlur:f,onDocUpdate:u,onBlocksChange:y,onIdentityChange:r,onSaveRequest:o,onCommitChange:s};let et=(0,K.useRef)(G);et.current=G;let tt=(0,K.useRef)(He);tt.current=He;let nt=(0,K.useRef)(Ae);nt.current=Ae;let rt=(0,K.useRef)(Me);rt.current=Me;let it=(0,K.useRef)(Pe);it.current=Pe;let at=(0,K.useRef)(Ie);at.current=Ie;let ot=(0,K.useRef)(Ke);ot.current=Ke;let st=(0,K.useMemo)(()=>xme({getNotebookScope:()=>tt.current,onCreateEffort:async e=>{await h2(e),W.current?.dispatch({effects:[S2.of(null)]}),be(e=>e+1)},onCreateTag:async e=>{await v2(e),W.current?.dispatch({effects:[S2.of(null)]});let t=W.current?.state.doc.toString()??``;Z2(Ye.current,t).then(e=>Ue(e)),be(e=>e+1)}}),[]),ct=(0,K.useCallback)(e=>{let t=W.current;if(!t||Je.current)return;_a(t);let n=l4(t.state),r=t.state.selection.main.head,i=e?.token??null;!i&&typeof e?.tokenIndex==`number`&&(i=n.tokens[e.tokenIndex]??null),i||=n.tokens.find(e=>r>=e.from&&r<=e.to)??n.tokens[0]??null;let a=e?.mode??(i?`token`:n.contextKind===`workout`?`add`:n.contextKind),o=e?.anchorRect??null;if(!o&&n.contextKind===`query`&&n.section){let e=n.section;try{let n=t.domAtPos(e.from),r=n.node instanceof Element?n.node:n.node.parentElement,i=r?.closest(`.cm-query-block-preview, .cm-widget-block-preview`)??r?.querySelector(`.cm-query-block-preview, .cm-widget-block-preview`)??null;if(i){let e=i.getBoundingClientRect();e.width>0&&e.height>0&&(o=e)}if(!o){let n=t.dom.querySelectorAll(`.cm-query-block-preview, .cm-widget-block-preview`);for(let r of n)try{let n=t.posAtDOM(r);if(n>=e.from&&n<=e.to){let e=r.getBoundingClientRect();if(e.width>0&&e.height>0){o=e;break}}}catch{}}}catch{}}if(!o)try{let e=t.coordsAtPos(i?.from??r);e&&(e.right>e.left||e.bottom>e.top)&&(o={left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:Math.max(24,e.right-e.left),height:Math.max(20,e.bottom-e.top),x:e.left,y:e.top,toJSON:()=>({})})}catch{o=null}Fe(a),Le(i?.id??null),ze(o),Ne(!nt.current)},[]),lt=(0,K.useRef)(ct);lt.current=ct;let ut=(0,K.useRef)(()=>({drawerOpen:nt.current,popoverOpen:rt.current,mode:it.current,contextKind:ot.current.contextKind,lineNum:ot.current.lineNum,selectedTokenId:at.current,tokens:ot.current.tokens.map(e=>({id:e.id,kind:e.kind,raw:e.raw,from:e.from,to:e.to})),lintFixes:ot.current.lintFixes.map(e=>({id:e.id,raw:e.raw,fixes:e.fixes}))}));(0,K.useEffect)(()=>{if(m||Te)return;let e=e=>{if(e.defaultPrevented)return;let t=U.current,n=document.activeElement;if(!t||!n||!t.contains(n))return;let r=(e.ctrlKey||e.metaKey)&&e.altKey&&!e.shiftKey&&(e.key.toLowerCase()===`i`||e.code===`KeyI`),i=e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&(e.key===`.`||e.code===`Period`);r?(e.preventDefault(),e.stopPropagation(),Dt.current()):i&&(e.preventDefault(),e.stopPropagation(),lt.current())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[m,Te]);let dt=yge(),ft=dt?.dispatch,pt=!!dt?.navState?.rightDrawerOpen,mt=dt?.peekTarget??null,ht=V??dt?.openPeek,gt=H??dt?.closePeek,_t=(0,K.useRef)(!1),vt=(0,K.useRef)(null),yt=(0,K.useRef)(mt);yt.current=mt;let bt=(0,K.useRef)({onPeekEntity:ht,onClosePeek:gt});bt.current={onPeekEntity:ht,onClosePeek:gt};let xt=(0,K.useCallback)(e=>{nt.current&&(_t.current=!0),je(!1),Ne(!1),yt.current=e,vt.current=e,bt.current.onPeekEntity?.(e)},[]),St=(0,K.useCallback)(()=>{yt.current=null,vt.current=null,bt.current.onClosePeek?.()},[]),Ct=(0,K.useCallback)(()=>{W.current&&_a(W.current),Ne(!1),St(),je(!0)},[St]),wt=(0,K.useCallback)(()=>{let e=!nt.current;e&&(W.current&&_a(W.current),Ne(!1),St()),je(e)},[St]),Tt=(0,K.useRef)(xt);Tt.current=xt;let Et=(0,K.useRef)(St);Et.current=St;let Dt=(0,K.useRef)(wt);Dt.current=wt;let Ot=!m&&!Te&&Ae,kt=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(ft&&Ot!==kt.current){if(kt.current=Ot,!Ot&&(_t.current||yt.current!==null)){_t.current=!1;return}_t.current=!1,ft({type:`SET_INSPECTOR_DRAWER`,open:Ot})}},[ft,Ot]),(0,K.useEffect)(()=>{mt&&(nt.current&&(_t.current=!0),je(!1),Ne(!1))},[mt]),(0,K.useEffect)(()=>()=>{kt.current&&(kt.current=!1,!_t.current&&yt.current===null&&ft?.({type:`SET_INSPECTOR_DRAWER`,open:!1}))},[ft]),(0,K.useEffect)(()=>{pt&&je(!1)},[pt]),(0,K.useEffect)(()=>K$(()=>{let e=W.current;e&&e.dispatch({effects:[S2.of(null),UM.of(null)]}),be(e=>e+1)}),[]),(0,K.useEffect)(()=>{let e=requestAnimationFrame(()=>{W.current?.requestMeasure(),be(e=>e+1)});return()=>cancelAnimationFrame(e)},[Ae]),(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: 1023px)`),t=e=>{Ee(e.matches),e.matches?(Ne(!1),je(!1)):(De(!1),ke(!1))};return Ee(e.matches),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[At,jt]=(0,K.useState)(null),[Mt,Nt]=(0,K.useState)(null),[Pt,Ft]=(0,K.useState)(!1),It=(0,K.useRef)(null),Lt=(0,K.useRef)(!1),Rt=(0,K.useRef)(n??0);(0,K.useEffect)(()=>{Rt.current=n??0},[n]);let[zt,Bt]=(0,K.useState)(null),Vt=(0,K.useRef)(null),Ht=(0,K.useCallback)(async(t,n=!1)=>{let r=W.current;if(!(!r||Lt.current)){Lt.current=!0,Bt(null);try{let o=await a?.();typeof o==`number`&&(Rt.current=o);let s=r.state.field(cM),c=await Yz({noteId:e??Br(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:Rt.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,Br(),e?void 0:`playground`,fe,{deferPersist:!0});It.current=c,Vt.current=null,Rt.current=c.note.sourceRevision,r.dispatch({effects:nM.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),Ft(n),jt(c.block),Nt(c.session.id)}catch(e){Bt(e instanceof Error?e.message:String(e))}finally{Lt.current=!1}}},[e,fe,i,a]),Ut=(0,K.useCallback)(()=>{jt(null),Nt(null),Ft(!1)},[]),Wt=(0,K.useCallback)(e=>{M&&Ht(e,!0)},[M,Ht]);(0,K.useEffect)(()=>_X({noteId:e,readonly:!!m,sourceRevision:n,getValue:()=>W.current?.state.doc.toString()??c,getView:()=>W.current,getBlocks:()=>{let e=W.current;return e?e.state.field(cM).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>F4(t,e.state)).filter(e=>e!==null):[]},applyEdit:async(e,t=!1)=>{if(m)throw Error(`Editor is in read-only mode. Clone this Note before editing.`);let n=W.current;if(!n){l(e),t&&await(o??s)?.();return}let r=n.state.doc.length;n.dispatch({changes:{from:0,to:r,insert:e}}),l(e),t&&await(o??s)?.()},undoEdit:()=>{let e=W.current;if(!e||m)return!1;let t=Ua(e);return t&&l(e.state.doc.toString()),t},startLiveWorkout:async(e,t=!0)=>{let n=W.current;if(!n)return{started:!1,error:`Editor view is not mounted.`};let r=n.state.field(cM).sections.filter(e=>e.type===`time`||e.type===`log`).map(e=>F4(e,n.state)).filter(e=>e!==null),i=e?r.find(t=>t.id===e):r[0];return i?(await Ht(i,t),{started:!0,blockId:i.id}):{started:!1,error:e?`Workout block '${e}' not found in editor.`:"No runnable ```time workout block found in editor."}},getInspectorState:()=>ut.current(),setInspectorDrawer:e=>{e&&(Ne(!1),Et.current()),je(e)},openTokenInspector:e=>{lt.current({mode:e?.mode,tokenIndex:e?.tokenIndex})},closeTokenInspector:()=>{Ne(!1)},...ht?{peekEntity:e=>Tt.current(e),closePeek:()=>Et.current()}:{}}),[e,m,n,c,l,o,s,Ht,ht]),(0,K.useEffect)(()=>{if(ht)return GX({getTarget:()=>yt.current??vt.current,openPeek:e=>Tt.current(e),closePeek:()=>Et.current()})},[ht]);let Gt=(0,K.useRef)(null),Kt=(0,K.useCallback)((e,t)=>{let n=Gt.current,r=n!==null&&n.results===t,i=It.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(Vt.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&W.current){let t=W.current,n=YN(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[mo.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(Gt.current={results:t,resultId:a,runBlock:o});let s;try{s=gR(fe).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>v?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{Gt.current?.results===t&&(Gt.current=null),Vt.current=a},()=>{}),s},[l,v,fe]),qt=(0,K.useMemo)(()=>{if(j)return[];if(A&&A.length>0)return A;let e=[];return M?e.push({id:`run`,label:`Run`,icon:(0,q.jsx)(Er,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:Ht}):_&&e.push({id:`run`,label:`Run`,icon:(0,q.jsx)(Er,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:_}),e.push({id:`playground`,label:`Playground`,icon:(0,q.jsx)(wi,{className:`h-3 w-3`}),splitIcon:(0,q.jsx)(Gi,{className:`h-3 w-3`}),splitSuccessIcon:(0,q.jsx)(zr,{className:`h-3 w-3`}),onClick:e=>{_ge(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await vge(e.content);await navigator.clipboard.writeText(t)}}),b&&e.push({id:`plan`,label:`Plan`,icon:(0,q.jsx)(ti,{className:`h-3 w-3`}),onClick:b}),e},[A,_,b,M,j,Ht]),Jt=(0,K.useMemo)(()=>ho({codeLanguages:kle}),[]),Yt=(0,K.useMemo)(()=>{let e=Math.max(1,n),r=P?[...P.keys()]:Ns;if(t&&Object.keys(t).length>0)try{return Hs(c,t,e,{registeredWidgets:r}),t}catch{return Vs(c,{sourceRevision:e,blocks:t,registeredWidgets:r})}return Vs(c,{sourceRevision:e,registeredWidgets:r})},[c,t,n,P]),Xt=(0,K.useMemo)(()=>[...T?[Ha(),Gee()]:[],Bee(),so(),Ra(),ka(),...w?[mo.lineWrapping]:[],qa.allowMultipleSelections.of(!0),ma(),qee(),Ja(),Wee(),Rse,yse,no.of([...Ma,...to,...fo,...lo,...$a,...ga,...Uee,vo,{key:`Mod-s`,run:()=>($e.current.onSaveRequest?.(),!0)},{key:`Alt-.`,run:()=>!Je.current&&(lt.current(),!0)},{key:`Mod-Alt-i`,run:()=>!Je.current&&(Dt.current(),!0)}]),mle,cM,eM.of({blocks:Yt,sourceRevision:Math.max(1,n),rawContent:c}),tM.of(P?[...P.keys()]:Ns),cse,WM.of(D),GM.of(de),...E||!D?[mce]:[],...E?[ese,Gse,Yse,Tme(e),fme(),vme(),Uce,Rce(),$ce]:[],...O?[dse]:[],go({parent:document.body}),Vse,tj,Dse,Ese,DM.of(xge),DM.of(bge),OM.of(st),...k?[hle]:[],NM,Yj.of(null),Zj.of(e=>{if(/^(https?:|mailto:|tel:)/i.test(e)){window.open(e,`_blank`,`noopener,noreferrer`);return}if(bt.current.onPeekEntity){let t=R4(e);if(t){Tt.current(t);return}}if(e.startsWith(`/`)&&typeof window<`u`){window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`));return}typeof window<`u`&&window.location.assign(e)}),ise,Mme,...nle,tse,...P&&P.size>0?[Ole(P)]:[],vse({executor:sJ,onResultSaved:mR,readOnly:m,onCaptureRpe:m?void 0:async(e,t)=>{await gB(e,t)},onEditMetric:m?void 0:async(e,t)=>{if(await mB({resultId:e,occurrence:t.occurrence,metric:{type:t.metric.type,value:t.metric.value,image:t.metric.image}})===`not-found`)throw Error(`Result segment not found in storage.`)},onOpenResults:e=>{let t=AH(e.resultId);ie.current?ie.current(t):typeof window<`u`&&window.location.assign(t)},onAddToDashboard:e=>{oe(e)},noteHref:e=>TG(`blockContentId`in e||`dataType`in e?oG(e):eG(e))}),Eme(e,fe),mo.domEventHandlers({click:(e,t)=>{if(e.button!==0||!bt.current.onPeekEntity)return!1;let n=e.target instanceof Element?e.target:null;if(!n)return!1;let r=n.closest(`.cm-frontmatter-preview a[href]`);if(r){let t=r.getAttribute(`href`);if(t){let n=R4(t);if(n)return e.preventDefault(),e.stopPropagation(),Tt.current(n),!0}}let i=e.ctrlKey||e.metaKey;if(!Je.current&&!i)return!1;let a=t.posAtCoords({x:e.clientX,y:e.clientY});if(a===null)try{let e=t.posAtDOM(n);Number.isFinite(e)&&(a=e)}catch{a=null}if(a===null)return!1;let o=Sge(t.state,a);return o?(e.preventDefault(),e.stopPropagation(),Tt.current(o),!0):!1},focus:(e,t)=>{if(typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches&&!m){let e=uM(t.state),n=e?.type===`time`||e?.type===`log`||e?.type===`query`;t.contentDOM.setAttribute(`inputmode`,n?`none`:`text`),De(!0),ke(!n)}return!1},blur:(e,t)=>{let n=e.relatedTarget;(!n||!n.closest(`.cm-tooltip`))&&_a(t);let r=!!(n&&te.current?.contains(n)),i=!!(n?.closest(`[data-mobile-editor-deck="true"]`)||!n&&Date.now()<ne.current);return!r&&!i&&(De(!1),ke(!1)),$e.current.onBlur?.(),!1}}),mo.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(cM);$e.current.onIdentityChange?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision});let n=e.transactions.every(e=>e.annotation(j4)===!0);n||(le.current.push(t.rawContent),$e.current.onChange(t.rawContent)),$e.current.onDocUpdate?.(e),I4(e.state,$e.current.onBlocksChange,ce),n||e.transactions.some(e=>e.isUserEvent(`input`)&&!e.isUserEvent(`input.wheel`)&&!e.isUserEvent(`input.format`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||Promise.resolve($e.current.onCommitChange?.()).catch(()=>{})}let t=Da(e.startState),n=Da(e.state),r=t!==n||ro(e.startState)!==ro(e.state);if(t!==`active`&&n===`active`&&Ne(!1),!e.selectionSet&&!e.docChanged&&r&&be(e=>e+1),e.selectionSet||e.docChanged){if(be(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Da(e.startState)!==null&&Da(e.state)===null&&P4(e.state,e.state.selection.main.head)?.value===``)queueMicrotask(()=>{e.view.state===e.state&&va(e.view)});else if(e.docChanged&&e.transactions.some(e=>e.isUserEvent(`input.type`))&&Da(e.state)===null){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),r=n.text.slice(0,t-n.from),i=uM(e.state),a=i?.type===`time`||i?.type===`log`,o=/(\[\[|\[:)$/.test(r),s=/(?:^|\s)#$/.test(r)&&(a||!/^\s*#$/.test(r));(o||s)&&queueMicrotask(()=>{e.view.state===e.state&&va(e.view)})}let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);$e.current.onCursorPositionChange?.(n.number,t-n.from+1);let r=uM(e.state);if(me(r?.id??null),ve(n.number),Xe.current){let{sections:t}=e.state.field(cM);ge(t)}if(e.selectionSet&&Zt.current&&!Je.current&&e.transactions.some(e=>e.isUserEvent(`select.pointer`))){let t=uM(e.startState),n=t?.type===`time`||t?.type===`log`||t?.type===`query`,i=r?.type===`time`||r?.type===`log`||r?.type===`query`;n!==i&&(e.view.contentDOM.setAttribute(`inputmode`,i?`none`:`text`),ke(!i))}}}),qa.readOnly.of(m),mo.editable.of(!m),...L?[uo(L)]:[],mo.contentAttributes.of({"aria-label":g})],[m,T,w,E,D,de,O,k,e,fe,P,L,g]);(0,K.useEffect)(()=>{let e=te.current;if(!e)return;let t;try{t=qa.create({doc:c,extensions:[...Xt,E4.of(Gj(Ze.current)),D4.of(Jt),O4.of([]),k4.of([mo.contentAttributes.of({inputmode:Te&&!Oe?`none`:`text`}),jM.of(Te&&G&&Oe&&!m)]),...N??[]]})}catch(e){console.error(`NoteEditor: Failed to initialize EditorState, recovering with safe fallback`,e),t=qa.create({doc:c,extensions:[E4.of(Gj(ue)),D4.of(Jt)]})}let n=new mo({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{if(et.current)return;let e=!i||i.scale<=1.05,t=!i||i.height<window.innerHeight;n.hasFocus&&e&&t&&(Zt.current?T4(n,{forceCenter:!0}):n.dispatch({effects:mo.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})}))})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),W.current=n,we(n),e.__codemirrorView=n,S?.(n);let{sections:s}=n.state.field(cM);ge(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;ve(l);let u=uM(n.state);me(u?.id??null);let d=n.state.field(cM);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),I4(n.state,y,ce),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,Qe.current=!1,we(null),n.destroy()}},[]),(0,K.useEffect)(()=>{let e=W.current;if(!e)return;let r=e.state.field(cM),i=le.current;if(c===r.rawContent){i.length=0,t&&n!==r.sourceRevision&&e.dispatch({effects:nM.of({blocks:t,sourceRevision:Math.max(1,n)})});return}let a=i.indexOf(c);if(a!==-1){i.splice(0,a+1);return}i.length=0;let o=Math.max(1,n),s=t?Vs(c,{sourceRevision:o,blocks:t,registeredWidgets:P?[...P.keys()]:Ns}):void 0,l=s&&t&&Object.keys(s).length===Object.keys(t).length&&Object.entries(t).every(([e,t])=>{let n=s[e];return n&&n.from===t.from&&n.to===t.to&&n.kind===t.kind&&n.dialect===t.dialect&&n.sport===t.sport});e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},annotations:j4.of(!0),...l?{effects:rM.of({rawContent:c,blocks:t,sourceRevision:o})}:{}})},[c,t,n]),(0,K.useEffect)(()=>{W.current&&W.current.dispatch({effects:E4.reconfigure(Gj(ue))})},[ue]);let Zt=(0,K.useRef)(Te);Zt.current=Te;let Qt=(0,K.useRef)(Oe);Qt.current=Oe,(0,K.useEffect)(()=>{if(!Te||!G||m||typeof document>`u`)return;let e=e=>{let t=e.target;t&&(te.current?.contains(t)||t.closest(`[data-mobile-editor-deck="true"], .cm-tooltip`)||(De(!1),ke(!1)))};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[Te,G,m]),(0,K.useEffect)(()=>{if(!W.current)return;if(!Qe.current){Qe.current=!0;return}let e=[];W.current.dispatch({effects:[eo.reconfigure.of([...Xt,E4.of(Gj(Ze.current)),D4.of(Jt),O4.of(e),k4.of([mo.contentAttributes.of({inputmode:Zt.current&&!Qt.current?`none`:`text`}),jM.of(Zt.current&&et.current&&Qt.current&&!Je.current)]),...N??[]])]})},[Xt,N,C,Jt]),(0,K.useEffect)(()=>{W.current&&W.current.dispatch({effects:k4.reconfigure([mo.contentAttributes.of({inputmode:Te&&!Oe?`none`:`text`}),jM.of(Te&&G&&Oe&&!m)])})},[Te,G,Oe,m]),(0,K.useEffect)(()=>{if(!B)return;let e=typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches;!m&&!e&&W.current?.focus()},[m,B]),(0,K.useEffect)(()=>{if(I&&W.current){let e=W.current,t=e.state.doc.toString().split(`
|
|
868
|
+
`),a=r.trim()?`${r.trimEnd()}\n${i}\n`:`${i}\n`;return e.dispatch({changes:{from:t.contentFrom,to:t.contentTo,insert:a},selection:{anchor:t.contentFrom},userEvent:`input.wheel`}),!0}function Uhe(e,t){let n=e.state.selection.main,r=`[[${t.trim()}]]`,i=n.from>0?e.state.doc.sliceString(n.from-1,n.from):``,a=`${i&&!/[\s([]/.test(i)?` `:``}${r}`;return e.dispatch({changes:{from:n.from,to:n.to,insert:a},selection:{anchor:n.from+a.length},userEvent:`input.format`}),!0}function p4(e,t){let n=e.state.selection.main,r=t.startsWith(`#`)?t:`#${t}`,i=n.from>0?e.state.doc.sliceString(n.from-1,n.from):``,a=`${i&&!/\s/.test(i)?` `:``}${r} `;return e.dispatch({changes:{from:n.from,to:n.to,insert:a},selection:{anchor:n.from+a.length},userEvent:`input.format`}),!0}function m4(e,t){let n=SP(),r=n.isInitialized()?n.list():[],i=e.trim().toLowerCase(),a=r.map(e=>{let n=!!(t?.defaultEffort&&e.slug===t.defaultEffort)||!!t?.defaultEquipment?.some(t=>e.equipment?.includes(t));return{slug:e.slug,label:e.label,aliases:e.aliases??[],discipline:e.baseAttributes?.discipline,scoped:n}}).filter(e=>!i||e.label.toLowerCase().includes(i)||e.slug.toLowerCase().includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i)));return a.sort((e,t)=>{if(i){let n=+!!e.label.toLowerCase().startsWith(i),r=+!!t.label.toLowerCase().startsWith(i);if(r!==n)return r-n}return e.scoped===t.scoped?e.label.localeCompare(t.label):Number(t.scoped)-Number(e.scoped)}),a.length>0?a.slice(0,40):[{slug:`kettlebell-swing`,label:`Kettlebell Swing`,aliases:[`swing`,`kb swing`,`kbs`],scoped:!0},{slug:`back-squat`,label:`Back Squat`,aliases:[`bs`,`squat`],scoped:!1},{slug:`pull-up`,label:`Pull-up`,aliases:[`pullup`,`kipping pullup`],scoped:!1},{slug:`push-up`,label:`Push-up`,aliases:[`pushup`],scoped:!1},{slug:`air-squat`,label:`Air Squat`,aliases:[`squat`],scoped:!1},{slug:`thruster`,label:`Thruster`,aliases:[`thrusters`],scoped:!1},{slug:`burpee`,label:`Burpee`,aliases:[`burpees`],scoped:!1},{slug:`run`,label:`Run`,aliases:[`running`],scoped:!1},{slug:`row`,label:`Row`,aliases:[`rowing`,`erg`],scoped:!1},{slug:`plank`,label:`Plank`,aliases:[`plank hold`],scoped:!1}].filter(e=>!i||e.label.toLowerCase().includes(i)||e.slug.includes(i)||e.aliases.some(e=>e.includes(i)))}function Whe(e){let t=uz(),n=t.isInitialized()?t.list():[],r=e.trim().toLowerCase(),i=n.filter(e=>!r||e.label.toLowerCase().includes(r)||e.slug.toLowerCase().includes(r)).slice(0,30).map(e=>({slug:e.slug,label:e.label}));return i.length>0?i:[{slug:`kettlebell`,label:`Kettlebell`},{slug:`barbell`,label:`Barbell`},{slug:`dumbbell`,label:`Dumbbell`},{slug:`pull-up-bar`,label:`Pull-up Bar`},{slug:`rower`,label:`Rower`}].filter(e=>!r||e.label.toLowerCase().includes(r))}function h4(e){let t=Sz().list().filter(e=>!e.isCategory),n=e.trim().replace(/^#/,``).toLowerCase(),r=e=>e?e.kind===`metric`?e.type:e.kind===`function`?e.name:e.slug:`Tag`,i=t.map(e=>({slug:e.slug,category:r(e.contributions[0])})).filter(e=>!n||e.slug.toLowerCase().includes(n)||e.category.toLowerCase().includes(n)).slice(0,40);return i.length>0?i:[{slug:`emom`,category:`Format`},{slug:`amrap`,category:`Format`},{slug:`tabata`,category:`Format`},{slug:`for-time`,category:`Format`},{slug:`strength`,category:`Focus`},{slug:`heavy`,category:`Load`}].filter(e=>!n||e.slug.includes(n))}async function Ghe(e){let t=await X.getAllNotes().catch(()=>[]),n=e.trim().toLowerCase(),r=new Set,i=[];for(let e of t){let t=e.title?.trim();if(!(!t||r.has(t.toLowerCase()))&&!(n&&!t.toLowerCase().includes(n)&&!e.tags?.some(e=>e.toLowerCase().includes(n)))&&(r.add(t.toLowerCase()),i.push({noteId:e.id,title:t,summary:e.tags?.slice(0,3).map(e=>`#${e}`).join(` `)||`Note`}),i.length>=25))break}return i}var g4=({label:e,ariaLabel:t,options:n,selectedValue:r,onSelect:i,compact:a=!1,testId:o=Q.EDITOR_INSPECTOR_SCRUBBER,optionTestIdPrefix:s})=>{let c=(0,K.useRef)(null),l=(0,K.useRef)(0),u=(0,K.useRef)(n),d=(0,K.useRef)(r),f=(0,K.useRef)(i);return u.current=n,d.current=r,f.current=i,(0,K.useEffect)(()=>{let e=c.current;if(!e)return;let t=e.querySelector(`[aria-selected="true"]`);if(!t)return;let n=Math.max(0,t.offsetTop-(e.clientHeight-t.offsetHeight)/2);l.current=Date.now()+180,e.scrollTop=n},[r,n.length]),(0,K.useEffect)(()=>{let e=c.current;if(!e)return;let t=e=>{if(!e||Date.now()<l.current||e===d.current)return;let t=u.current.find(t=>t.value===e);t&&f.current(t)};if(typeof HTMLElement<`u`&&`onscrollsnapchange`in HTMLElement.prototype){let n=e=>{let n=e.snapTargetBlock;t(n?.dataset?.optionValue)};return e.addEventListener(`scrollsnapchange`,n),()=>e.removeEventListener(`scrollsnapchange`,n)}let n=null,r=()=>{if(e.clientHeight<=0)return;let t=e.scrollTop+e.clientHeight/2,n,r=1/0;return e.querySelectorAll(`[data-option-value]`).forEach(e=>{let i=e.offsetTop+e.offsetHeight/2,a=Math.abs(i-t);a<r&&(r=a,n=e.dataset.optionValue)}),n},i=()=>{Date.now()<l.current||(n&&clearTimeout(n),n=setTimeout(()=>{t(r())},140))};return e.addEventListener(`scroll`,i,{passive:!0}),()=>{n&&clearTimeout(n),e.removeEventListener(`scroll`,i)}},[]),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,"data-testid":o,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground px-0.5 truncate`,children:e}),(0,q.jsxs)(`div`,{className:$(`relative rounded-md border border-border bg-popover overflow-hidden`,a?`h-[144px]`:`h-[172px]`),style:{containerType:`size`},children:[(0,q.jsx)(`div`,{"aria-hidden":`true`,className:`pointer-events-none absolute inset-x-1.5 top-1/2 -translate-y-1/2 h-11 rounded-[6px] bg-primary/10 border border-primary/40 z-[1]`}),(0,q.jsx)(`div`,{ref:c,role:`listbox`,tabIndex:0,"aria-label":t??e,onKeyDown:e=>{if(e.key!==`ArrowUp`&&e.key!==`ArrowDown`||n.length===0)return;e.preventDefault();let t=n.findIndex(e=>e.value===r),a=t>=0?t:0,o=n[Math.max(0,Math.min(n.length-1,a+(e.key===`ArrowDown`?1:-1)))];o&&o.value!==r&&i(o)},className:`relative z-[2] h-full overflow-y-auto snap-y snap-mandatory overscroll-contain flex flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50`,style:{paddingBlock:`calc(50cqh - 22px)`},children:n.map(e=>{let t=e.value===r;return(0,q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,"data-option-value":e.value,"data-testid":s?`${s}-${e.id}`:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>i(e),className:$(`shrink-0 h-11 snap-center w-full px-3 flex items-center justify-center gap-1.5 font-mono tabular-nums text-sm transition-colors cursor-pointer`,t?`font-bold text-primary`:`font-medium text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(`span`,{className:`truncate`,children:e.label}),e.sublabel&&(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.sublabel})]},e.id)})})]})]})},_4=`inline-flex items-center justify-center rounded-full border text-xs font-medium transition-colors cursor-pointer whitespace-nowrap tabular-nums`,Khe=[{label:`Total Reps`,val:`:sum{metric:reps} by {week} last 4w | :bar{}`},{label:`Total Volume`,val:`:sum{metric:volume} by {week} last 12w | :timeseries{}`},{label:`Weekly TIS`,val:`:sum{metric:tis} by {week} last 8w | :timeseries{}`},{label:`Find Sessions`,val:`:session{} last 4w`},{label:`Find Notes`,val:`:note{tags:benchmark} last 8w`}],qhe=[{label:`Bar Chart`,suffix:`| :bar{}`},{label:`Timeseries`,suffix:`| :timeseries{}`},{label:`Table`,suffix:`| :table{}`},{label:`No Chart`,suffix:``}];function Jhe(e,t){let n=e.replace(/\s*\|\s*:(?:bar|timeseries|table|pie)\{[^}]*\}\s*$/i,``).trim()||`:sum{metric:reps} by {week} last 4w`;return t?`${n} ${t}`:n}var Yhe=/^\s*(?:view|limit|title|chart|span|unit|range|groupBy|columns|sort)\s*:/m,Xhe=e=>Fg(e)?sJ.runFind(e):sJ.runQuery(e.raw),v4=({view:e,mode:t,inspection:n,token:r,scope:i,useScrubber:o=!1,onToggleScrubber:s,compact:c=!1,showHeader:l=!0,showFooter:u=!0,showStepButtons:d=!1,showClose:f=!1,showDockButton:p=!1,onDockDrawer:m,onMutate:h,onModeChange:g,onStepToken:_,onClose:v,activeQueryStageId:y,queryStageRequestToken:b})=>{let[x,S]=(0,K.useState)(``),[C,w]=(0,K.useState)(!1),[T,E]=(0,K.useState)([]),[D,O]=(0,K.useState)(!1),k=n.section?.type===`query`?n.section:null,A=!!(e&&k&&k.contentFrom!==void 0&&k.contentTo!==void 0),M=A&&e&&k?e.state.doc.sliceString(k.contentFrom,k.contentTo):n.lineText,N=(0,K.useMemo)(()=>{let e=Ck(M),t=/^\s*query\s*:/m.test(M),n=Yhe.test(M),r;return r=t||e.length>0&&!n?e[0]?.query??``:n?``:M.trim(),{extracted:e,hasYamlQueryKey:t,hasOtherYamlConfig:n,currentQuery:r}},[M]),[P,F]=(0,K.useState)(()=>!N.currentQuery.trim()),I=(0,K.useRef)(N.currentQuery);I.current=N.currentQuery,(0,K.useEffect)(()=>{S(``),w(!1)},[r?.id,t]),(0,K.useEffect)(()=>{t===`query`&&F(!I.current.trim())},[t,k?.id]),(0,K.useEffect)(()=>{t===`query`&&y===`wql-metric`&&b&&F(!0)},[t,y,b]);let L=(0,K.useMemo)(()=>{if(!(t!==`query`||!b||b<=0)){if(y===`wql-metric`){let e=I.current.trim();return{type:/^:(?:session|note|block|effort|notebook|tag|equipment)\b/i.test(e)?`target`:`metric`,token:b}}if(y===`wql-scope`)return{type:`notebook`,token:b};if(y===`wql-window`)return{type:`time`,token:b}}},[t,y,b]);(0,K.useEffect)(()=>{if(t!==`wiki`)return;let e=!1;return Ghe(x).then(t=>{e||E(t)}),()=>{e=!0}},[t,x]);let R=c?`min-h-[44px] px-3.5 py-2`:`min-h-[32px] px-2.5 py-1`,B=c?`min-h-[44px] px-3 py-2`:`min-h-[36px] px-2.5 py-1.5`,V=(t,n)=>{if(!e||!r)return;let i=r.raw,a=zhe(e,r,t);a.applied&&h?.({from:i,to:a.nextText},n??`Updated -> ${a.nextText}`)},H=()=>{if(!e||!r)return;let t=r.raw;d4(e,r)&&h?.({from:t,to:`removed`},`Removed ${t}`)},U=(t,r)=>{if(!e)return;let i=Bhe(e,n.lineNum,t);i&&(h?.({from:`+ add`,to:i.clean},r??`Added ${i.clean}`),g?.(`token`))},te=()=>{e&&e.dispatch({effects:[S2.of(null)]})},W=async(e,t)=>{if(!(!t.trim()||D)){O(!0);try{if(e===`tag`){let e=t.replace(/^#/,``).trim();await v2(e),te(),h?.({from:t,to:`#${e}`},`Created tag #${e}`)}else if(e===`effort`){let e=await h2(t);te(),h?.({from:t,to:e.label},`Defined effort "${e.label}"`)}else{let e=await _2(t);te(),h?.({from:t,to:e.label},`Defined equipment "${e.label}"`)}}finally{O(!1)}}},ne=async(t,i,a)=>{if(!D){O(!0);try{if(await g2(t,a),te(),e&&r&&y2(n.lineText).jsonFrom>=0){let r=b2(n.lineText,{effort:t});e.dispatch({changes:{from:n.lineFrom,to:n.lineTo,insert:r},userEvent:`input.wheel`})}w(!1),h?.({from:a,to:i},`Aliased "${a}" -> ${i}`)}finally{O(!1)}}},re=(0,K.useMemo)(()=>m4(x,i),[x,i]),ie=(0,K.useMemo)(()=>Whe(x),[x]),ae=(0,K.useMemo)(()=>h4(x),[x]),se=(0,K.useMemo)(()=>{let e=new Map;for(let t of ae){let n=e.get(t.category)??[];n.push(t),e.set(t.category,n)}return[...e.entries()]},[ae]),ce=(0,K.useMemo)(()=>e&&n.section?u4(e.state,n.section):[],[e,n]),le=`Edit Token`,ue=r?.raw??``,de=``;if(t===`block`&&n.section){let e=n.section.sport?`:${n.section.sport}`:``;le=`Timer Block Settings`,ue=`\`\`\`${n.section.type}${e}`,de="Switch fence dialect (`time` vs `log`) or insert a grammar-verified template."}else t===`wiki`?(le=`Insert [[Wiki Link]]`,ue=`Note Graph`,de=`Link directly to another Note in your workspace.`):t===`prose-tag`?(le=`Insert #Tag`,ue=`#taxonomy`,de=`Insert a canonical tag or create a new tag inline.`):t===`add`?(le=`Add Syntax Element`,ue=`+ Element`,de=`Append a structured token to the active workout line.`):t===`markdown`?(le=`Markdown & Blocks`,ue=`Line ${n.lineNum}`,de=`Insert workout fences, WQL queries, headings, or wiki links.`):t===`query`?(le=`WQL Query Stage`,ue="```query",de=`Build a WQL query clause without leaving the note.`):r&&(r.kind===`duration`?(le=`Timer & Duration`,de=`Change timer mode without losing duration or surrounding line text.`):r.kind===`rounds`?(le=`Rounds & Structure`,de=`Switch round count, set scheme, ladder, or interval keyword.`):r.kind===`rep`?(le=`Repetitions`,de=`Adjust target rep count with presets or steppers.`):r.kind===`resistance`?(le=`Resistance & Load`,de=`Toggle @ prefix, unit (kg/lb/pood/%), or target load.`):r.kind===`distance`?(le=`Distance & Calories`,de=`Pick standard distances or convert units.`):r.kind===`effort`||r.kind===`equipment`?(le=r.kind===`effort`?`Movement / Effort`:`Equipment`,de=`Search catalog & aliases — rewrites clean Whiteboard Script text.`):r.kind===`tag`?(le=`Tag (#tag)`,de=`Replace with a workspace tag or create a new tag inline.`):r.kind===`unresolved`?(le=r.isTag?`Unrecognized Tag`:`Unrecognized Term`,de=r.diagnostic?.message??`Define "${r.raw}" in your catalog or replace from suggestions.`):r.kind===`lintError`?(le=`Syntax Repair`,de=r.lintMessage??`Fix invalid Whiteboard Script syntax.`):r.kind===`action`&&(le=`Action Cue`,de=`Replace with a structured bracketed timer cue.`));let fe=(e,t)=>(0,q.jsxs)(`div`,{className:`relative flex items-center`,children:[(0,q.jsx)(Yr,{className:`h-3.5 w-3.5 text-muted-foreground absolute left-2.5 pointer-events-none`,"aria-hidden":`true`}),(0,q.jsx)(`input`,{type:`search`,value:x,onChange:e=>S(e.target.value),placeholder:e,"aria-label":t,className:$(`w-full pl-8 pr-2.5 rounded-md border border-field-border bg-background text-foreground placeholder:text-muted-foreground text-base lg:text-xs focus:outline-none focus:ring-2 focus:ring-ring`,c?`min-h-[44px]`:`h-8`)})]});return(0,q.jsxs)(`div`,{className:`flex flex-col min-h-0 min-w-0`,children:[l&&(0,q.jsxs)(`div`,{className:`px-3 py-2.5 border-b border-border bg-popover/70 flex items-start justify-between gap-2 shrink-0`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,q.jsx)(`span`,{className:`text-[13px] font-bold text-foreground tracking-tight`,children:le}),ue&&(0,q.jsx)(`span`,{className:`font-mono text-[11.5px] font-semibold px-2 py-0.5 rounded bg-muted border border-border text-foreground max-w-[160px] truncate`,children:ue})]}),de&&(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5 leading-snug`,children:de})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Delete token`,"data-testid":Q.EDITOR_TOKEN_DELETE_BTN,onClick:H,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-transparent hover:border-destructive/30 hover:bg-destructive/10 text-destructive transition-colors cursor-pointer`,children:(0,q.jsx)(Me,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),d&&_&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`button`,{type:`button`,"aria-label":`Previous token`,"data-testid":Q.EDITOR_TOKEN_PREV_BTN,onClick:()=>_(-1),className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(j,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,q.jsx)(`button`,{type:`button`,"aria-label":`Next token`,"data-testid":Q.EDITOR_TOKEN_NEXT_BTN,onClick:()=>_(1),className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ee,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]}),p&&m&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Dock inspector drawer`,title:`Open Option B Right Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,onClick:m,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ia,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),f&&v&&(0,q.jsx)(`button`,{type:`button`,"aria-label":`Close inspector`,onClick:v,className:`inline-flex items-center justify-center min-h-[30px] min-w-[30px] rounded-md border border-border bg-card hover:bg-muted text-foreground transition-colors cursor-pointer`,children:(0,q.jsx)(ze,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]})]}),(0,q.jsx)(`div`,{className:$(`flex flex-col gap-3 min-h-0 min-w-0`,u?`p-3 overflow-y-auto max-h-[380px]`:c?`py-1`:`p-3`),children:(()=>{if(t===`block`&&n.section){let t=n.section;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Block Dialect`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`time`,`log`].map(n=>{let r=t.type===n;return(0,q.jsx)(`button`,{type:`button`,onClick:()=>{e&&(Vhe(e,t,{dialect:n}),h?.({from:t.type,to:n},`Switched block to \`\`\`${n}`))},className:$(_4,R,r?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:n===`time`?"TIMER (```time)":"LOG (```log)"},n)})})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Insert Starter Template`}),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-44 overflow-y-auto pr-0.5`,children:Mhe.map(n=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{e&&Hhe(e,t,n.lines)&&h?.({from:`block`,to:n.name},`Inserted ${n.name} template`)},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 transition-colors cursor-pointer`,B),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:n.name}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:n.desc})]}),(0,q.jsxs)(`span`,{className:`text-[11px] font-mono text-primary shrink-0 flex items-center gap-1`,children:[(0,q.jsx)(a,{className:`h-3 w-3`,"aria-hidden":`true`}),`Insert`]})]},n.id))})]}),ce.length>0&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Block Statements`}),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-36 overflow-y-auto`,children:ce.map(t=>{let r=t.lineNum===n.lineNum;return(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_TIMELINE_ROW,onClick:()=>{if(!e)return;let n=e.state.doc.line(t.lineNum);e.dispatch({selection:{anchor:n.from}}),e.focus()},className:$(`w-full rounded-md border px-2.5 py-1.5 min-h-[34px] flex items-center justify-between gap-2 text-left text-xs transition-colors cursor-pointer`,r?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsx)(`span`,{className:`truncate font-mono`,children:t.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono tabular-nums px-1.5 py-0.5 rounded bg-card border border-border shrink-0`,children:t.durationLabel})]},t.lineNum)})})]})]})}if(t===`wiki`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search workspace notes...`,`Search workspace notes`),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1 max-h-52 overflow-y-auto`,children:[T.map(t=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_WIKI_PICKER_ITEM,onClick:()=>{e&&Uhe(e,t.title)&&h?.(null,`Linked [[${t.title}]]`)},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:t.title}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:t.summary})]}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-primary shrink-0`,children:`[[Link]]`})]},t.noteId)),T.length===0&&(0,q.jsxs)(`p`,{className:`text-xs text-muted-foreground py-2`,children:[`No matching workspace notes found. Type `,(0,q.jsx)(`code`,{children:`[[Title]]`}),` directly to create a new link.`]})]})]});if(t===`prose-tag`){let t=x.trim().replace(/^#/,``),n=ae.some(e=>e.slug.toLowerCase()===t.toLowerCase());return(0,q.jsxs)(q.Fragment,{children:[fe(`Filter or create #tag...`,`Filter or create tag`),t&&!n&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,onClick:async()=>{await W(`tag`,t),e&&p4(e,t)},className:`inline-flex items-center gap-1.5 min-h-[36px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create & insert #`,t]}),(0,q.jsx)(`div`,{className:`flex flex-col gap-2 max-h-48 overflow-y-auto`,children:se.map(([t,n])=>(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wide text-muted-foreground`,children:t}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:n.map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{e&&p4(e,t.slug)&&h?.(null,`Inserted #${t.slug}`)},className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted font-mono`),children:[`#`,t.slug]},t.slug))})]},t))})]})}if(t===`markdown`)return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsx)(`div`,{className:`flex flex-col gap-1`,children:[{label:`Timer Block`,sub:"```time",insert:"\n```time\n10:00 EMOM\n 10 Air Squat\n```\n"},{label:`Log Block`,sub:"```log",insert:"\n```log\n5x5 Back Squat @100kg\n```\n"},{label:`Query Block`,sub:"```query",insert:"\n```query\n:sum{metric:reps} by {week} last 4w | :bar{}\n```\n"},{label:`Task Item`,sub:`- [ ]`,prefix:`- [ ] `},{label:`Heading 2`,sub:`## Title`,prefix:`## `}].map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{if(!e)return;let r=e.state.doc.line(n.lineNum);if(t.insert)e.dispatch({changes:{from:r.to,to:r.to,insert:t.insert},selection:{anchor:r.to+t.insert.length},userEvent:`input.wheel`}),h?.(null,`Inserted ${t.label}`);else if(t.prefix){let n=r.text.replace(/^(#{1,6}\s+|-\s+\[[ xX]\]\s+)/,``),i=`${t.prefix}${n}`;e.dispatch({changes:{from:r.from,to:r.to,insert:i},selection:{anchor:r.from+i.length},userEvent:`input.wheel`}),h?.(null,`Applied ${t.label}`)}},className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:t.label}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-muted-foreground`,children:t.sub})]},t.label))}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>g?.(`wiki`),className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted`),children:`[[Wiki Link]]`}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>g?.(`prose-tag`),className:$(_4,R,`bg-popover text-foreground border-border hover:bg-muted`),children:`#Tag`})]})]});if(t===`query`){let t=(t,r)=>{if(!(!e||t===N.currentQuery)){if(A&&k){let n;if(N.extracted.length>0&&(N.hasYamlQueryKey||!N.hasOtherYamlConfig))n=wk(M,t,0);else if(N.hasOtherYamlConfig){let e=M.trimEnd();n=e?`${e}\nquery: ${t}\n`:`query: ${t}\n`}else{let e=M.trimEnd();n=e?`${e}\n${t}\n`:t?`${t}\n`:``}e.dispatch({changes:{from:k.contentFrom,to:k.contentTo,insert:n},userEvent:`input.wheel`})}else{let r=e.state.doc.line(n.lineNum);e.dispatch({changes:{from:r.from,to:r.to,insert:t},userEvent:`input.wheel`})}h?.(r?{from:N.currentQuery||`empty`,to:t}:null,r??`Updated query`)}};return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2.5 min-w-0`,children:[(0,q.jsx)(vj,{surface:`sheet`,defaultExpanded:!0,query:N.currentQuery,onQueryChange:e=>t(e),execute:Xhe,showDiagnostics:!0,compact:c,segmentEditRequest:L}),y===`wql-chart`&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0 border-t border-border/60 pt-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Chart stage`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:qhe.map(e=>{let n=Jhe(N.currentQuery,e.suffix),r=e.suffix===``?!/\|\s*:(?:bar|timeseries|table|pie)\{/i.test(N.currentQuery):N.currentQuery.toLowerCase().includes(e.suffix.slice(2).trim().toLowerCase());return(0,q.jsx)(`button`,{type:`button`,onClick:()=>t(n,`Chart -> ${e.label}`),className:$(_4,R,r?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e.label},e.label)})})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0 border-t border-border/60 pt-2`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>F(e=>!e),"aria-expanded":P,className:$(`inline-flex items-center justify-between gap-2 text-xs font-semibold text-muted-foreground hover:text-foreground cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:[(0,q.jsx)(`span`,{children:`Quick-seed presets`}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono`,children:P?`Hide`:`Show`})]}),P&&(0,q.jsx)(`div`,{className:`grid grid-cols-2 gap-1.5 min-w-0`,children:Khe.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>t(e.val,`Applied ${e.label}`),className:$(`min-w-0 rounded-md border border-border bg-popover hover:bg-muted text-left flex flex-col gap-0.5 cursor-pointer px-2.5 py-1.5`,c?`min-h-[44px]`:`min-h-[36px]`),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground truncate`,children:e.val})]},e.label))})]})]})}if(t===`add`||!r){let e=i.preferredMassUnit??`kg`,t=i.preferredDistanceUnit??`m`,n=m4(``,i)[0]?.label??`Kettlebell Swing`,r=`#${h4(``)[0]?.slug??`emom`}`,a=[{id:`effort`,label:`Movement / Effort`,raw:n,testId:`wheel-option-add-effort`},{id:`weight`,label:`Weight / Load`,raw:`20${e}`,testId:`wheel-option-add-weight`},{id:`duration`,label:`Countdown Timer`,raw:`1:00`},{id:`rest`,label:`Rest Interval`,raw:`*1:00`},{id:`rep`,label:`Reps`,raw:`10`},{id:`distance`,label:`Distance`,raw:`400${t}`},{id:`rounds`,label:`Rounds`,raw:`(3)`},{id:`action`,label:`Action Cue`,raw:`[:rest]`},{id:`tag`,label:`Tag (#)`,raw:r}];return(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-60 overflow-y-auto`,children:a.map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":e.testId,onClick:()=>U(e.raw),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-primary font-semibold`,children:e.raw})]},e.id))})}if(r.kind===`duration`){let e=r.durationMeta??r4(r.raw),t=String(e.mins),n=String(e.secs),i=e.mode===`rest`?`*`:e.mode===`countup`?`^`:``,a=e.mode===`collectible`?[`:?`]:[`${i}:20`,`${i}:30`,`${i}1:00`,`${i}2:00`,`${i}5:00`,`${i}10:00`],l=t=>{let n=Math.max(5,e.mins*60+e.secs+t);V(i4({mode:e.mode===`collectible`?`countdown`:e.mode,mins:Math.floor(n/60),secs:n%60}))},u=Fhe.map(e=>({id:`min-${e}`,label:`${e}m`,value:String(e)})),d=(t4.includes(e.secs)?t4:[...t4,e.secs].sort((e,t)=>e-t)).map(e=>({id:`sec-${e}`,label:`:${String(e).padStart(2,`0`)}`,value:String(e)}));return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Timer Mode`}),s&&e.mode!==`collectible`&&(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_SCRUBBER_TOGGLE_BTN,onClick:s,className:$(`inline-flex items-center rounded-md px-2 text-xs font-semibold text-primary hover:bg-primary/10 hover:underline cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:o?`Use Presets`:`Use Scrubber`})]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Phe.map(t=>{let n=e.mode===t.mode,r=t.mode===`collectible`?`:?`:i4({mode:t.mode,mins:e.mode===`collectible`?1:e.mins,secs:e.mode===`collectible`?0:e.secs});return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(r,`Mode -> ${t.label}`),className:$(_4,R,n?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[t.label,` (`,t.sample,`)`]},t.mode)})})]}),e.mode!==`collectible`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Quick Presets`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:a.map(e=>{let t=r.raw.trim()===e;return(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e)})})]}),o?(0,q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,q.jsx)(g4,{label:`Minutes`,options:u,selectedValue:t,compact:c,onSelect:t=>V(i4({mode:e.mode,mins:parseInt(t.value,10)||0,secs:e.secs}))}),(0,q.jsx)(g4,{label:`Seconds`,options:d,selectedValue:n,compact:c,onSelect:t=>V(i4({mode:e.mode,mins:e.mins,secs:parseInt(t.value,10)||0}))})]}):(0,q.jsx)(`div`,{className:`grid grid-cols-4 gap-1.5`,children:[-15,-5,5,15].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>l(e),className:$(_4,R,`font-mono bg-popover text-foreground border-border hover:bg-muted rounded-md`),children:e>0?`+${e}s`:`${e}s`},e))})]})]})}if(r.kind===`rounds`){let e=/^\((\d+)\)$/.exec(r.raw.trim()),t=e?parseInt(e[1],10):null;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Rounds / Keyword`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`(3)`,`(4)`,`(5)`,`(8)`,`(10)`,`(21-15-9)`,`5x5`,`EMOM`,`AMRAP`,`Tabata`].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,r.raw.trim().toUpperCase()===e.toUpperCase()?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e))})]}),t!==null&&(0,q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`(${Math.max(1,t-1)})`),className:$(_4,R,`rounded-md bg-popover text-foreground border-border hover:bg-muted gap-1`),children:[(0,q.jsx)(z,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),` 1 Round`]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`(${t+1})`),className:$(_4,R,`rounded-md bg-popover text-foreground border-border hover:bg-muted gap-1`),children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),` 1 Round`]})]})]})}if(r.kind===`rep`){let e=parseInt(r.raw.replace(/^@/,``),10)||10;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Common Rep Targets`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`5`,`8`,`10`,`12`,`15`,`20`,`21`,`30`].map(e=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(e),className:$(_4,R,`font-mono`,r.raw.trim()===e?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e},e))})]}),(0,q.jsx)(`div`,{className:`grid grid-cols-4 gap-1.5`,children:[-5,-1,1,5].map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(String(Math.max(1,e+t))),className:$(_4,R,`rounded-md font-mono bg-popover text-foreground border-border hover:bg-muted`),children:t>0?`+${t}`:String(t)},t))})]})}if(r.kind===`resistance`){let e=r.resistanceMeta??a4(r.raw),t=(n4.includes(e.amount)?n4:[e.amount,...n4]).map(t=>({id:`amt-${t}`,label:`${e.hasAt?`@`:``}${t}${e.unit}`,value:t}));return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(o4({...e,hasAt:!e.hasAt})),className:$(_4,R,`font-mono`,e.hasAt?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:e.hasAt?`@ Prefix On`:`Add @ Prefix`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:Ihe.map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(o4({...e,unit:t})),className:$(_4,R,`font-mono`,e.unit===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:t},t))})]}),(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Load Amount`}),s&&(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_SCRUBBER_TOGGLE_BTN,onClick:s,className:$(`inline-flex items-center rounded-md px-2 text-xs font-semibold text-primary hover:bg-primary/10 hover:underline cursor-pointer`,c?`min-h-[44px]`:`min-h-[28px]`),children:o?`Use Presets`:`Use Scrubber`})]}),o?(0,q.jsx)(g4,{label:`Load (${e.unit})`,options:t,selectedValue:e.amount,compact:c,testId:`wheel-drum-unit-amount`,onSelect:t=>V(o4({...e,amount:t.value,altAmount:null}))}):(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:[`16`,`20`,`24`,`32`,`60`,`100`].map(t=>{let n=o4({...e,amount:t,altAmount:null});return(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(n),className:$(_4,R,`font-mono`,e.amount===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:n},t)})})]})}if(r.kind===`distance`){let e=r.distanceMeta??s4(r.raw),t=e.unit===`cal`?[`10`,`15`,`20`,`30`,`50`]:[`100`,`200`,`400`,`800`,`1000`,`2000`];return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:Lhe.map(t=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>V(`${e.amount}${t}`),className:$(_4,R,`font-mono`,e.unit===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:t},t))}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`${t}${e.unit}`),className:$(_4,R,`font-mono`,e.amount===t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[t,e.unit]},t))})]})}if(r.kind===`effort`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search movement or alias (e.g. swing, kbs)...`,`Search effort catalog`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-48 overflow-y-auto`,children:re.map(e=>{let t=e.label.toLowerCase()===r.raw.trim().toLowerCase()||e.slug===r.refSlug;return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border text-left flex items-center justify-between gap-2 cursor-pointer`,B,t?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold truncate`,children:e.label}),e.aliases.length>0&&(0,q.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate`,children:[`Aliases: `,e.aliases.slice(0,3).join(`, `)]})]}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground shrink-0`,children:e.scoped?`Scoped`:e.discipline||e.slug})]},e.slug)})})]});if(r.kind===`equipment`)return(0,q.jsxs)(q.Fragment,{children:[fe(`Search equipment...`,`Search equipment catalog`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-48 overflow-y-auto`,children:ie.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground`,children:e.slug})]},e.slug))})]});if(r.kind===`tag`){let e=x.trim().replace(/^#/,``),t=ae.some(t=>t.slug.toLowerCase()===e.toLowerCase());return(0,q.jsxs)(q.Fragment,{children:[fe(`Filter or create #tag...`,`Search or create tag`),e&&!t&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,onClick:async()=>{await W(`tag`,e),V(`#${e}`)},className:`inline-flex items-center gap-1.5 min-h-[36px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create & apply #`,e]}),(0,q.jsx)(`div`,{className:`flex flex-col gap-2 max-h-44 overflow-y-auto`,children:se.map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wide text-muted-foreground`,children:e}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>{let t=r.raw.trim().toLowerCase()===`#${e.slug}`.toLowerCase();return(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`#${e.slug}`),className:$(_4,R,`font-mono`,t?`bg-primary text-primary-foreground border-primary font-semibold`:`bg-popover text-foreground border-border hover:bg-muted`),children:[`#`,e.slug]},e.slug)})})]},e))})]})}if(r.kind===`action`)return(0,q.jsx)(`div`,{className:`flex flex-col gap-1`,children:Nhe.map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.code),className:$(`w-full rounded-md border text-left flex items-center justify-between gap-2 cursor-pointer`,B,r.raw.trim()===e.code?`bg-primary/10 border-primary text-foreground font-semibold`:`bg-popover border-border text-foreground hover:bg-muted`),children:[(0,q.jsxs)(`span`,{className:`min-w-0 flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.desc})]}),(0,q.jsx)(`span`,{className:`text-xs font-mono text-primary font-semibold shrink-0`,children:e.code})]},e.code))});if(r.kind===`lintError`)return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`p-2.5 rounded-md border border-destructive/40 bg-destructive/10 text-destructive text-xs flex items-start gap-2`,children:[(0,q.jsx)(oe,{className:`h-4 w-4 shrink-0 mt-0.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r.lintMessage})]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:(r.lintFixes??[]).map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:()=>V(e,`Fixed -> ${e}`),className:$(_4,R,`bg-primary text-primary-foreground border-primary font-semibold`),children:[`Fix: `,e]},e))})]});if(r.kind===`unresolved`){if(r.isTag){let e=r.raw.replace(/^#/,``).trim();return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_TAG_BTN,disabled:D,onClick:()=>void W(`tag`,e),className:`inline-flex items-center gap-1.5 min-h-[38px] px-3 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer self-start`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Create Tag #`,e]}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:h4(``).slice(0,8).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(`#${e.slug}`),className:$(_4,R,`font-mono bg-popover text-foreground border-border hover:bg-muted`),children:[`#`,e.slug]},e.slug))})]})}return(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`p-2 rounded-md border border-warning/40 bg-warning/10 text-warning text-xs flex items-start gap-2`,children:[(0,q.jsx)(aa,{className:`h-4 w-4 shrink-0 mt-0.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r.diagnostic?.message??`"${r.raw}" is not in your catalog yet.`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_EFFORT_BTN,disabled:D,onClick:()=>void W(`effort`,r.raw),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md bg-primary text-primary-foreground text-xs font-semibold cursor-pointer`,children:[(0,q.jsx)(ti,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Effort`]}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_ALIAS_BTN,disabled:D,onClick:()=>w(e=>!e),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md border border-border bg-popover text-foreground hover:bg-muted text-xs font-medium cursor-pointer`,children:`+ Alias`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":Q.EDITOR_DEFINE_EQUIPMENT_BTN,disabled:D,onClick:()=>void W(`equipment`,r.raw),className:`inline-flex items-center gap-1 min-h-[36px] px-2.5 rounded-md border border-border bg-popover text-foreground hover:bg-muted text-xs font-medium cursor-pointer`,children:`+ Equipment`})]}),C&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1.5 pt-1 border-t border-border`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:[`Link "`,r.raw,`" as alias to:`]}),fe(`Search target effort...`,`Search target effort for alias`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-36 overflow-y-auto`,children:re.slice(0,12).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>void ne(e.slug,e.label,r.raw),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-primary`,children:`Link alias`})]},e.slug))})]}),(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Or replace with existing movement:`}),!C&&fe(`Search known movements...`,`Search known movements`),(0,q.jsx)(`div`,{className:`flex flex-col gap-1 max-h-32 overflow-y-auto`,children:re.slice(0,6).map(e=>(0,q.jsxs)(`button`,{type:`button`,onClick:()=>V(e.label),className:$(`w-full rounded-md border border-border bg-popover hover:bg-muted text-left flex items-center justify-between gap-2 cursor-pointer`,B),children:[(0,q.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:e.label}),(0,q.jsx)(`span`,{className:`text-[11px] font-mono text-muted-foreground`,children:`Replace`})]},e.slug))})]})]})}return(0,q.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Token `,(0,q.jsx)(`code`,{className:`font-mono text-foreground`,children:r.raw}),` can be edited inline in the editor.`]})})()}),u&&(0,q.jsxs)(`div`,{className:`px-3 py-2 border-t border-border bg-popover/70 flex items-center justify-between gap-2 text-[11.5px] text-muted-foreground shrink-0`,children:[(0,q.jsx)(`span`,{children:`Line-safe transaction`}),(0,q.jsx)(`span`,{children:`Esc closes inspector`})]})]})},y4=340,b4=12,x4=({open:e,anchorRect:t,editorDom:n,view:r,mode:i,inspection:a,token:o,scope:s,docText:c,onClose:l,onMutate:u,onModeChange:d,onStepToken:f,onDockDrawer:p})=>{let m=(0,K.useRef)(null),[h,g]=(0,K.useState)(!1);(0,K.useEffect)(()=>{g(!1)},[o?.id,i]),(0,K.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),l(),typeof r?.focus==`function`&&r.focus())},n=e=>{let t=e.target;t&&(m.current?.contains(t)||t.closest(`[data-inspector-trigger="true"]`)||l())};return document.addEventListener(`keydown`,t,!0),document.addEventListener(`pointerdown`,n),()=>{document.removeEventListener(`keydown`,t,!0),document.removeEventListener(`pointerdown`,n)}},[e,l,r]);let _=(0,K.useMemo)(()=>{let e=typeof window<`u`?window.innerWidth:1024,r=typeof window<`u`?window.innerHeight:768;if(t&&t.width>0&&t.height>0&&t){let n=r-t.bottom<340&&t.top>280,i=Math.max(b4,Math.min(t.left,e-y4-b4));return n?{left:i,bottom:Math.max(b4,r-t.top+8)}:{left:i,top:Math.max(b4,Math.min(t.bottom+8,r-140))}}let i=n?.getBoundingClientRect();return i&&(i.width>0||i.height>0||i.top>0||i.left>0)&&i?{top:Math.max(b4,Math.min(i.top+48,r-200)),left:Math.max(b4,Math.min(i.left+16,e-y4-b4))}:{top:72,left:24}},[t,n]);return e?(0,q.jsx)(`div`,{ref:m,role:`dialog`,"aria-label":`Syntax Token Inspector`,"data-testid":Q.EDITOR_INSPECTOR_POPOVER,style:_,className:`fixed z-40 flex max-h-[min(540px,calc(100vh-28px))] w-[340px] max-w-[calc(100vw-24px)] flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-xl`,children:(0,q.jsx)(v4,{view:r,mode:i,inspection:a,token:o,scope:s,docText:c,useScrubber:h,onToggleScrubber:()=>g(e=>!e),compact:!1,showHeader:!0,showFooter:!0,showStepButtons:i===`token`,showClose:!0,showDockButton:!!p,onDockDrawer:p,onMutate:u,onModeChange:d,onStepToken:f,onClose:()=>{l(),typeof r?.focus==`function`&&r.focus()}})}):null},Zhe={[Y.Duration]:{label:`Timer`,Icon:nr,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[Y.Rep]:{label:`Reps`,Icon:F,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[Y.Effort]:{label:`Exercise`,Icon:Pr,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[Y.Rounds]:{label:`Rounds`,Icon:Ue,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[Y.Distance]:{label:`Distance`,Icon:Aee,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[Y.Resistance]:{label:`Weight`,Icon:Hn,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[Y.Equipment]:{label:`Equipment`,Icon:Ui,textClass:`text-metric-equipment`,bgClass:`bg-metric-equipment/10`,borderClass:`border-metric-equipment/30`},[Y.Action]:{label:`Action`,Icon:Eee,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[Y.Label]:{label:`Label`,Icon:On,textClass:`text-muted-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border`}},Qhe={tags:[],defaultEquipment:[],customMetricTypes:[]};function S4(e){switch(e){case Y.Duration:return`duration`;case Y.Rep:return`rep`;case Y.Rounds:return`rounds`;case Y.Effort:return`effort`;case Y.Equipment:return`equipment`;case Y.Resistance:return`resistance`;case Y.Distance:return`distance`;case Y.Action:return`action`;default:return`custom`}}function $he(e,t,n,r){let i=t.tokens.find(t=>t.metric===e);if(i)return i;let a=S4(e.type),o=String(e.image??e.value??``).trim(),s=t.tokens.find(e=>e.kind===a&&(o===``||e.raw.trim().toLowerCase()===o.toLowerCase()||e.raw.toLowerCase().includes(o.toLowerCase())));if(s)return s;let c=S4(e.type),l=o||String(e.type),u={id:`fallback-${c}-${n}`,kind:c,raw:l,displayLabel:c===`rep`?`${l} reps`:l,from:r.lineFrom,to:r.lineTo,lineNum:r.cursorLine,metric:e};return c===`duration`&&(u.durationMeta=r4(l)),c===`resistance`&&(u.resistanceMeta=a4(l)),c===`distance`&&(u.distanceMeta=s4(l)),u}var ege=({metric:e,tooltip:t,isFocused:n,isSelected:r,onClick:i})=>{let a=Zhe[e.type],o=e.type===Y.Hint,s=e.name??e.image??(e.value===void 0?``:String(e.value)),c=a?.label??String(e.type),l=a?.Icon,u=$(`inline-flex items-center gap-1 px-2 py-0.5 min-h-[24px] rounded-full border text-[11px] leading-tight font-medium whitespace-nowrap tabular-nums`,`pointer-events-auto transition-colors`,a?.bgClass??`bg-muted/40`,a?.textClass??`text-muted-foreground`,a?.borderClass??`border-border`,n&&`font-bold ring-1 ring-foreground/20`,r&&`ring-2 ring-primary/50 border-primary`);return o?(0,q.jsx)(`span`,{title:t,className:u,children:(0,q.jsx)(`span`,{children:e.icon})}):(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:t,onClick:i,className:$(u,`hover:opacity-90 focus-visible:outline-2 focus-visible:outline-ring cursor-pointer`),children:[l?(0,q.jsx)(l,{weight:`bold`,className:`h-3 w-3 shrink-0`}):null,(0,q.jsx)(`span`,{className:`sr-only`,children:c}),(0,q.jsx)(`span`,{className:`font-semibold`,children:s||c})]})};function C4(e){let t=Xo(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function tge(e,t,n){try{let r=e.coordsAtPos(t.lineFrom);if(!r)return null;let i=typeof t.lineTo==`number`?e.coordsAtPos(t.lineTo)??r:r,a=e.dom?.getBoundingClientRect?.()??{top:0,left:0,width:600},o=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:600},s=Math.max(0,o.left-a.left),c=s+Math.max(240,o.width),l=i.left-a.left+12,u=c-l;if(n?u>210:u>=160){let e=typeof i.top==`number`?i.top:i.bottom-20;return{top:Math.max(0,e-a.top-1),left:l,maxWidth:u-4,belowLine:!1}}return{top:i.bottom-a.top+3,left:s,maxWidth:Math.max(220,o.width),belowLine:!0}}catch{return null}}var nge=({view:e,cursorVersion:t,getCursorFocusState:n,noteId:r,hidden:i=!1,activeTokenId:a=null,drawerOpen:o=!1,onOpenInspector:s,onToggleDrawer:c,onPeekEntity:l,onClosePeek:u})=>{let[d,f]=(0,K.useState)(null),[p,m]=(0,K.useState)(null),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(Qhe),[y,b]=(0,K.useState)(null),x=(0,K.useRef)(null),S=(0,K.useRef)(void 0),C=(0,K.useCallback)(()=>{if(!e||i){S.current=void 0,m(null),f(null);return}let t=(n??E2)(e.state);m(t);let r=t?tge(e,t,S.current):null;S.current=r?.belowLine,f(r)},[e,n,i]);(0,K.useEffect)(()=>{C()},[C,t]),(0,K.useEffect)(()=>{if(!e||i)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,i]);let w=e?.state?.doc&&typeof e.state.doc.toString==`function`?e.state.doc.toString():``;(0,K.useEffect)(()=>{if(s||!y||!w)return;let e=!1;return Z2(r,w).then(t=>{e||v(t)}),()=>{e=!0}},[s,y,r,w]);let T=(0,K.useMemo)(()=>{if(!e?.state||!p)return{contextKind:`markdown`,section:null,focus:null,lineNum:1,lineFrom:0,lineTo:0,lineText:``,tokens:[],lintFixes:[]};try{return l4(e.state,p)}catch{return{contextKind:`markdown`,section:p.section,focus:p,lineNum:p.cursorLine,lineFrom:p.lineFrom,lineTo:p.lineTo,lineText:typeof e.state.doc?.sliceString==`function`?e.state.doc.sliceString(p.lineFrom,p.lineTo):``,tokens:[],lintFixes:[]}}},[e,p]),E=(0,K.useMemo)(()=>{if(!p?.section)return{lineKey:null,lineText:``,lineRefs:null,visibleMetrics:[],tokens:[],refs:[],tagRefs:[],diagnostics:[],unresolvedTagSlugs:[],lintFixes:[],malformed:!1};let t=`${p.section.id}:${p.cursorLine}`,n=typeof e?.state?.doc?.sliceString==`function`?e.state.doc.sliceString(p.lineFrom,p.lineTo):T.lineText??``,r=p.allStatements?.filter(e=>e.meta?.line===p.cursorLine-p.section.startLine)??(p.statement?[p.statement]:[]),i=r.flatMap(e=>e.metrics.toArray()).filter(e=>{if(e.type===Y.Sound||e.type===Y.System||e.type===Y.Hint&&!e.icon||e.type===Y.Custom&&typeof e.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(e.value.trim()))return!1;if(e.type===Y.Effort||e.type===Y.Equipment){let t=C4(e);if(t.refs.length>0||t.diagnostics.length>0)return!1}return!0}),a=O1(i,`runtime-badge`),o=r.flatMap(e=>e.metrics.toArray()),s=[],c=[],l=[];for(let e of o){let t=C4(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;s.includes(t)||(s.push(t),c.push(e))}l.push(...t.diagnostics)}let u=[],d=[];for(let e of o){let t=as(e.metadata);if(t){u.some(e=>e.slug===t.slug)||u.push(t);continue}if(e.type===Y.Custom&&typeof e.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(e.value.trim())){let t=e.value.trim().slice(1);d.includes(t)||d.push(t)}}let f=typeof e?.state?.doc?.sliceString==`function`?y2(e.state.doc.sliceString(p.lineFrom,p.lineTo)):null;return{lineKey:t,lineText:n,lineRefs:f,visibleMetrics:i,tokens:a,refs:c,tagRefs:u,diagnostics:l,unresolvedTagSlugs:d,lintFixes:T.lintFixes,malformed:!!f?.malformed}},[p,e,T.lineText,T.lintFixes]),[D,O]=(0,K.useState)({lineKey:null,lineText:``,diagKeys:[],tagSlugs:[],lintIds:[],malformed:!1}),[k,A]=(0,K.useState)(null),j=(0,K.useRef)(null),M=(0,K.useMemo)(()=>E.diagnostics.map((e,t)=>`${e.reason}-${e.token?.trim()??t}`),[E.diagnostics]),N=(0,K.useMemo)(()=>E.lintFixes.map(e=>e.id),[E.lintFixes]),P=`${E.lineKey??``}\u0000${E.lineText}\u0000${M.join(`,`)}\u0000${E.unresolvedTagSlugs.join(`,`)}\u0000${N.join(`,`)}\u0000${E.malformed?`1`:`0`}`;(0,K.useEffect)(()=>{if(!E.lineKey)return;if(D.lineKey!==E.lineKey||D.lineText===E.lineText){O({lineKey:E.lineKey,lineText:E.lineText,diagKeys:M,tagSlugs:E.unresolvedTagSlugs,lintIds:N,malformed:E.malformed});return}let e=setTimeout(()=>{O({lineKey:E.lineKey,lineText:E.lineText,diagKeys:M,tagSlugs:E.unresolvedTagSlugs,lintIds:N,malformed:E.malformed})},320);return()=>clearTimeout(e)},[P]);let F=E.visibleMetrics.length>0||E.refs.length>0||E.tagRefs.length>0;(0,K.useEffect)(()=>{if(!E.lineKey||F||E.lineText.trim()===``){E.lineKey&&F?j.current={lineKey:E.lineKey,visibleMetrics:E.visibleMetrics,tokens:E.tokens,refs:E.refs,tagRefs:E.tagRefs}:(!E.lineKey||E.lineText.trim()===``)&&(j.current=null),A(null);return}let e=j.current;if(!e||e.lineKey!==E.lineKey){A(null);return}A(e);let t=setTimeout(()=>{j.current=null,A(null)},220);return()=>clearTimeout(t)},[E.lineKey,E.lineText,F,E.visibleMetrics,E.tokens,E.refs,E.tagRefs]);let I=e?.state&&typeof e.state.field==`function`?Da(e.state):null,ee=I===`active`,L=I!==null;if(i||!d||!p?.section||ee)return null;let R=!F&&k!==null&&k.lineKey===E.lineKey&&E.lineText.trim()!==``,z=R?k.visibleMetrics:E.visibleMetrics,B=R?k.tokens:E.tokens,V=R?k.refs:E.refs,H=R?k.tagRefs:E.tagRefs,U=D.lineKey!==null&&D.lineKey===E.lineKey&&D.lineText!==E.lineText,te=U?new Set(D.diagKeys):null,W=U?new Set(D.tagSlugs):null,ne=U?new Set(D.lintIds):null,re=te?E.diagnostics.filter((e,t)=>te.has(`${e.reason}-${e.token?.trim()??t}`)):E.diagnostics,ie=W?E.unresolvedTagSlugs.filter(e=>W.has(e)):E.unresolvedTagSlugs,ae=ne?E.lintFixes.filter(e=>ne.has(e.id)):E.lintFixes,oe=U?D.malformed&&E.malformed:E.malformed,se=E.lineRefs,ce=typeof e?.state?.facet==`function`?e.state.facet(HM)?.()??null:null,le=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&se?.equipment.includes(e.token)?`equipment`:`effort`,ue=e=>typeof e==`string`&&e.trim()?e:null,de=(e,t,n)=>{let r=n?.getBoundingClientRect?.()??null;if(s){s({mode:e,token:t,anchorRect:r});return}b(n=>n&&n.mode===e&&n.token?.id===t?.id?null:{mode:e,token:t,anchorRect:r})},fe=async t=>{if(!e)return;let n=e.state.doc.sliceString(p.lineFrom,p.lineTo),r=jQ.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort...`,sources:[p2(`effort`)]});if(t.dismissed)return;let i=ue(t.item.payload);if(!i)return;e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(n,{effort:i})}});return}let i=[...se?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)...`:`Set equipment...`,sources:[p2(`equipment`)]});if(e.dismissed)break;let t=ue(e.item.payload);t&&!i.includes(t)&&i.push(t)}((se?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(n,{equipment:i})}})},pe=async()=>{if(!e)return;let t=e.state.doc.sliceString(p.lineFrom,p.lineTo),n=jQ.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)...`,sources:[p2(`effort`)]});i.dismissed||(r=ue(i.item.payload)??void 0);let a=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)...`,sources:[p2(`equipment`)]});if(e.dismissed)break;let t=ue(e.item.payload);t&&!a.includes(t)&&a.push(t)}!r&&a.length===0||e.dispatch({changes:{from:p.lineFrom,to:p.lineTo,insert:b2(t,{effort:r,equipment:a})}})},me=()=>{e&&typeof e.dispatch==`function`&&e.dispatch({effects:[S2.of(null)]}),C()},he=async t=>{if(!e||!t.token)return;let n=le(t),r=await jQ.getState().open({placeholder:`Replace "${t.token}"...`,sources:[p2(n,t.candidates)]});if(r.dismissed)return;let i=ue(r.item.payload);if(!i)return;let a=e.state.doc.sliceString(p.lineFrom,p.lineTo).indexOf(t.token);a<0||e.dispatch({changes:{from:p.lineFrom+a,to:p.lineFrom+a+t.token.length,insert:i}})},ge=async(e,t)=>{t.trim()&&(e===`effort`?await h2(t):await _2(t),me())},_e=async e=>{if(!e.trim())return;let t=await jQ.getState().open({placeholder:`Link "${e}" as alias to effort...`,sources:[p2(`effort`)]});if(t.dismissed)return;let n=ue(t.item.payload);n&&(await g2(n,e),me())},ve=async e=>{e.trim()&&(await v2(e),me())},ye=(t,n,r)=>{if(!e)return;let i=t.type===Y.Effort?`effort`:t.type===Y.Equipment?`equipment`:null;if(i&&l){let e=String(t.name??t.image??t.value??``).trim(),n=af(e)||e;if(n){l({kind:i,slug:n,label:e||n});return}}if(i&&se?.jsonFrom!==void 0&&se.jsonFrom>=0){fe(i);return}let a=$he(t,T,n,p);de(`token`,a,r.currentTarget)},be=(e,t)=>{if(l){l({kind:e.kind,slug:e.slug,label:e.label});return}if(se?.jsonFrom!==void 0&&se.jsonFrom>=0){fe(e.kind);return}let n=T.tokens.find(t=>t.refSlug===e.slug||t.kind===e.kind&&t.raw.toLowerCase().includes(e.label.toLowerCase()))??{id:`ref-${e.kind}-${e.slug}`,kind:e.kind,raw:e.label,displayLabel:e.label,from:p.lineFrom,to:p.lineTo,lineNum:p.cursorLine,refKind:e.kind,refSlug:e.slug};de(`token`,n,t.currentTarget)},xe=z.length>0||V.length>0||H.length>0||re.length>0||ie.length>0||ae.length>0||oe,Se=!!(e?.state?.doc&&typeof e.state.doc.lineAt==`function`),Ce=p.section.type===`time`||p.section.type===`log`,we=p.section.type===`log`?`log`:`time`,Te=y?.token&&T.tokens.find(e=>e.id===y.token?.id||e.from===y.token?.from&&e.kind===y.token?.kind);return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{ref:x,className:$(`cm-metric-inline-panel`,`absolute z-[15]`,`inline-flex items-center gap-1 px-1.5 py-0.5 min-h-[24px]`,d.belowLine?`pointer-events-auto bg-card/95 border border-border rounded-md shadow-xs`:`pointer-events-none bg-transparent`,`transition-opacity duration-100 max-w-full`),style:{top:d.top,left:d.left,maxWidth:d.maxWidth},role:`region`,"aria-live":L?`off`:`polite`,"aria-label":`Metric inline panel`,children:xe?(0,q.jsxs)(`div`,{"data-testid":Q.EDITOR_TOKEN_STRIP,className:$(`flex items-center gap-1`,d.belowLine?`flex-wrap`:`flex-nowrap overflow-x-auto max-w-full scrollbar-none`),children:[z.map((e,t)=>{let n=T.tokens.find(t=>t.metric===e),r=!!(a&&n?.id===a);return(0,q.jsx)(ege,{metric:e,tooltip:e.type===Y.Hint?String(e.value??``):B[t]?.tooltip,isFocused:p.focusedMetric===e,isSelected:r,onClick:n=>ye(e,t,n)},`${e.type}-${t}`)}),V.map(e=>{let t=e.kind===`effort`&&p.focusedMetric?.type===Y.Effort||e.kind===`equipment`&&p.focusedMetric?.type===Y.Equipment,n=e.kind===`effort`?Pr:Ui;return(0,q.jsxs)(`div`,{className:$(`pointer-events-auto inline-flex items-center gap-0.5 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium whitespace-nowrap`,e.kind===`effort`?`bg-metric-effort/10 text-metric-effort border-metric-effort/30`:`bg-metric-equipment/10 text-metric-equipment border-metric-equipment/30`,t&&`font-bold ring-1 ring-foreground/20`),children:[(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:`${e.kind===`effort`?`Effort`:`Equipment`}: ${e.label} (${e.slug})${e.matchedAlias?` · matched alias "${e.matchedAlias}"`:``} · click to edit or change`,onClick:t=>be(e,t),className:`inline-flex items-center gap-1 cursor-pointer hover:opacity-80`,children:[(0,q.jsx)(n,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{className:`sr-only`,children:e.kind===`effort`?`Exercise`:`Equipment`}),(0,q.jsx)(`span`,{className:`font-semibold`,children:e.label})]}),ce&&(0,q.jsx)(`a`,{href:ce.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`opacity-70 hover:opacity-100 ml-0.5 inline-flex items-center`,onClick:e=>e.stopPropagation(),children:(0,q.jsx)(Ye,{weight:`bold`,className:`h-2.5 w-2.5`})})]},`${e.kind}:${e.slug}`)}),H.map(e=>(0,q.jsxs)(`div`,{className:`pointer-events-auto inline-flex items-center gap-0.5 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium bg-primary/10 text-primary border-primary/30 whitespace-nowrap`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,title:e.soundProfileId?`Tag ${e.label} · names the ${e.soundProfileId} sound profile`:`Tag ${e.label}`,onClick:t=>{if(l){l({kind:`tag`,label:e.slug||e.label});return}de(`token`,T.tokens.find(t=>t.isTag&&t.raw.includes(e.slug))??{id:`tag-${e.slug}`,kind:`tag`,raw:`#${e.slug}`,displayLabel:`#${e.slug}`,from:p.lineFrom,to:p.lineTo,lineNum:p.cursorLine,tagRef:e,isTag:!0},t.currentTarget)},className:`inline-flex items-center gap-0.5 cursor-pointer hover:opacity-80`,children:[(0,q.jsx)(`span`,{children:`#`}),(0,q.jsx)(`span`,{className:`font-semibold font-mono`,children:e.label})]}),ce&&(0,q.jsx)(`a`,{href:ce.openHref(`tag`,e.slug),title:`Open the ${e.label} tag`,"aria-label":`Open the ${e.label} tag`,className:`opacity-70 hover:opacity-100 ml-0.5 inline-flex items-center`,onClick:e=>e.stopPropagation(),children:(0,q.jsx)(Ye,{weight:`bold`,className:`h-2.5 w-2.5`})})]},`tag:${e.slug}`)),ae.map(t=>(0,q.jsxs)(`span`,{className:`pointer-events-auto inline-flex items-center gap-1 px-1.5 py-0.5 min-h-[22px] rounded-full border border-dashed text-[11px] leading-tight font-medium bg-destructive/10 text-destructive border-destructive/30 whitespace-nowrap`,title:t.message,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{className:`font-mono`,children:t.raw}),t.fixes.slice(0,2).map(n=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:r=>{r.stopPropagation(),e&&f4(e,t,n)},className:`rounded-full bg-background/80 px-1.5 py-0.5 font-mono text-[10px] font-semibold text-foreground hover:bg-primary hover:text-primary-foreground cursor-pointer transition-colors`,children:[`Fix: `,n]},n))]},t.id)),oe&&(0,q.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-[4px] border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:`Malformed reference JSON`})]}),ie.map(e=>(0,q.jsxs)(`span`,{"data-testid":`editor-tag-unknown`,title:`Unknown tag #${e} — click to define`,className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-dashed text-[11px] leading-tight font-medium bg-warning/10 text-warning border-warning/40 whitespace-nowrap`,children:[l?(0,q.jsxs)(`button`,{type:`button`,onClick:()=>l({kind:`unrecognized`,term:`#${e}`}),className:`font-mono font-semibold cursor-pointer hover:text-foreground`,children:[`#`,e]}):(0,q.jsxs)(`span`,{className:`font-mono font-semibold`,children:[`#`,e]}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-create-tag-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold ml-0.5`,onClick:t=>{t.stopPropagation(),l?l({kind:`unrecognized`,term:`#${e}`}):ve(e)},children:`+ Tag`})]},`unresolved-tag:${e}`)),re.map((e,t)=>{let n=le(e),r=e.token?.trim()??``,i=e.reason===`unknown-effort`,a=`${e.reason}-${r||t}`,o=!l&&(h===a||h===`all`);return(0,q.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,onClick:()=>{if(l&&r){l({kind:`unrecognized`,term:r});return}o||g(a)},className:$(`pointer-events-auto inline-flex flex-wrap items-center gap-1.5 px-2 py-0.5 min-h-[22px] rounded-[6px] border border-dashed text-[11px] leading-tight font-medium bg-warning/10 text-warning border-warning/40 max-w-full`,!o&&`rounded-full whitespace-nowrap cursor-pointer hover:bg-warning/15`),children:[(0,q.jsx)(`span`,{children:`?`}),(0,q.jsx)(`span`,{className:`font-semibold`,children:e.token??e.reason}),o?(0,q.jsxs)(`span`,{className:`inline-flex flex-wrap items-center gap-1.5 pl-1 border-l border-warning/30`,children:[r&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":`editor-create-${n}-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),ge(n,r)},children:[`+ `,n===`effort`?`Effort`:`Equipment`]}),r&&i&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-link-alias-inline`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),_e(r)},children:`+ Alias`}),r&&i&&(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-create-equipment-from-token`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{e.stopPropagation(),ge(`equipment`,r)},children:`+ Equipment`}),(0,q.jsx)(`button`,{type:`button`,className:`underline cursor-pointer hover:text-foreground`,onClick:t=>{t.stopPropagation(),he(e)},children:`Select existing`}),ce&&(0,q.jsx)(`a`,{href:ce.createHref(n),className:`underline hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`Create page`})]}):(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-define-token`,className:`underline cursor-pointer hover:text-foreground font-semibold`,onClick:e=>{if(e.stopPropagation(),l&&r){l({kind:`unrecognized`,term:r});return}g(a)},children:`Define`})]},a)}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void pe(),className:`pointer-events-auto inline-flex items-center px-2 py-0.5 min-h-[22px] rounded-full border border-dashed border-border text-[11px] leading-tight text-muted-foreground hover:text-foreground hover:border-foreground cursor-pointer whitespace-nowrap`,children:`+ Metric`}),Se&&Ce&&(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,title:`Configure ${we.toUpperCase()} block header or templates`,onClick:e=>de(`block`,T.tokens[0]??null,e.currentTarget),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-border bg-muted/40 text-[11px] leading-tight font-medium text-muted-foreground hover:text-foreground cursor-pointer whitespace-nowrap`,children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:we===`log`?`LOG`:`TIMER`})]}),c&&(0,q.jsxs)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_INSPECTOR_DRAWER_TOGGLE,"aria-pressed":o,title:`Toggle Right Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,onClick:()=>{o||u?.(),c()},className:$(`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border text-[11px] leading-tight font-medium cursor-pointer whitespace-nowrap transition-colors`,o?`border-primary bg-primary/10 text-primary`:`border-border bg-muted/40 text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(Nee,{weight:`bold`,className:`h-3 w-3 shrink-0`}),(0,q.jsx)(`span`,{children:`Drawer`})]})]}):(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[(0,q.jsx)(`span`,{className:`text-[11px] text-muted-foreground/70 italic select-none`,children:`No metrics on this line`}),Se&&Ce&&(0,q.jsx)(`button`,{type:`button`,"data-inspector-trigger":`true`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,onClick:e=>de(`add`,null,e.currentTarget),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 min-h-[22px] rounded-full border border-dashed border-border bg-card/70 text-[11px] text-muted-foreground hover:bg-card hover:text-foreground hover:border-foreground/40 transition-colors cursor-pointer`,children:`+ Token`})]})}),!s&&y&&(0,q.jsx)(x4,{open:!0,anchorRect:y.anchorRect,editorDom:e?.dom??null,view:e,mode:y.mode,inspection:T,token:Te??y.token,scope:_,docText:w,onClose:()=>b(null),onMutate:(e,t)=>{C()},onModeChange:e=>b(t=>t&&{...t,mode:e}),onStepToken:e=>{if(!y||T.tokens.length===0)return;let t=T.tokens.findIndex(e=>e.id===(Te?.id??y.token?.id)),n=((t>=0?t:0)+e+T.tokens.length)%T.tokens.length;b(e=>e&&{...e,token:T.tokens[n]})}})]})},rge=`[data-page-sticky-boundary="true"]`;function ige(e){if(e)return e;let t=document.querySelector(`[data-mobile-editor-deck="true"]`);if(t)return t;for(let e of document.querySelectorAll(`[data-testid]`)){let t=e.getAttribute(`data-testid`);if(t===Q.MOBILE_WHEEL_COMPOSER||t===Q.MOBILE_TYPING_BAR)return e}return null}function age(e){let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){let e=t.getAttribute(`data-testid`);if(e===`tour-runway`||e===`scroll-runway-section`||e?.startsWith(`guide-runway-`))return!0;t=t.parentElement}return!1}function oge(e,t){if(typeof window>`u`||typeof document>`u`)return{safeTop:14,safeBottom:58,idealCenterY:36,vvHeight:0,keyboardOffsetBottom:0};let n=window.visualViewport,r=n?.offsetTop??0,i=n?.height??window.innerHeight,a=r+i,o=Math.max(0,window.innerHeight-a),s=0,c=document.querySelectorAll(rge);for(let t of c){if(t.contains(e.dom))continue;let n=t.getBoundingClientRect();n.height<=0||n.bottom<=0||(s=Math.max(s,n.bottom))}let l=s>0?s:r,u=a,d=ige(t);if(d){let e=d.getBoundingClientRect();e.height>0&&e.top>0&&(u=Math.min(a,e.top))}let f=Math.max(r,l)+14,p=Math.max(f+44,u-14);return{safeTop:f,safeBottom:p,idealCenterY:f+(p-f)*.46,vvHeight:i,keyboardOffsetBottom:o}}function sge(e){if(typeof window>`u`)return null;let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){if(window.getComputedStyle(t).position===`sticky`)return t;t=t.parentElement}return null}function cge(e){let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t).overflowY;if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight+1)return t;t=t.parentElement}return null}function w4(e,t,n){let r=cge(e);if(r&&typeof r.scrollBy==`function`){let e=r.scrollTop;return r.scrollBy({top:t,behavior:n}),r.scrollTop-e}if(typeof window.scrollBy==`function`){let e=window.scrollY;return window.scrollBy({top:t,behavior:n}),window.scrollY-e}return 0}function T4(e,t){if(typeof window>`u`||!e||!e.dom||window.visualViewport&&window.visualViewport.scale>1.05)return!1;let n=t?.pos??e.state.selection.main.head,r;try{r=e.coordsAtPos(n)}catch{return!1}if(!r||r.top===0&&r.bottom===0)return!1;let{safeTop:i,safeBottom:a,idealCenterY:o}=oge(e,t?.overlayEl);if(r.top>=i&&r.bottom<=a&&!t?.forceCenter)return!1;let s=(r.top+r.bottom)/2-o;if(Math.abs(s)<=1)return!1;let c=age(e.dom),l=sge(e.dom),u=t?.behavior??`auto`;if(!c&&l){let t=l.getBoundingClientRect();if(t.height>0){let n=Number.parseFloat(window.getComputedStyle(l).top),r=Number.isFinite(n)?n:0;if(s>0&&t.top>r+1){let n=Math.max(s,t.bottom-a),i=Math.min(n,t.top-r);if(i>2){let t=w4(e.dom,i,u);s-=t===0?i:t}}else if(s<0&&t.top<r-1){let n=Math.max(s,t.top-r);if(n<-2){let t=w4(e.dom,n,u);s-=t===0?n:t}}}}let d=e.scrollDOM;if(d&&Math.abs(s)>1){let e=window.getComputedStyle(d),t=d.scrollHeight-d.clientHeight;if(t>1&&e.overflowY!==`hidden`&&e.overflowY!==`visible`){let e=d.scrollTop,n=Math.max(0,Math.min(t,e+s)),r=n-e;Math.abs(r)>.5&&(d.scrollTop=n,s-=r)}}return Math.abs(s)>2&&!c&&!l&&w4(e.dom,s,u),!0}var lge={tags:[],defaultEquipment:[],customMetricTypes:[]},uge=[{label:`#`,ariaLabel:`Insert tag prefix #`,insert:`#`,triggerComplete:!0},{label:`@`,ariaLabel:`Insert resistance prefix @`,insert:`@`},{label:`*`,ariaLabel:`Insert rest prefix *`,insert:`*`},{label:`:`,ariaLabel:`Insert timer separator :`,insert:`:`},{label:`[:`,ariaLabel:`Insert action cue [:`,insert:`[:`,triggerComplete:!0},{label:`()`,ariaLabel:`Insert rounds parentheses ()`,insert:`()`,cursorOffset:1},{label:`[[`,ariaLabel:`Insert wiki link [[`,insert:`[[`,triggerComplete:!0},{label:`|`,ariaLabel:`Insert WQL pipe |`,insert:` | `}];function dge(e){switch(e.type){case`variable`:return`bg-metric-effort`;case`unit`:return`bg-metric-resistance`;case`constant`:return`bg-metric-action`;case`keyword`:return`bg-metric-time`;case`property`:return`bg-muted-foreground`;default:return`bg-primary`}}function fge(e){let t=e.metricType?.toLowerCase();if(t===`duration`)return`duration`;if(t===`rep`)return`rep`;if(t===`rounds`)return`rounds`;if(t===`effort`)return`effort`;if(t===`equipment`)return`equipment`;if(t===`resistance`)return`resistance`;if(t===`distance`)return`distance`;if(t===`action`)return`action`;let n=e.rawText.trim();return n.startsWith(`#`)?`tag`:/^\*?\d+:\d{2}$/.test(n)||n.startsWith(`:`)?`duration`:`custom`}function pge(e,t,n){if(!e||e.kind!==`metric`)return n[0]??null;let r=n.find(t=>Math.max(t.from,e.from)<Math.min(t.to,e.to)||t.from===e.from&&t.to===e.to);if(r)return r;let i=e.rawText.trim()||e.label,a=fge(e),o={id:`slot-${e.id}`,kind:a,raw:i,displayLabel:a===`rep`?`${i} reps`:e.label||i,from:e.from,to:e.to,lineNum:t,isTag:i.startsWith(`#`),isRest:a===`duration`&&i.startsWith(`*`)};return a===`duration`&&(o.durationMeta=r4(i)),a===`resistance`&&(o.resistanceMeta=a4(i)),a===`distance`&&(o.distanceMeta=s4(i)),o}var mge=({view:e,noteId:t,cursorVersion:n,isOpen:r,isTypingMode:i,onSwitchToTyping:a,onDeckInteract:o,onClose:s})=>{let[l,u]=(0,K.useState)(lge),[d,f]=(0,K.useState)(null),[p,m]=(0,K.useState)(!1),[h,g]=(0,K.useState)(`token`),_=(0,K.useRef)(-1),v=(0,K.useRef)(null),y=(0,K.useRef)(null),[b,x]=(0,K.useState)(null),S=(0,K.useCallback)(e=>{y.current=e,x(e)},[]),C=(0,K.useRef)(0),w=(0,K.useRef)(null),[T,E]=(0,K.useState)({height:null,offsetTop:0,keyboardOffsetBottom:0}),[D,O]=(0,K.useState)(0),k=e?.state.doc.toString()??``;(0,K.useEffect)(()=>{if(!(typeof document>`u`))return r&&e?document.documentElement.dataset.mobileEditorOpen=`true`:delete document.documentElement.dataset.mobileEditorOpen,()=>{delete document.documentElement.dataset.mobileEditorOpen}},[r,e]),(0,K.useEffect)(()=>{if(!r||!e)return;let n=!1;return Z2(t,k).then(e=>{n||u(e)}),()=>{n=!0}},[r,t,k,e]),(0,K.useEffect)(()=>{if(!r||typeof window>`u`){E({height:null,offsetTop:0,keyboardOffsetBottom:0});return}let e=window.visualViewport;if(!e){E({height:window.innerHeight,offsetTop:0,keyboardOffsetBottom:0});return}let t=0,n=()=>{t=0;let n=Math.max(0,window.innerHeight-(e.height+e.offsetTop));E(t=>t.height===e.height&&t.offsetTop===e.offsetTop&&t.keyboardOffsetBottom===n?t:{height:e.height,offsetTop:e.offsetTop,keyboardOffsetBottom:n})},i=()=>{t||=requestAnimationFrame(n)};return n(),e.addEventListener(`resize`,i),e.addEventListener(`scroll`,i),()=>{t&&cancelAnimationFrame(t),e.removeEventListener(`resize`,i),e.removeEventListener(`scroll`,i)}},[r]),(0,K.useEffect)(()=>{if(typeof document>`u`)return;if(!r||!e||!b){document.documentElement.style.removeProperty(`--mobile-editor-inset`);return}let t=()=>{let e=Math.round(b.getBoundingClientRect().height)+T.keyboardOffsetBottom;document.documentElement.style.setProperty(`--mobile-editor-inset`,`${e}px`)};t();let n=typeof ResizeObserver<`u`?new ResizeObserver(t):null;return n?.observe(b),()=>{n?.disconnect(),document.documentElement.style.removeProperty(`--mobile-editor-inset`)}},[r,e,b,T.keyboardOffsetBottom]),(0,K.useEffect)(()=>{if(!e)return;let t=e.state.doc.lineAt(e.state.selection.main.head).number;t!==_.current&&(_.current=t,f(null),g(`token`),m(!1))},[e,n]);let A=(0,K.useMemo)(()=>!e||!r?null:jhe(e.state,l,d),[e,r,l,d,n]),j=(0,K.useMemo)(()=>!e||!r?null:l4(e.state),[e,r,n]),M=(0,K.useCallback)(t=>{if(!e||!r)return;C.current&&cancelAnimationFrame(C.current),w.current!==null&&(window.clearTimeout(w.current),w.current=null);let n=()=>{T4(e,{pos:t?.pos,overlayEl:y.current,forceCenter:t?.forceCenter})};C.current=requestAnimationFrame(()=>{C.current=0,n()}),t?.followUp&&(w.current=window.setTimeout(()=>{w.current=null,n()},120))},[e,r]);(0,K.useEffect)(()=>()=>{C.current&&cancelAnimationFrame(C.current),w.current!==null&&window.clearTimeout(w.current)},[]),(0,K.useEffect)(()=>{!r||!e||M({forceCenter:!0,followUp:!0})},[r,e,i,T.keyboardOffsetBottom,T.height,h,p,M]),(0,K.useEffect)(()=>{!r||!e||M()},[r,e,n,M]);let N=(0,K.useCallback)(t=>{if(!e||!A||A.slots.length===0)return;let n=Math.max(0,Math.min(A.slots.length-1,t)),r=A.slots[n];f(n),g(`token`),m(!1),r.kind===`metric`?(e.dispatch({selection:{anchor:r.from,head:r.to}}),M({pos:r.from})):r.kind===`add-metric`?(e.dispatch({selection:{anchor:r.from,head:r.from}}),M({pos:r.from})):r.kind===`query-stage`&&O(e=>e+1)},[e,A,M]),P=(0,K.useCallback)(e=>{A&&N(A.activeSlotIndex+e)},[A,N]),F=(0,K.useCallback)((t,n)=>{if(!e||!A)return;let r=A.slots[A.activeSlotIndex];if(r){if(A.context===`workout`&&r.kind===`add-metric`){let t=e.state.doc.lineAt(e.state.selection.main.head),r=t.text.length>0&&!/\s$/.test(t.text),i=`${r?` `:``}${n.value}`,a=t.to+ +!!r,o=t.to+i.length;f(null),g(`token`),m(n.id===`add-weight`||n.id===`add-duration`),e.dispatch({changes:{from:t.to,to:t.to,insert:i},selection:{anchor:a,head:o},userEvent:`input.wheel`}),M({pos:a});return}if(A.context===`workout`){let i=n.value;(t.id===`duration-min`||t.id===`duration-sec`)&&(i=n.value);let a=r.from+i.length;e.dispatch({changes:{from:r.from,to:r.to,insert:i},selection:{anchor:r.from,head:a},userEvent:`input.wheel`}),M({pos:r.from})}}},[e,A,M]),I=(0,K.useCallback)(()=>{if(!e)return;let t=e.state.selection.main.head,n=e.state.doc.lineAt(t),r=n.text.match(/^(\s*)/),i=`\n${r?r[1]:``}`,a=n.to+i.length;f(null),g(`token`),e.dispatch({changes:{from:n.to,to:n.to,insert:i},selection:{anchor:a},userEvent:`input.wheel`}),M({pos:a})},[e,M]),ee=(0,K.useCallback)(()=>{e&&(e.contentDOM.setAttribute(`inputmode`,`text`),a(!0),e.focus())},[e,a]),L=(0,K.useCallback)(()=>{e&&(_a(e),e.contentDOM.setAttribute(`inputmode`,`none`),a(!1),e.focus())},[e,a]),R=(0,K.useCallback)(()=>{e&&_a(e),typeof document<`u`&&(delete document.documentElement.dataset.mobileEditorOpen,document.documentElement.style.removeProperty(`--mobile-editor-inset`)),e?.contentDOM.blur(),s()},[e,s]),z=(0,K.useCallback)(t=>{if(!e)return;let n=e.state.selection.main,r=n.from+(t.cursorOffset??t.insert.length);e.dispatch({changes:{from:n.from,to:n.to,insert:t.insert},selection:{anchor:r},userEvent:`input`}),e.focus(),M({pos:r}),t.triggerComplete&&queueMicrotask(()=>{va(e)})},[e,M]),B=(0,K.useCallback)(e=>{if(e.target?.closest(`[role="listbox"], input, textarea, select`)){v.current=null;return}if(e.currentTarget.scrollWidth>e.currentTarget.clientWidth+4){v.current=null;return}v.current={x:e.clientX,y:e.clientY}},[]),V=(0,K.useCallback)((e,t)=>{let n=v.current;if(v.current=null,!n)return;let r=e-n.x,i=t-n.y;Math.abs(r)>=28&&Math.abs(r)>Math.abs(i)*1.2&&P(r<0?1:-1)},[P]);if(!r||!e||!A||!j)return null;let H=A.slots[A.activeSlotIndex],U=pge(H,A.lineNumber,j.tokens),te=h===`block`||h===`add`||h===`wiki`||h===`prose-tag`?h:A.context===`query`?`query`:A.context===`markdown`?`markdown`:`token`,W=A.context===`workout`&&H?.kind===`metric`&&U!==null&&te===`token`,{height:ne,keyboardOffsetBottom:re}=T;if(i){let t=Da(e.state)===`active`?io(e.state).slice(0,18):[],n=t=>{e.dispatch({effects:Ta(t)}),ja(e),e.focus()};return(0,q.jsxs)(`div`,{ref:S,"data-testid":`mobile-typing-bar`,"data-mobile-editor-deck":`true`,onPointerDownCapture:()=>o?.(),style:{bottom:`${re}px`,...re>0?{paddingBottom:0}:{}},className:`fixed inset-x-0 z-40 flex flex-col border-t border-border bg-card text-card-foreground shadow-lg select-none overscroll-contain pb-[env(safe-area-inset-bottom,0px)]`,children:[t.length>0&&(0,q.jsx)(`div`,{role:`listbox`,"aria-label":`Autocomplete suggestions`,className:`flex min-h-[44px] items-center gap-1.5 overflow-x-auto border-b border-border bg-muted/30 px-2 py-1 scrollbar-none`,children:t.map((e,t)=>(0,q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":!1,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),className:`inline-flex h-9 min-w-[44px] shrink-0 items-center gap-1.5 rounded-full border border-border bg-background px-3 text-xs text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(`span`,{"aria-hidden":`true`,className:$(`h-1.5 w-1.5 shrink-0 rounded-full`,dge(e))}),(0,q.jsx)(`span`,{className:`font-mono font-semibold whitespace-nowrap`,children:e.displayLabel??e.label}),e.detail&&(0,q.jsx)(`span`,{className:`max-w-[96px] truncate text-[11px] text-muted-foreground`,children:e.detail})]},`${e.label}-${t}`))}),(0,q.jsxs)(`div`,{className:`flex min-h-[48px] items-center gap-1.5 overflow-x-auto overscroll-x-contain border-b border-border bg-muted/40 px-2.5 scrollbar-none`,children:[(0,q.jsxs)(`span`,{className:`shrink-0 font-mono text-[11px] font-semibold text-muted-foreground tabular-nums`,children:[`L`,A.lineNumber]}),A.slots.map((e,t)=>{let n=t===A.activeSlotIndex;return(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>{N(t),L()},className:$(`shrink-0 min-h-[44px] rounded-full border px-3 text-xs font-mono tabular-nums transition-colors cursor-pointer`,n?`border-primary bg-primary text-primary-foreground font-semibold`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:e.label},e.id)})]}),(0,q.jsxs)(`div`,{className:`flex min-h-[48px] items-center justify-between gap-1.5 px-2 py-1`,children:[(0,q.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-x-auto overscroll-x-contain scrollbar-none`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-return-wheel-btn`,onMouseDown:e=>e.preventDefault(),onClick:L,className:`inline-flex h-11 shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Deck`})]}),uge.map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-label":e.ariaLabel,onMouseDown:e=>e.preventDefault(),onClick:()=>z(e),className:`inline-flex h-11 min-w-[44px] shrink-0 items-center justify-center rounded-md border border-border bg-background px-2 font-mono text-xs font-semibold text-foreground hover:bg-muted cursor-pointer transition-colors`,children:e.label},e.label)),(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>Za(e),"aria-label":`Outdent line`,className:`inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(vee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>za(e),"aria-label":`Indent line`,className:`inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(oee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsxs)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:I,className:`inline-flex h-11 shrink-0 items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Dt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Line`})]})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-done-btn`,onMouseDown:e=>e.preventDefault(),onClick:R,className:`inline-flex h-11 shrink-0 items-center gap-1 rounded-md bg-primary px-3 text-xs font-semibold text-primary-foreground cursor-pointer`,children:[(0,q.jsx)(tt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Done`})]})]})]})}let ie={bottom:`${re}px`,...ne!==null&&re>0?{paddingBottom:0,height:`${Math.min(276,Math.max(184,Math.round(ne*.52)))}px`,minHeight:`184px`}:ne===null?{}:{maxHeight:`${Math.min(360,Math.max(252,Math.round(ne*.44)))}px`}};return(0,q.jsxs)(`section`,{ref:S,"aria-label":`Mobile workout and note thumb deck`,"data-testid":`mobile-wheel-composer`,"data-mobile-editor-deck":`true`,onPointerDownCapture:()=>o?.(),onMouseDown:e=>{e.target.tagName!==`INPUT`&&e.preventDefault()},style:ie,className:`fixed inset-x-0 bottom-0 z-40 h-[min(42svh,360px)] max-h-[380px] min-h-[252px] flex flex-col border-t border-border bg-card text-card-foreground shadow-xl select-none overscroll-contain pb-[env(safe-area-inset-bottom,0px)]`,children:[(0,q.jsxs)(`div`,{"data-testid":`mobile-wheel-slot-rail`,onPointerDown:B,onPointerUp:e=>V(e.clientX,e.clientY),className:`flex min-h-[48px] items-center gap-1.5 overflow-x-auto overscroll-x-contain border-b border-border bg-muted/40 px-2 scrollbar-none`,children:[(0,q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 pr-1`,children:[(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-prev-slot`,"aria-label":`Previous slot`,disabled:A.activeSlotIndex<=0,onClick:()=>P(-1),className:`inline-flex h-11 w-11 items-center justify-center rounded-md border border-border bg-background text-foreground disabled:opacity-35 hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(c,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-next-slot`,"aria-label":`Next slot`,disabled:A.activeSlotIndex>=A.slots.length-1,onClick:()=>P(1),className:`inline-flex h-11 w-11 items-center justify-center rounded-md border border-border bg-background text-foreground disabled:opacity-35 hover:bg-muted cursor-pointer transition-colors`,children:(0,q.jsx)(dee,{weight:`bold`,className:`h-4 w-4`})}),(0,q.jsxs)(`span`,{className:`pl-1 font-mono text-[11px] font-semibold uppercase tracking-wide text-muted-foreground tabular-nums`,children:[`L`,A.lineNumber]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[A.slots.map((e,t)=>{let n=t===A.activeSlotIndex&&h!==`block`,r=e.kind===`add-metric`;return(0,q.jsx)(`button`,{type:`button`,"data-testid":`mobile-wheel-slot-${e.kind===`add-metric`?`add`:t}`,onClick:()=>N(t),className:$(`shrink-0 min-h-[44px] rounded-full border px-3 text-xs font-mono tabular-nums transition-colors cursor-pointer`,n?`border-primary bg-primary text-primary-foreground font-semibold`:r?`border-dashed border-border bg-background text-foreground hover:bg-muted`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:e.label},e.id)}),j.lintFixes.map(t=>t.fixes.slice(0,1).map(n=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_LINT_QUICK_FIX,onClick:()=>f4(e,t,n),className:`inline-flex min-h-[44px] shrink-0 items-center gap-1 rounded-full border border-dashed border-destructive/40 bg-destructive/10 px-2.5 text-xs font-mono font-semibold text-destructive hover:bg-destructive hover:text-destructive-foreground cursor-pointer transition-colors`,children:[(0,q.jsx)(Yn,{weight:`bold`,className:`h-3.5 w-3.5 shrink-0`}),(0,q.jsxs)(`span`,{children:[`Fix: `,n]})]},`${t.id}:${n}`))),A.context===`workout`&&(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_SETTINGS_BTN,"aria-pressed":te===`block`,onClick:()=>g(e=>e===`block`?`token`:`block`),className:$(`inline-flex min-h-[44px] shrink-0 items-center gap-1 rounded-full border px-2.5 text-xs font-medium cursor-pointer transition-colors`,te===`block`?`border-primary bg-primary/15 text-primary font-semibold`:`border-border bg-background text-muted-foreground hover:text-foreground`),children:[(0,q.jsx)(Ji,{weight:`bold`,className:`h-3.5 w-3.5 shrink-0`}),(0,q.jsx)(`span`,{children:`Block`})]})]})]}),(0,q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain px-3 py-2.5`,children:A.context===`workout`&&H?.kind===`add-metric`&&te!==`block`&&te!==`add`?(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,q.jsxs)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:[`Append metric to line `,A.lineNumber]}),(0,q.jsx)(`button`,{type:`button`,onClick:()=>g(`add`),className:`inline-flex min-h-[44px] items-center rounded-md px-2.5 text-xs font-medium text-primary hover:bg-primary/10 cursor-pointer`,children:`Full Catalog`})]}),(0,q.jsx)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:(A.drums[0]?.options??[]).map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":`wheel-option-${e.id}`,onClick:()=>{A.drums[0]&&F(A.drums[0],e)},className:`flex min-h-[44px] w-full items-center justify-between gap-2 rounded-lg border border-border bg-popover px-3 py-2 text-left text-popover-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.label}),e.sublabel&&(0,q.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground tabular-nums`,children:e.sublabel})]},e.id))})]}):(0,q.jsx)(v4,{view:e,mode:te,inspection:j,token:U,scope:l,docText:k,useScrubber:p,onToggleScrubber:()=>m(e=>!e),compact:!0,showHeader:!1,showFooter:!1,showStepButtons:!1,showClose:!1,showDockButton:!1,activeQueryStageId:H?.kind===`query-stage`?H.id:void 0,queryStageRequestToken:D,onModeChange:e=>g(e),onMutate:()=>{M()}})}),(0,q.jsxs)(`div`,{className:`flex min-h-[52px] items-center justify-between gap-1.5 border-t border-border bg-muted/40 px-2.5 py-1`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>{Ua(e),e.focus()},"aria-label":`Undo last edit`,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(ct,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Undo`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_TOKEN_DELETE_BTN,disabled:!W,onClick:()=>{U&&(d4(e,U),f(null))},className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-destructive disabled:opacity-35 hover:bg-destructive/10 cursor-pointer transition-colors`,children:[(0,q.jsx)(Wr,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Delete`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-newline-btn`,onClick:I,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Dt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Line`})]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-type-btn`,onClick:ee,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground hover:bg-muted cursor-pointer transition-colors`,children:[(0,q.jsx)(Pt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Type`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`mobile-wheel-done-btn`,onClick:R,className:`inline-flex min-h-[44px] items-center gap-1 rounded-md bg-primary px-3 text-xs font-semibold text-primary-foreground cursor-pointer transition-colors`,children:[(0,q.jsx)(tt,{weight:`bold`,className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Done`})]})]})]})]})},hge=({view:e,cursorVersion:t,disabled:n=!1})=>{let[r,i]=(0,K.useState)(null);if((0,K.useEffect)(()=>{if(!e||n||e.state.readOnly){i(null);return}let t=e.state.selection.main;if(t.empty||!e.hasFocus){i(null);return}let r=uM(e.state);if(!r||r.type!==`markdown`){i(null);return}let a=e.coordsAtPos(t.from),o=e.coordsAtPos(t.to),s=e.dom.getBoundingClientRect();if(!a||!o){i(null);return}let c=(a.left+o.right)/2-s.left,l=Math.max(96,Math.min(s.width-96,c)),u=e.state.doc.lineAt(t.from),d=u.number>1&&/^#{1,6}\s/.test(e.state.doc.line(u.number-1).text),f=a.top-s.top-38,p=f<48||d?o.bottom-s.top+6:f;i({top:p,left:l})},[e,t,n]),!r||!e)return null;let a=[{id:`bold`,label:`Bold (Ctrl+B)`,Icon:yr,run:()=>{TM(e,`**`),e.focus()}},{id:`italic`,label:`Italic (Ctrl+I)`,Icon:Zr,run:()=>{TM(e,`*`),e.focus()}},{id:`strike`,label:`Strikethrough`,Icon:mr,run:()=>{TM(e,`~~`),e.focus()}},{id:`code`,label:`Inline code (Ctrl+E)`,Icon:k,run:()=>{TM(e,"`"),e.focus()}},{id:`link`,label:`Insert link (Ctrl+Shift+K)`,Icon:S,run:()=>{EM(e),e.focus()}},{id:`timer`,label:`Wrap in timer block`,Icon:nr,run:()=>{let t=e.state.selection.main;if(t.empty)return;let n=e.state.doc.sliceString(t.from,t.to),r=`\n\`\`\`time\n${n}\n\`\`\`\n`;e.dispatch({changes:{from:t.from,to:t.to,insert:r},selection:{anchor:t.from+9,head:t.from+9+n.length},userEvent:`input.format`}),e.focus()}}];return(0,q.jsx)(`div`,{role:`toolbar`,"aria-label":`Text formatting`,"data-testid":`selection-format-bar`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},style:{position:`absolute`,top:`${r.top}px`,left:`${r.left}px`,transform:`translateX(-50%)`,boxShadow:`0 2px 8px rgba(0, 0, 0, 0.04)`},className:`z-30 hidden lg:inline-flex items-center gap-0.5 px-1 py-0.5 rounded-[6px] bg-card border border-border text-foreground`,children:a.map(({id:e,label:t,Icon:n,run:r})=>(0,q.jsx)(`button`,{type:`button`,title:t,"aria-label":t,"data-testid":`format-bar-${e}`,onClick:r,className:`inline-flex items-center justify-center h-6 w-6 rounded-[4px] text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:(0,q.jsx)(n,{weight:`bold`,className:`h-3.5 w-3.5`})},e))})},gge=({open:e,layout:t=`docked-right`,view:n,mode:r,inspection:i,token:a,scope:o,docText:s,lastEditDiff:c,onClose:l,onModeChange:u,onMutate:d,onStepToken:f})=>{let[p,m]=(0,K.useState)(!0),h=HY(65),g=i.section?.type,_=g===`time`||g===`log`,v=(0,K.useMemo)(()=>!n||!_||!i.section?[]:u4(n.state,i.section),[n,_,i]);if((0,K.useEffect)(()=>{if(!e||t!==`docked-right`)return;let r=e=>{e.key===`Escape`&&typeof window<`u`&&window.innerWidth<1280&&(e.preventDefault(),e.stopPropagation(),l(),n?.focus())};return document.addEventListener(`keydown`,r,!0),()=>document.removeEventListener(`keydown`,r,!0)},[e,t,l,n]),!e)return null;let y=e=>{if(!n||e<1||e>n.state.doc.lines)return;let t=n.state.doc.line(e);n.dispatch({selection:_o.cursor(t.from),scrollIntoView:!0}),n.focus()};return(0,q.jsxs)(q.Fragment,{children:[t===`docked-right`&&(0,q.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-label":`Close inspector drawer`,onClick:l,className:`xl:hidden fixed inset-0 z-[29] bg-black/20 cursor-default`}),(0,q.jsxs)(`aside`,{role:`complementary`,"aria-label":`Focused Token Inspector Drawer`,"data-testid":Q.EDITOR_INSPECTOR_DRAWER,style:t===`docked-right`?{"--inspector-sticky-top":`${h}px`}:void 0,className:$(`flex flex-col overflow-hidden border-l border-border bg-card text-card-foreground`,t===`docked-right`?`fixed right-0 bottom-0 z-30 w-[340px] max-w-[92vw] max-xl:top-[var(--inspector-sticky-top)] max-xl:shadow-xl xl:top-0 xl:shadow-none`:`w-[340px] max-w-full shrink-0`),children:[(0,q.jsxs)(`div`,{className:`flex items-start justify-between gap-2 border-b border-border bg-muted/40 px-3 py-2.5`,children:[(0,q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,q.jsx)(`div`,{className:`flex items-center gap-1.5`,children:(0,q.jsx)(`h2`,{className:`truncate text-xs font-semibold uppercase tracking-wide text-foreground`,children:`Focused Token Inspector`})}),(0,q.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums`,children:[(0,q.jsxs)(`span`,{children:[`Ln `,i.lineNum,` · `,i.tokens.length,` token`,i.tokens.length===1?``:`s`]}),c&&(0,q.jsxs)(`span`,{"data-testid":Q.EDITOR_INSPECTOR_DIFF_BADGE,className:`inline-flex items-center rounded bg-primary/10 px-1.5 py-0.5 font-mono text-[11px] font-medium text-primary`,title:`Last change: ${c.from} -> ${c.to}`,children:[c.from,` → `,c.to]})]})]}),(0,q.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Close inspector drawer`,title:`Close Inspector Drawer (Ctrl+Alt+I / Cmd+Alt+I)`,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground cursor-pointer`,children:(0,q.jsx)(Mt,{className:`h-4 w-4`})})]}),(0,q.jsxs)(`div`,{className:`flex-1 overflow-y-auto divide-y divide-border`,children:[(0,q.jsx)(v4,{view:n,mode:r,inspection:i,token:a,scope:o,docText:s,useScrubber:p,onToggleScrubber:()=>m(e=>!e),compact:!1,showHeader:!0,showFooter:!1,showStepButtons:r===`token`,showClose:!1,showDockButton:!1,onMutate:d,onModeChange:u,onStepToken:f}),_&&v.length>0&&(0,q.jsxs)(`div`,{className:`px-3 py-2.5`,children:[(0,q.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,q.jsx)(xr,{className:`h-3.5 w-3.5`}),(0,q.jsx)(`span`,{children:`Block Runtime Preview`})]}),(0,q.jsxs)(`button`,{type:`button`,onClick:()=>u?.(`block`),className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground cursor-pointer`,children:[(0,q.jsx)(Pi,{className:`h-3 w-3`}),(0,q.jsx)(`span`,{children:`Configure`})]})]}),(0,q.jsx)(`div`,{className:`overflow-hidden rounded-lg bg-muted/35 divide-y divide-border/60`,children:v.map(e=>{let t=e.lineNum===i.lineNum;return(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.EDITOR_BLOCK_TIMELINE_ROW,onClick:()=>y(e.lineNum),className:$(`flex w-full items-center justify-between gap-2 px-2.5 py-2 text-left text-xs transition-colors cursor-pointer`,t?`bg-primary/10 text-foreground font-medium`:`text-muted-foreground hover:bg-muted/70 hover:text-foreground`),children:[(0,q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,q.jsx)(`span`,{className:`w-5 shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums`,children:e.lineNum}),(0,q.jsx)(`span`,{className:$(`truncate`,e.isRest&&`italic text-muted-foreground`),children:e.label})]}),(0,q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[e.hasError&&(0,q.jsx)(oe,{className:`h-3.5 w-3.5 text-destructive`,"aria-label":`Line has syntax warning`}),e.durationLabel&&(0,q.jsx)(`span`,{className:`rounded bg-background/80 px-1.5 py-0.5 font-mono text-[11px] text-foreground tabular-nums`,children:e.durationLabel})]})]},e.lineNum)})})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`inline-flex items-center gap-1 font-medium text-foreground`,children:(0,q.jsx)(Ve,{className:`h-3 w-3`})}),(0,q.jsx)(`span`,{children:`Ctrl+Space Typeahead`}),(0,q.jsx)(`span`,{children:`/ Blocks`}),(0,q.jsx)(`span`,{children:`Alt+. Popover`}),(0,q.jsx)(`span`,{children:`Ctrl+Alt+I / Cmd+Alt+I Drawer`}),(0,q.jsx)(`span`,{children:`Ctrl+←/→ Step`}),(0,q.jsx)(`span`,{children:`Alt+↑/↓ Value`})]})]})]})},E4=new oo,D4=new oo,O4=new oo,k4=new oo;async function A4(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 _ge(e){let t=await A4(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function vge(e){let t=await A4(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${aE()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var j4=Ga.define();function yge(){let e=PV,t=K.useContext(MV);return e?e():t??null}var M4=({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=``,ariaLabel:g=`Note editor`,onStartWorkout:_,onCompleteWorkout:v,onBlocksChange:y,onAddToPlan:b,notePersistence:x,onViewCreated:S,mode:C=`edit`,lineWrapping:w=!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:ee,placeholder:L,defaultInspectorDrawerOpen:R=!1,inspectorDrawerLayout:z=`docked-right`,autoFocus:B=!0,onPeekEntity:V,onClosePeek:H})=>{let U=(0,K.useRef)(null),te=(0,K.useRef)(null),W=(0,K.useRef)(null),ne=(0,K.useRef)(0),re=i2(),ie=(0,K.useRef)(re);ie.current=re;let[ae,oe]=(0,K.useState)(null),se=(0,K.useRef)(null),ce=(0,K.useRef)(``),le=(0,K.useRef)([]),ue=p===`dark`||p===`vs-dark`,{isDebugMode:de}=Ew(),fe=wme(se,x),[pe,me]=(0,K.useState)(null),[he,ge]=(0,K.useState)([]),[_e,ve]=(0,K.useState)(1),[ye,be]=(0,K.useState)(0),xe=F??pe,Se=zme(he,xe),[Ce,we]=(0,K.useState)(null),[Te,Ee]=(0,K.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches),[G,De]=(0,K.useState)(!1),[Oe,ke]=(0,K.useState)(!1),[Ae,je]=(0,K.useState)(R),[Me,Ne]=(0,K.useState)(!1),[Pe,Fe]=(0,K.useState)(`token`),[Ie,Le]=(0,K.useState)(null),[Re,ze]=(0,K.useState)(null),[Be,Ve]=(0,K.useState)(null),[He,Ue]=(0,K.useState)({tags:[],defaultEquipment:[],customMetricTypes:[]}),We=Ce?.state.doc.toString()??c,Ge=(0,K.useRef)(void 0);(0,K.useEffect)(()=>{if(m)return;let t=!1,n=Ge.current!==e;Ge.current=e;let r=()=>{Z2(e,We).then(e=>{t||Ue(t=>JSON.stringify(t)===JSON.stringify(e)?t:e)})};if(n)return r(),()=>{t=!0};let i=setTimeout(r,300);return()=>{t=!0,clearTimeout(i)}},[e,We,m]);let Ke=(0,K.useMemo)(()=>{let e=Ce??W.current;return e?l4(e.state):{contextKind:`markdown`,section:null,focus:null,lineNum:1,lineFrom:0,lineTo:0,lineText:``,tokens:[],lintFixes:[]}},[Ce,ye]),qe=(0,K.useMemo)(()=>{if(Ke.tokens.length===0)return null;if(Ie){let e=Ke.tokens.find(e=>e.id===Ie);if(e)return e}let e=(Ce??W.current)?.state.selection.main.head??0;return Ke.tokens.find(t=>e>=t.from&&e<=t.to)??Ke.tokens[0]??null},[Ke,Ie,Ce]),Je=(0,K.useRef)(m);Je.current=m;let Ye=(0,K.useRef)(e);Ye.current=e;let Xe=(0,K.useRef)(k);Xe.current=k;let Ze=(0,K.useRef)(ue);Ze.current=ue;let Qe=(0,K.useRef)(!1),$e=(0,K.useRef)({onChange:l,onCursorPositionChange:d,onBlur:f,onDocUpdate:u,onBlocksChange:y,onIdentityChange:r,onSaveRequest:o,onCommitChange:s});$e.current={onChange:l,onCursorPositionChange:d,onBlur:f,onDocUpdate:u,onBlocksChange:y,onIdentityChange:r,onSaveRequest:o,onCommitChange:s};let et=(0,K.useRef)(G);et.current=G;let tt=(0,K.useRef)(He);tt.current=He;let nt=(0,K.useRef)(Ae);nt.current=Ae;let rt=(0,K.useRef)(Me);rt.current=Me;let it=(0,K.useRef)(Pe);it.current=Pe;let at=(0,K.useRef)(Ie);at.current=Ie;let ot=(0,K.useRef)(Ke);ot.current=Ke;let st=(0,K.useMemo)(()=>xme({getNotebookScope:()=>tt.current,onCreateEffort:async e=>{await h2(e),W.current?.dispatch({effects:[S2.of(null)]}),be(e=>e+1)},onCreateTag:async e=>{await v2(e),W.current?.dispatch({effects:[S2.of(null)]});let t=W.current?.state.doc.toString()??``;Z2(Ye.current,t).then(e=>Ue(e)),be(e=>e+1)}}),[]),ct=(0,K.useCallback)(e=>{let t=W.current;if(!t||Je.current)return;_a(t);let n=l4(t.state),r=t.state.selection.main.head,i=e?.token??null;!i&&typeof e?.tokenIndex==`number`&&(i=n.tokens[e.tokenIndex]??null),i||=n.tokens.find(e=>r>=e.from&&r<=e.to)??n.tokens[0]??null;let a=e?.mode??(i?`token`:n.contextKind===`workout`?`add`:n.contextKind),o=e?.anchorRect??null;if(!o&&n.contextKind===`query`&&n.section){let e=n.section;try{let n=t.domAtPos(e.from),r=n.node instanceof Element?n.node:n.node.parentElement,i=r?.closest(`.cm-query-block-preview, .cm-widget-block-preview`)??r?.querySelector(`.cm-query-block-preview, .cm-widget-block-preview`)??null;if(i){let e=i.getBoundingClientRect();e.width>0&&e.height>0&&(o=e)}if(!o){let n=t.dom.querySelectorAll(`.cm-query-block-preview, .cm-widget-block-preview`);for(let r of n)try{let n=t.posAtDOM(r);if(n>=e.from&&n<=e.to){let e=r.getBoundingClientRect();if(e.width>0&&e.height>0){o=e;break}}}catch{}}}catch{}}if(!o)try{let e=t.coordsAtPos(i?.from??r);e&&(e.right>e.left||e.bottom>e.top)&&(o={left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:Math.max(24,e.right-e.left),height:Math.max(20,e.bottom-e.top),x:e.left,y:e.top,toJSON:()=>({})})}catch{o=null}Fe(a),Le(i?.id??null),ze(o),Ne(!nt.current)},[]),lt=(0,K.useRef)(ct);lt.current=ct;let ut=(0,K.useRef)(()=>({drawerOpen:nt.current,popoverOpen:rt.current,mode:it.current,contextKind:ot.current.contextKind,lineNum:ot.current.lineNum,selectedTokenId:at.current,tokens:ot.current.tokens.map(e=>({id:e.id,kind:e.kind,raw:e.raw,from:e.from,to:e.to})),lintFixes:ot.current.lintFixes.map(e=>({id:e.id,raw:e.raw,fixes:e.fixes}))}));(0,K.useEffect)(()=>{if(m||Te)return;let e=e=>{if(e.defaultPrevented)return;let t=U.current,n=document.activeElement;if(!t||!n||!t.contains(n))return;let r=(e.ctrlKey||e.metaKey)&&e.altKey&&!e.shiftKey&&(e.key.toLowerCase()===`i`||e.code===`KeyI`),i=e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&(e.key===`.`||e.code===`Period`);r?(e.preventDefault(),e.stopPropagation(),Dt.current()):i&&(e.preventDefault(),e.stopPropagation(),lt.current())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[m,Te]);let dt=yge(),ft=dt?.dispatch,pt=!!dt?.navState?.rightDrawerOpen,mt=dt?.peekTarget??null,ht=V??dt?.openPeek,gt=H??dt?.closePeek,_t=(0,K.useRef)(!1),vt=(0,K.useRef)(null),yt=(0,K.useRef)(mt);yt.current=mt;let bt=(0,K.useRef)({onPeekEntity:ht,onClosePeek:gt});bt.current={onPeekEntity:ht,onClosePeek:gt};let xt=(0,K.useCallback)(e=>{nt.current&&(_t.current=!0),je(!1),Ne(!1),yt.current=e,vt.current=e,bt.current.onPeekEntity?.(e)},[]),St=(0,K.useCallback)(()=>{yt.current=null,vt.current=null,bt.current.onClosePeek?.()},[]),Ct=(0,K.useCallback)(()=>{W.current&&_a(W.current),Ne(!1),St(),je(!0)},[St]),wt=(0,K.useCallback)(()=>{let e=!nt.current;e&&(W.current&&_a(W.current),Ne(!1),St()),je(e)},[St]),Tt=(0,K.useRef)(xt);Tt.current=xt;let Et=(0,K.useRef)(St);Et.current=St;let Dt=(0,K.useRef)(wt);Dt.current=wt;let Ot=!m&&!Te&&Ae,kt=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(ft&&Ot!==kt.current){if(kt.current=Ot,!Ot&&(_t.current||yt.current!==null)){_t.current=!1;return}_t.current=!1,ft({type:`SET_INSPECTOR_DRAWER`,open:Ot})}},[ft,Ot]),(0,K.useEffect)(()=>{mt&&(nt.current&&(_t.current=!0),je(!1),Ne(!1))},[mt]),(0,K.useEffect)(()=>()=>{kt.current&&(kt.current=!1,!_t.current&&yt.current===null&&ft?.({type:`SET_INSPECTOR_DRAWER`,open:!1}))},[ft]),(0,K.useEffect)(()=>{pt&&je(!1)},[pt]),(0,K.useEffect)(()=>K$(()=>{let e=W.current;e&&e.dispatch({effects:[S2.of(null),UM.of(null)]}),be(e=>e+1)}),[]),(0,K.useEffect)(()=>{let e=requestAnimationFrame(()=>{W.current?.requestMeasure(),be(e=>e+1)});return()=>cancelAnimationFrame(e)},[Ae]),(0,K.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: 1023px)`),t=e=>{Ee(e.matches),e.matches?(Ne(!1),je(!1)):(De(!1),ke(!1))};return Ee(e.matches),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[At,jt]=(0,K.useState)(null),[Mt,Nt]=(0,K.useState)(null),[Pt,Ft]=(0,K.useState)(!1),It=(0,K.useRef)(null),Lt=(0,K.useRef)(!1),Rt=(0,K.useRef)(n??0);(0,K.useEffect)(()=>{Rt.current=n??0},[n]);let[zt,Bt]=(0,K.useState)(null),Vt=(0,K.useRef)(null),Ht=(0,K.useCallback)(async(t,n=!1)=>{let r=W.current;if(!(!r||Lt.current)){Lt.current=!0,Bt(null);try{let o=await a?.();typeof o==`number`&&(Rt.current=o);let s=r.state.field(cM),c=await Yz({noteId:e??Br(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:Rt.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,Br(),e?void 0:`playground`,fe,{deferPersist:!0});It.current=c,Vt.current=null,Rt.current=c.note.sourceRevision,r.dispatch({effects:nM.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),Ft(n),jt(c.block),Nt(c.session.id)}catch(e){Bt(e instanceof Error?e.message:String(e))}finally{Lt.current=!1}}},[e,fe,i,a]),Ut=(0,K.useCallback)(()=>{jt(null),Nt(null),Ft(!1)},[]),Wt=(0,K.useCallback)(e=>{M&&Ht(e,!0)},[M,Ht]);(0,K.useEffect)(()=>_X({noteId:e,readonly:!!m,sourceRevision:n,getValue:()=>W.current?.state.doc.toString()??c,getView:()=>W.current,getBlocks:()=>{let e=W.current;return e?e.state.field(cM).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>F4(t,e.state)).filter(e=>e!==null):[]},applyEdit:async(e,t=!1)=>{if(m)throw Error(`Editor is in read-only mode. Clone this Note before editing.`);let n=W.current;if(!n){l(e),t&&await(o??s)?.();return}let r=n.state.doc.length;n.dispatch({changes:{from:0,to:r,insert:e}}),l(e),t&&await(o??s)?.()},undoEdit:()=>{let e=W.current;if(!e||m)return!1;let t=Ua(e);return t&&l(e.state.doc.toString()),t},startLiveWorkout:async(e,t=!0)=>{let n=W.current;if(!n)return{started:!1,error:`Editor view is not mounted.`};let r=n.state.field(cM).sections.filter(e=>e.type===`time`||e.type===`log`).map(e=>F4(e,n.state)).filter(e=>e!==null),i=e?r.find(t=>t.id===e):r[0];return i?(await Ht(i,t),{started:!0,blockId:i.id}):{started:!1,error:e?`Workout block '${e}' not found in editor.`:"No runnable ```time workout block found in editor."}},getInspectorState:()=>ut.current(),setInspectorDrawer:e=>{e&&(Ne(!1),Et.current()),je(e)},openTokenInspector:e=>{lt.current({mode:e?.mode,tokenIndex:e?.tokenIndex})},closeTokenInspector:()=>{Ne(!1)},...ht?{peekEntity:e=>Tt.current(e),closePeek:()=>Et.current()}:{}}),[e,m,n,c,l,o,s,Ht,ht]),(0,K.useEffect)(()=>{if(ht)return GX({getTarget:()=>yt.current??vt.current,openPeek:e=>Tt.current(e),closePeek:()=>Et.current()})},[ht]);let Gt=(0,K.useRef)(null),Kt=(0,K.useCallback)((e,t)=>{let n=Gt.current,r=n!==null&&n.results===t,i=It.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(Vt.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&W.current){let t=W.current,n=YN(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[mo.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(Gt.current={results:t,resultId:a,runBlock:o});let s;try{s=gR(fe).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,blockVersion:i.revision.version,blockContentId:i.session.blockContentId,blockContent:i.block.content,...i.block.dialect?{blockDialect:i.block.dialect}:{},...i.block.sport?{blockSport:i.block.sport}:{},...i.session.origin?{origin:i.session.origin}:{},...i.session.scheduleItemId?{scheduleItemId:i.session.scheduleItemId}:{},...i.session.sessionDate?{sessionDate:i.session.sessionDate}:{},data:t,createdAt:t.endTime}).then(()=>v?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{Gt.current?.results===t&&(Gt.current=null),Vt.current=a},()=>{}),s},[l,v,fe]),qt=(0,K.useMemo)(()=>{if(j)return[];if(A&&A.length>0)return A;let e=[];return M?e.push({id:`run`,label:`Run`,icon:(0,q.jsx)(Er,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:Ht}):_&&e.push({id:`run`,label:`Run`,icon:(0,q.jsx)(Er,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:_}),e.push({id:`playground`,label:`Playground`,icon:(0,q.jsx)(wi,{className:`h-3 w-3`}),splitIcon:(0,q.jsx)(Gi,{className:`h-3 w-3`}),splitSuccessIcon:(0,q.jsx)(zr,{className:`h-3 w-3`}),onClick:e=>{_ge(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await vge(e.content);await navigator.clipboard.writeText(t)}}),b&&e.push({id:`plan`,label:`Plan`,icon:(0,q.jsx)(ti,{className:`h-3 w-3`}),onClick:b}),e},[A,_,b,M,j,Ht]),Jt=(0,K.useMemo)(()=>ho({codeLanguages:kle}),[]),Yt=(0,K.useMemo)(()=>{let e=Math.max(1,n),r=P?[...P.keys()]:Ns;if(t&&Object.keys(t).length>0)try{return Hs(c,t,e,{registeredWidgets:r}),t}catch{return Vs(c,{sourceRevision:e,blocks:t,registeredWidgets:r})}return Vs(c,{sourceRevision:e,registeredWidgets:r})},[c,t,n,P]),Xt=(0,K.useMemo)(()=>[...T?[Ha(),Gee()]:[],Bee(),so(),Ra(),ka(),...w?[mo.lineWrapping]:[],qa.allowMultipleSelections.of(!0),ma(),qee(),Ja(),Wee(),Rse,yse,no.of([...Ma,...to,...fo,...lo,...$a,...ga,...Uee,vo,{key:`Mod-s`,run:()=>($e.current.onSaveRequest?.(),!0)},{key:`Alt-.`,run:()=>!Je.current&&(lt.current(),!0)},{key:`Mod-Alt-i`,run:()=>!Je.current&&(Dt.current(),!0)}]),mle,cM,eM.of({blocks:Yt,sourceRevision:Math.max(1,n),rawContent:c}),tM.of(P?[...P.keys()]:Ns),cse,WM.of(D),GM.of(de),...E||!D?[mce]:[],...E?[ese,Gse,Yse,Tme(e),fme(),vme(),Uce,Rce(),$ce]:[],...O?[dse]:[],go({parent:document.body}),Vse,tj,Dse,Ese,DM.of(xge),DM.of(bge),OM.of(st),...k?[hle]:[],NM,Yj.of(null),Zj.of(e=>{if(/^(https?:|mailto:|tel:)/i.test(e)){window.open(e,`_blank`,`noopener,noreferrer`);return}if(bt.current.onPeekEntity){let t=R4(e);if(t){Tt.current(t);return}}if(e.startsWith(`/`)&&typeof window<`u`){window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`));return}typeof window<`u`&&window.location.assign(e)}),ise,Mme,...nle,tse,...P&&P.size>0?[Ole(P)]:[],vse({executor:sJ,onResultSaved:mR,readOnly:m,onCaptureRpe:m?void 0:async(e,t)=>{await gB(e,t)},onEditMetric:m?void 0:async(e,t)=>{if(await mB({resultId:e,occurrence:t.occurrence,metric:{type:t.metric.type,value:t.metric.value,image:t.metric.image}})===`not-found`)throw Error(`Result segment not found in storage.`)},onOpenResults:e=>{let t=AH(e.resultId);ie.current?ie.current(t):typeof window<`u`&&window.location.assign(t)},onAddToDashboard:e=>{oe(e)},noteHref:e=>TG(`blockContentId`in e||`dataType`in e?oG(e):eG(e))}),Eme(e,fe),mo.domEventHandlers({click:(e,t)=>{if(e.button!==0||!bt.current.onPeekEntity)return!1;let n=e.target instanceof Element?e.target:null;if(!n)return!1;let r=n.closest(`.cm-frontmatter-preview a[href]`);if(r){let t=r.getAttribute(`href`);if(t){let n=R4(t);if(n)return e.preventDefault(),e.stopPropagation(),Tt.current(n),!0}}let i=e.ctrlKey||e.metaKey;if(!Je.current&&!i)return!1;let a=t.posAtCoords({x:e.clientX,y:e.clientY});if(a===null)try{let e=t.posAtDOM(n);Number.isFinite(e)&&(a=e)}catch{a=null}if(a===null)return!1;let o=Sge(t.state,a);return o?(e.preventDefault(),e.stopPropagation(),Tt.current(o),!0):!1},focus:(e,t)=>{if(typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches&&!m){let e=uM(t.state),n=e?.type===`time`||e?.type===`log`||e?.type===`query`;t.contentDOM.setAttribute(`inputmode`,n?`none`:`text`),De(!0),ke(!n)}return!1},blur:(e,t)=>{let n=e.relatedTarget;(!n||!n.closest(`.cm-tooltip`))&&_a(t);let r=!!(n&&te.current?.contains(n)),i=!!(n?.closest(`[data-mobile-editor-deck="true"]`)||!n&&Date.now()<ne.current);return!r&&!i&&(De(!1),ke(!1)),$e.current.onBlur?.(),!1}}),mo.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(cM);$e.current.onIdentityChange?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision});let n=e.transactions.every(e=>e.annotation(j4)===!0);n||(le.current.push(t.rawContent),$e.current.onChange(t.rawContent)),$e.current.onDocUpdate?.(e),I4(e.state,$e.current.onBlocksChange,ce),n||e.transactions.some(e=>e.isUserEvent(`input`)&&!e.isUserEvent(`input.wheel`)&&!e.isUserEvent(`input.format`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||Promise.resolve($e.current.onCommitChange?.()).catch(()=>{})}let t=Da(e.startState),n=Da(e.state),r=t!==n||ro(e.startState)!==ro(e.state);if(t!==`active`&&n===`active`&&Ne(!1),!e.selectionSet&&!e.docChanged&&r&&be(e=>e+1),e.selectionSet||e.docChanged){if(be(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Da(e.startState)!==null&&Da(e.state)===null&&P4(e.state,e.state.selection.main.head)?.value===``)queueMicrotask(()=>{e.view.state===e.state&&va(e.view)});else if(e.docChanged&&e.transactions.some(e=>e.isUserEvent(`input.type`))&&Da(e.state)===null){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),r=n.text.slice(0,t-n.from),i=uM(e.state),a=i?.type===`time`||i?.type===`log`,o=/(\[\[|\[:)$/.test(r),s=/(?:^|\s)#$/.test(r)&&(a||!/^\s*#$/.test(r));(o||s)&&queueMicrotask(()=>{e.view.state===e.state&&va(e.view)})}let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);$e.current.onCursorPositionChange?.(n.number,t-n.from+1);let r=uM(e.state);if(me(r?.id??null),ve(n.number),Xe.current){let{sections:t}=e.state.field(cM);ge(t)}if(e.selectionSet&&Zt.current&&!Je.current&&e.transactions.some(e=>e.isUserEvent(`select.pointer`))){let t=uM(e.startState),n=t?.type===`time`||t?.type===`log`||t?.type===`query`,i=r?.type===`time`||r?.type===`log`||r?.type===`query`;n!==i&&(e.view.contentDOM.setAttribute(`inputmode`,i?`none`:`text`),ke(!i))}}}),qa.readOnly.of(m),mo.editable.of(!m),...L?[uo(L)]:[],mo.contentAttributes.of({"aria-label":g})],[m,T,w,E,D,de,O,k,e,fe,P,L,g]);(0,K.useEffect)(()=>{let e=te.current;if(!e)return;let t;try{t=qa.create({doc:c,extensions:[...Xt,E4.of(Gj(Ze.current)),D4.of(Jt),O4.of([]),k4.of([mo.contentAttributes.of({inputmode:Te&&!Oe?`none`:`text`}),jM.of(Te&&G&&Oe&&!m)]),...N??[]]})}catch(e){console.error(`NoteEditor: Failed to initialize EditorState, recovering with safe fallback`,e),t=qa.create({doc:c,extensions:[E4.of(Gj(ue)),D4.of(Jt)]})}let n=new mo({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{if(et.current)return;let e=!i||i.scale<=1.05,t=!i||i.height<window.innerHeight;n.hasFocus&&e&&t&&(Zt.current?T4(n,{forceCenter:!0}):n.dispatch({effects:mo.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})}))})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),W.current=n,we(n),e.__codemirrorView=n,S?.(n);let{sections:s}=n.state.field(cM);ge(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;ve(l);let u=uM(n.state);me(u?.id??null);let d=n.state.field(cM);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),I4(n.state,y,ce),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,Qe.current=!1,we(null),n.destroy()}},[]),(0,K.useEffect)(()=>{let e=W.current;if(!e)return;let r=e.state.field(cM),i=le.current;if(c===r.rawContent){i.length=0,t&&n!==r.sourceRevision&&e.dispatch({effects:nM.of({blocks:t,sourceRevision:Math.max(1,n)})});return}let a=i.indexOf(c);if(a!==-1){i.splice(0,a+1);return}i.length=0;let o=Math.max(1,n),s=t?Vs(c,{sourceRevision:o,blocks:t,registeredWidgets:P?[...P.keys()]:Ns}):void 0,l=s&&t&&Object.keys(s).length===Object.keys(t).length&&Object.entries(t).every(([e,t])=>{let n=s[e];return n&&n.from===t.from&&n.to===t.to&&n.kind===t.kind&&n.dialect===t.dialect&&n.sport===t.sport});e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},annotations:j4.of(!0),...l?{effects:rM.of({rawContent:c,blocks:t,sourceRevision:o})}:{}})},[c,t,n]),(0,K.useEffect)(()=>{W.current&&W.current.dispatch({effects:E4.reconfigure(Gj(ue))})},[ue]);let Zt=(0,K.useRef)(Te);Zt.current=Te;let Qt=(0,K.useRef)(Oe);Qt.current=Oe,(0,K.useEffect)(()=>{if(!Te||!G||m||typeof document>`u`)return;let e=e=>{let t=e.target;t&&(te.current?.contains(t)||t.closest(`[data-mobile-editor-deck="true"], .cm-tooltip`)||(De(!1),ke(!1)))};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[Te,G,m]),(0,K.useEffect)(()=>{if(!W.current)return;if(!Qe.current){Qe.current=!0;return}let e=[];W.current.dispatch({effects:[eo.reconfigure.of([...Xt,E4.of(Gj(Ze.current)),D4.of(Jt),O4.of(e),k4.of([mo.contentAttributes.of({inputmode:Zt.current&&!Qt.current?`none`:`text`}),jM.of(Zt.current&&et.current&&Qt.current&&!Je.current)]),...N??[]])]})},[Xt,N,C,Jt]),(0,K.useEffect)(()=>{W.current&&W.current.dispatch({effects:k4.reconfigure([mo.contentAttributes.of({inputmode:Te&&!Oe?`none`:`text`}),jM.of(Te&&G&&Oe&&!m)])})},[Te,G,Oe,m]),(0,K.useEffect)(()=>{if(!B)return;let e=typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1023px)`).matches;!m&&!e&&W.current?.focus()},[m,B]),(0,K.useEffect)(()=>{if(I&&W.current){let e=W.current,t=e.state.doc.toString().split(`
|
|
869
869
|
`),n,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:[mo.scrollIntoView(t,{y:`start`,yMargin:20})]})}}},[I]);let $t=t=>{if(!D&&t.sectionType===`frontmatter`)return null;if(t.sectionType===`time`||t.sectionType===`log`)return(0,q.jsx)(ihe,{noteId:e,sectionId:t.sectionId,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,cursorLine:_e,docVersion:t.docVersion,commands:qt,extendedResults:ee,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(cM),n=e.find(e=>e.id===t.sectionId);return(0,q.jsx)(Ume,{sectionId:t.sectionId,section:n,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,docVersion:t.docVersion})}return t.sectionType===`widget`&&t.widgetName?(0,q.jsx)(ahe,{sectionId:t.sectionId,widgetName:t.widgetName,view:t.view,registry:P??new Map,docVersion:t.docVersion}):(0,q.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,q.jsx)(`div`,{className:`font-medium text-foreground`,children:t.sectionType})})},en=(0,K.useCallback)(e=>{let t=Ke.tokens;if(t.length===0)return;let n=qe?.id,r=t.findIndex(e=>e.id===n),i=t[((r>=0?r:0)+e+t.length)%t.length];if(!i)return;Le(i.id);let a=W.current;a&&a.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0})},[Ke.tokens,qe]),tn=(0,K.useCallback)(e=>{e&&Ve(e),be(e=>e+1)},[]),nn=Ce??W.current,rn=!Te&&!m;return(0,q.jsxs)(q.Fragment,{children:[e&&!At?(0,q.jsx)(W0,{noteId:e}):null,(0,q.jsxs)(`div`,{ref:U,className:rn&&z===`inline`&&Ae?`flex w-full min-w-0 items-stretch`:`contents`,children:[(0,q.jsxs)(`div`,{ref:te,"data-mobile-editing":Te&&G&&!m?`true`:void 0,onBlur:e=>{if(!Te||!G)return;let t=e.relatedTarget;t&&te.current?.contains(t)||!t&&Date.now()<ne.current||(De(!1),ke(!1))},className:`cm-note-editor relative w-full min-w-0 flex-1 ${h}`,children:[k&&(0,q.jsx)(Fme,{view:nn,widths:Se.widths,activeSectionId:xe,renderSlot:$t,cursorLine:_e}),zt&&(0,q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[`Workout not started. `,zt,` Your draft is kept.`]}),!k&&qt.length>0&&(0,q.jsx)(vhe,{view:nn,commands:qt}),!m&&!Te&&(0,q.jsx)(hge,{view:nn,cursorVersion:ye}),(0,q.jsx)(nge,{view:nn,cursorVersion:ye,noteId:e,hidden:Te&&G,activeTokenId:qe?.id??null,drawerOpen:Ae,onPeekEntity:ht?xt:void 0,onClosePeek:gt?St:void 0,onOpenInspector:e=>{nn&&_a(nn),Fe(e.mode),Le(e.token?.id??null),ze(e.anchorRect),Ne(!Ae)},onToggleDrawer:wt}),rn&&Me&&!Ae&&(0,q.jsx)(x4,{open:Me,anchorRect:Re,editorDom:nn?.dom??null,view:nn,mode:Pe,inspection:Ke,token:qe,scope:He,docText:We,onClose:()=>Ne(!1),onMutate:e=>tn(e),onModeChange:Fe,onStepToken:en,onDockDrawer:Ct}),Te&&!m&&(0,q.jsx)(mge,{view:nn,noteId:e,cursorVersion:ye,isOpen:G,isTypingMode:Oe,onSwitchToTyping:ke,onDeckInteract:()=>{ne.current=Date.now()+300},onClose:()=>{De(!1),ke(!1)}}),At&&W.current&&(0,q.jsx)(z2,{block:At,view:nn,onClose:Ut,onCompleteWorkout:Kt,resultId:Mt??void 0,noteId:e,autoStart:Pt}),(0,q.jsx)(yhe,{sections:he,isRuntimeActive:At!==null,editorState:nn?.state??null,onSelectBlock:Wt})]}),rn&&Ae&&(0,q.jsx)(gge,{open:Ae,layout:z,view:nn,mode:Pe,inspection:Ke,token:qe,scope:He,docText:We,lastEditDiff:Be,onClose:()=>je(!1),onModeChange:Fe,onMutate:e=>tn(e),onStepToken:en})]}),(0,q.jsx)(o2,{open:ae!==null,onOpenChange:e=>{e||oe(null)},context:ae})]})},bge=Sme(),xge=async e=>{if(!N4(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=P4(e.state,e.pos);if(!n&&!r)return null;let[i,a]=await Promise.all([X.getAllTagTypes().catch(()=>[]),X.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)&&N4(r,n)};if(!r)return null;let{propertyKey:o,from:s}=r,c={effort:`effort`,"metrics.effort":`effort`,"metrics.equipment":`equipment`,equipment:`equipment`}[o.toLowerCase()];if(c){let e=await d2();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=P4(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}}let l=o.toLowerCase(),u=i.find(e=>e.name.toLowerCase()===l),d=u?a.filter(e=>e.type?.toLowerCase()===u.name.toLowerCase()):[];return u&&d.length>0?{from:s,options:d.map(e=>({label:e.label,detail:u.label,type:`constant`})),validFor:(e,t,n,r)=>{let i=P4(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}:l===`discipline`?{from:s,options:yd.map(e=>({label:e,detail:`Discipline`,type:`constant`})),validFor:(e,t,n,r)=>{let i=P4(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}:l===`intensity`||l===`intensitytier`?{from:s,options:[`low`,`moderate`,`high`].map(e=>({label:e,detail:`Intensity`,type:`constant`})),validFor:(e,t,n,r)=>{let i=P4(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}:null};function N4(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 P4(e,t){if(!N4(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 F4(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=nu({tags:Sz()}).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(cM).noteBlocks[e.id]?.version??1,createdAt:Date.now(),widgetIds:{}}}function I4(e,t,n){if(!t)return;let r=e.field(cM).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>F4(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 L4(e){try{return decodeURIComponent(e)}catch{return e}}function R4(e){if(!e.startsWith(`/`))return null;let t=(e.split(/[?#]/,1)[0]??``).split(`/`).filter(Boolean);if(t.length===0)return null;let[n,r,i]=t;return n===`effort`&&r&&r!==`new`&&t.length===2?{kind:`effort`,slug:L4(r)}:n===`equipment`&&r&&r!==`new`&&t.length===2?{kind:`equipment`,slug:L4(r)}:n===`t`&&r&&i&&t.length===3?{kind:`tag`,tagType:L4(r),label:L4(i)}:(n===`note`||n===`notes`)&&r&&t.length===2?{kind:`note`,noteId:L4(r)}:n===`notebook`&&r&&t.length===2?{kind:`notebook`,slug:L4(r)}:n===`day`&&r&&/^\d{4}-\d{2}-\d{2}$/.test(r)&&t.length===2?{kind:`day`,date:r}:null}function Sge(e,t){let n=Math.max(0,Math.min(t,e.doc.length)),r=e.doc.lineAt(n),{sections:i}=e.field(cM),a=i.find(e=>(e.type===`time`||e.type===`log`)&&r.number>e.startLine&&r.number<e.endLine&&e.contentFrom!==void 0&&e.contentTo!==void 0);if(a&&a.contentFrom!==void 0&&a.contentTo!==void 0){let t=e.doc.sliceString(a.contentFrom,a.contentTo);if(t.trim())try{let i=u2(),o=Sz(),s=nu(i?{references:i,defaults:f2(e.doc.toString()),tags:o}:{tags:o}).read(t,a.sport).statements??[],c=r.number-a.startLine;for(let t of s){if(t.meta?.line!==c)continue;let r=Array.from(t.metrics);for(let o of r){let r=t.metricMeta?.get(o);if(!r)continue;let s=a.contentFrom+r.startOffset,c=a.contentFrom+r.endOffset;if(n<s||n>c)continue;let l=as(o.metadata);if(l?.slug)return{kind:`tag`,label:l.slug};if(o.type===Y.Custom&&typeof o.value==`string`&&/^#[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(o.value.trim()))return{kind:`unrecognized`,term:o.value.trim()};let u=Xo(o.metadata);if(u){if(u.diagnostics&&u.diagnostics.length>0){let t=u.diagnostics[0]?.token?.trim()||e.doc.sliceString(s,c).trim();if(t)return{kind:`unrecognized`,term:t}}if(u.refs&&u.refs.length>0){let e=o.type===Y.Equipment?`equipment`:`effort`,t=u.refs.find(t=>t.kind===e)??u.refs[0];if(t)return{kind:t.kind,slug:t.slug,label:t.label}}}if(o.type===Y.Effort||o.type===Y.Equipment){let t=e.doc.sliceString(s,c).trim();if(t){let e=o.type===Y.Equipment?`equipment`:`effort`;if(i){let n=e===`equipment`?i.resolveEquipment(t):i.resolveEffort(t);return n?{kind:e,slug:n.slug,label:n.label}:{kind:`unrecognized`,term:t}}return{kind:e,slug:af(t)||t,label:t}}}}}}catch{}}let o=n-r.from;if(!/^\s*#{1,6}\s/.test(r.text)){let e=/(?:^|[\s(])(#[a-zA-Z][a-zA-Z0-9_-]*)\b/g,t;for(;(t=e.exec(r.text))!==null;){let e=t[1],n=t.index+t[0].length-e.length,r=n+e.length;if(o>=n&&o<=r){let t=e.slice(1);return Sz().resolve(t)?{kind:`tag`,label:t}:{kind:`unrecognized`,term:e}}}}let s=/\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g,c;for(;(c=s.exec(r.text))!==null;){let e=c.index,t=e+c[0].length;if(o>=e&&o<=t){let e=c[1].trim(),t=c[2]?.trim()||e;return R4(e)||{kind:`note`,noteId:e,title:t}}}return null}function z4({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,K.useRef)([]),E=(0,K.useCallback)(e=>{T.current=e,a?.(e)},[a]),D=(0,K.useCallback)(()=>{v?.onRun(n,T.current[0]??null)},[v,n]),O=(0,K.useMemo)(()=>!v||!m?m:m.filter(e=>e.id!==`run`&&e.id!==`play`),[v,m]),k=!!h||!!v&&(!O||O.length===0),A=(0,q.jsxs)(q.Fragment,{children:[y,v&&(0,q.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,q.jsx)(Er,{size:11,fill:`currentColor`}),v.label??`Run`]})]});return(0,q.jsx)(r2,{title:e,subtitle:t,onReset:_,headerActions:A,className:S,children:(0,q.jsxs)(`div`,{className:`flex h-full flex-col min-h-0`,children:[b,(0,q.jsxs)(`div`,{ref:w,className:$(`relative flex-1 min-h-0`,C),children:[(0,q.jsx)(M4,{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:O,hideDefaultCommands:k,onViewCreated:g,autoFocus:!1,className:`h-full`}),x]})]})})}function Cge({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,q.jsx)(`div`,{className:`h-full`,style:{opacity:t,transition:`opacity 180ms ease`},children:(0,q.jsx)(z4,{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,q.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,q.jsx)(`span`,{children:`Try editing this example ↓`}),e===n?null:(0,q.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 B4(e,t){return e>=640&&e>=t?`split`:`stack`}function wge(e,t){let n=(0,K.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:B4(t,n)}},[e]),[r,i]=(0,K.useState)(n);return(0,K.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:B4(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 V4=e=>Math.max(0,Math.min(1,e)),H4=(e,t,n)=>e+(t-e)*n,U4=e=>1-(1-e)**2;function Tge(e,t){return e===``||t===e}var W4={id:``,range:[0,1]};function G4(e,t){if(!t||t.length===0)return{index:-1,stage:W4,t:0,ring:null};let n=V4(e),r=t.map(e=>({...e,start:V4(Math.min(e.range[0],e.range[1])),end:V4(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]??W4,o=(a.end??1)-(a.start??0),s=o>0?V4((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 Ege(e,t,n){let r=t-n;return{progress:r>0?V4(-e/r):0,reached:e<=0,inView:e<n&&e+t>0}}function Dge(e,t){let n=t/2;for(let t of e)if(t.top<=n&&t.bottom>n)return t.id;return null}var K4=(0,K.createContext)(null);function q4(){return(0,K.useContext)(K4)}function Oge({children:e}){let t=(0,K.useRef)(new Map),n=(0,K.useRef)(new Map),r=(0,K.useRef)(null),i=(0,K.useRef)(0),[a,o]=(0,K.useState)(null),s=(0,K.useRef)(null),c=(0,K.useCallback)(e=>{r.current?.gateId===e&&(r.current=null,o(null))},[]),l=(0,K.useCallback)((e,t)=>{r.current={gateId:e,segmentId:t},o(e)},[]),u=(0,K.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=typeof document<`u`&&document.documentElement.dataset.mobileEditorOpen===`true`,d=Dge(l,e);if(d!==s.current){s.current=d;let e=r.current;e&&e.segmentId!==d&&!u&&(r.current=null,o(null))}u||n.current.forEach((t,n)=>{let r=a.get(n);if(!r||r.height-e<=0)return;let i=Ege(r.top,r.height,e);t.onMeasure({slice:G4(i.progress,t.getStages()),progress:i.progress,reached:i.reached})})},[]),d=(0,K.useCallback)(()=>{i.current||=requestAnimationFrame(u)},[u]);(0,K.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,K.useCallback)((e,n)=>(t.current.set(e,n),d(),()=>{t.current.delete(e)}),[d]),p=(0,K.useCallback)((e,t)=>(n.current.set(e,t),d(),()=>{n.current.delete(e)}),[d]),m=(0,K.useCallback)(()=>u(),[u]),h=(0,K.useMemo)(()=>({registerAnchor:f,registerDriver:p,resync:m,capturedGateId:a,captureGate:l,releaseGate:c}),[f,p,m,a,l,c]);return(0,q.jsx)(K4.Provider,{value:h,children:e})}function kge(e,t){let n=q4()?.registerAnchor;(0,K.useEffect)(()=>{if(n)return n(e,()=>t.current)},[n,e,t])}function J4({gateId:e,segmentId:t,className:n,children:r}){let i=q4(),a=(0,K.useRef)(null),[o,s]=(0,K.useState)(!1);if((0,K.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,q.jsx)(`div`,{className:n,children:r});let c=i.capturedGateId===e?`captured`:`yield`;return(0,q.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)&&typeof document<`u`&&document.documentElement.dataset.mobileEditorOpen===`true`||(!(t.relatedTarget instanceof Node)||!t.currentTarget.contains(t.relatedTarget))&&i.releaseGate(e)},children:[(0,q.jsx)(`div`,{ref:a,className:`relative min-h-0 flex-1`,children:r}),(o||c===`captured`)&&(0,q.jsx)(`button`,{type:`button`,className:`mt-2 inline-flex min-h-9 max-lg:min-h-11 items-center gap-1.5 self-end rounded-full border border-border/80 bg-card px-3 py-1.5 font-mono text-[11px] font-medium text-muted-foreground shadow-xs transition-colors hover:border-foreground/25 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`,"aria-label":`${c===`captured`?`Scroll page`:`Scroll panel`}: ${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 Y4({trackRef:e,height:t,stages:n,activeIndex:r,pane:i,captions:a,status:o,segmentId:s,testId:c,className:l}){let u=HY(65),[d,f]=(0,K.useState)(null),p=wge(u,d).mode===`split`,m={status:o,pips:(0,q.jsx)(`div`,{className:`flex items-center gap-1.5`,"aria-hidden":`true`,children:n.map((e,t)=>{let n=r===t;return(0,q.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,q.jsx)(`section`,{ref:e,"data-testid":c,className:l?`relative ${l}`:`relative`,style:{height:t},children:(0,q.jsx)(n2.Provider,{value:m,children:(0,q.jsx)(`div`,{className:`sticky flex flex-col overflow-hidden`,style:{top:u,height:`calc(100dvh - ${u}px)`},children:(0,q.jsxs)(`div`,{ref:f,className:`mx-auto flex min-h-0 w-full max-w-[1500px] 2xl:max-w-[1720px] flex-1 px-3 pt-3 pb-4 sm:px-5 sm:pb-5 lg:px-10 lg:pt-3 xl:px-16 xl:pb-8 2xl:pb-10 ${p?`flex-row items-stretch gap-[clamp(20px,2.5vw,56px)] xl:gap-12 2xl:gap-16`:`flex-col gap-3 sm:gap-5 xl:gap-8`}`,children:[(0,q.jsx)(`div`,{className:p?`relative min-h-0 min-w-0 flex-[3_1_0%]`:`relative min-h-0 min-w-0 flex-1`,children:i}),(0,q.jsx)(`div`,{className:p?`flex min-h-0 min-w-0 flex-[2_1_0%] flex-col`:`flex min-h-0 min-w-0 flex-1 flex-col`,children:s?(0,q.jsx)(J4,{gateId:`${s}-captions`,segmentId:s,className:`relative min-h-0 flex-1`,children:a}):(0,q.jsx)(`div`,{className:`relative min-h-0 flex-1`,children:a})})]})})})})}function Age(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 jge(e,t,n=`smooth`){let r=Age(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 X4(e,t,n,r){let[i,a]=(0,K.useState)(()=>G4(0,n)),[o,s]=(0,K.useState)(!1),c=(0,K.useRef)(0),l=(0,K.useRef)(i),u=(0,K.useRef)(new Set),d=(0,K.useRef)(0),f=(0,K.useRef)(t);f.current=t;let p=q4(),m=p?.registerDriver,h=(0,K.useRef)(p);h.current=p;let g=(0,K.useId)(),_=r??g,v=(0,K.useRef)(n);v.current=n;let y=(0,K.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,K.useCallback)(()=>{if(d.current=0,f.current||typeof document<`u`&&document.documentElement.dataset.mobileEditorOpen===`true`)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(G4(i,v.current),i)},[e,y]),x=(0,K.useCallback)(()=>{if(h.current){h.current.resync();return}b()},[b]),S=(0,K.useCallback)(()=>{d.current||=requestAnimationFrame(x)},[x]);(0,K.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,K.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,K.useCallback)(e=>(u.current.add(e),e(l.current,c.current),()=>{u.current.delete(e)}),[]),w=(0,K.useCallback)(()=>{x()},[x]);return{slice:i,progress:c.current,runwayReached:o,subscribe:C,resync:w}}var Z4={reference:!0},Mge={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`]],"metrics-summaries":[[`frontmatter-metrics`,`tag-summaries`,`stacking-overrides`],[`querying-summaries`,`dependency-diagnostics`,`try-it`]]};function Q4(e,t){let n=e.filter(e=>!Z4[e.id]),r=e.filter(e=>Z4[e.id]);if(n.length===0)return{groups:[],tail:r};let i=t?Mge[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 Nge(e){let t=Math.max(1,e.length);return e.map((e,n)=>({id:e.id,range:[n/t,(n+1)/t]}))}var Pge=[{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, notebook workouts, and dated entries`,eyebrow:`Library`,title:`Browse Journal and Notebook notes in one Library.`,caption:`Your dated journal notes and preloaded notebook benchmarks live in one unified surface. Search, filter by source, or clone to today’s note.`},{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 Fge({slides:e=Pge,className:t}){let n=(0,K.useRef)(null),[r,i]=(0,K.useState)(0);(0,K.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,q.jsxs)(`div`,{className:$(`relative w-full`,t),children:[(0,q.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,q.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,q.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,q.jsx)(`img`,{src:t.src,alt:t.alt,loading:n===0?`eager`:`lazy`,className:`h-full w-full object-cover`})}),(0,q.jsxs)(`div`,{className:`flex w-full flex-col gap-2 sm:w-1/2 sm:gap-3`,children:[(0,q.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-[0.24em] text-primary/80`,children:t.eyebrow}),(0,q.jsx)(`h3`,{className:`text-2xl font-black tracking-[-0.04em] text-foreground sm:text-3xl`,children:t.title}),(0,q.jsx)(`p`,{className:`text-sm leading-7 text-muted-foreground sm:text-base`,children:t.caption}),(0,q.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground`,children:[(0,q.jsxs)(`span`,{className:`text-primary`,children:[`Step `,n+1]}),(0,q.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,q.jsx)(`span`,{children:e.length})]})]})]},t.src))}),(0,q.jsx)(`div`,{className:`mt-4 flex items-center justify-center gap-2`,children:e.map((e,t)=>(0,q.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Go to slide ${t+1}: ${e.title}`,"aria-current":t===r?`true`:`false`,className:$(`h-2 rounded-full transition-all`,t===r?`w-8 bg-primary`:`w-2 bg-border hover:bg-muted-foreground/40`)},e.src))})]})}var $4=`wodwiki:text-filter-navigation`,e3=({paramName:e=`q`,placeholder:t=`Search…`,autoFocus:n=!1,className:r,navigationScope:i,inputTestId:a})=>{let[o,s]=V(e,{defaultValue:``}),c=i??e,l=(0,K.useRef)(null);return(0,K.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,q.jsxs)(`div`,{className:$(`flex items-center gap-3 px-6 lg:px-10 pb-3`,r),children:[(0,q.jsx)(hi,{className:`size-5 text-muted-foreground shrink-0`}),(0,q.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($4,{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,q.jsx)(`button`,{onClick:()=>s(``),"aria-label":`Clear`,className:`text-muted-foreground hover:text-foreground transition-colors text-lg leading-none`,children:`×`})]})};function Ige(e){let t=[],n=!1;for(let r of e){if(r.trim()===`---`){n=!n;continue}n||t.push(r)}return t}function Lge(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 Rge(e){return new Date(e).toISOString().slice(0,10)}function zge(e,t){let n=t.trim().toLowerCase();return!n||e.name.toLowerCase().includes(n)||e.content.toLowerCase().includes(n)||e.date!==void 0&&Rge(e.date).includes(n)}function Bge(e){if(!e)return null;let t=Ige(cc(e).split(`
|
|
870
870
|
`)).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```"))[0];return t?Lge(t):null}var t3=({category:e,workoutItems:t,onSelect:n,showSearch:r=!0,variant:i=`card`,className:a,navigationScope:o=`q`,getItemActions:s})=>{let[c]=V(`q`,{defaultValue:``}),[l,u]=(0,K.useState)(0),[d,f]=(0,K.useState)(0),p=(0,K.useRef)([]),m=(0,K.useMemo)(()=>t.filter(t=>t.category===e&&t.name.toLowerCase()!==`readme`).filter(e=>zge(e,c)),[t,e,c]),h=(0,K.useMemo)(()=>m.map(e=>({item:e,preview:Bge(e.content),actions:s?.(e)??[{id:`open`,label:`Open`,onSelect:n}]})),[m,s,n]);return(0,K.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,K.useEffect)(()=>{p.current=[]},[h]),(0,K.useEffect)(()=>{u(0),f(0)},[c]),(0,K.useEffect)(()=>{(p.current[l]?.[d])?.scrollIntoView({block:`nearest`,inline:`nearest`})},[d,l]),(0,K.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($4,e),()=>{window.removeEventListener($4,e)}},[h,o,d,l]),(0,q.jsxs)(`div`,{className:$(`flex flex-col`,i===`card`&&`rounded-3xl border border-border bg-card overflow-hidden shadow-2xl shadow-black/5`,a),children:[r?(0,q.jsx)(`div`,{className:`border-b border-border/60 bg-background/95 backdrop-blur-md`,children:(0,q.jsx)(e3,{placeholder:`Filter collection workouts…`,className:`pt-3`,navigationScope:o})}):null,h.length===0?(0,q.jsx)(`div`,{className:`px-6 py-10 text-sm font-medium text-muted-foreground`,children:`No workouts found.`}):(0,q.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,q.jsx)(`div`,{role:`option`,"aria-selected":n,className:$(`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,q.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:$(`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,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`flex-shrink-0 size-10 rounded-xl bg-muted flex items-center justify-center transition-colors`,children:(0,q.jsx)(ci,{className:`size-4 text-primary`})}),(0,q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,q.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate uppercase tracking-tight`,children:e.item.displayName??e.item.name}),e.preview?(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground font-medium truncate mt-1`,children:e.preview}):null]}),e.item.date===void 0?null:(0,q.jsx)(`span`,{className:`shrink-0 self-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:Mw(new Date(e.item.date))}),(0,q.jsx)(ee,{className:`size-4 text-muted-foreground shrink-0 transition-opacity`})]}):r.label},r.id)})},e.item.id)})})]})};function n3(){return(0,K.useEffect)(()=>{Yq().catch(e=>console.warn(`[queryService] page source population failed`,e))},[]),(0,K.useSyncExternalStore)(Qq,Zq)}function r3(e,t){let n=e.find(e=>e.key===t&&!e.negate);return n&&n.values.length===1?n.values[0].value:null}function Vge(e){let t=e.trim();if(!t.startsWith(`:`))return null;let n=XU(t),r=Xg(n);if(r.error||!Fg(r))return null;let i=`?q=${encodeURIComponent(n)}`;switch(r.target){case`effort`:return`/efforts${i}`;case`session`:case`segment`:case`event`:return`/sessions${i}`;case`notebook`:{let e=r3(r.filters,`notebook`);if(e){let t=Ss(e);return`/notebook/${encodeURIComponent(t)}${i}`}return`/notebooks${i}`}case`page`:return`/pages${i}`;case`tag`:return`/tags${i}`;case`equipment`:return`/equipment${i}`;case`note`:case`block`:{let e=r3(r.filters,`notebook`);if(e){let t=Ss(e);return t===`journal`?`/journal${i}`:t===`playground`?`/playgrounds${i}`:`/notebook/${encodeURIComponent(t)}${i}`}let t=r3(r.filters,`source`);return t===`journal`?`/journal${i}`:t===`playground`?`/playgrounds${i}`:t===`feeds`||t===`notebooks`||t===`notebook`||t===`guides`?`/notes${i}`:r3(r.filters,`type`)===`dashboard`?`/dashboards${i}`:`/notes${i}`}default:return null}}function i3(e,t,n){return t?{...t,title:n?.title??t.title,description:n?.question??t.description}:uv(e,{fenceTag:Ab({type:n?.type??``,spanCols:n?.spanCols,spanFull:n?.spanFull,attributes:n?.attributes}).slice(3),adjacentTitle:n?.title?.trim()||void 0,adjacentDescription:n?.question?.trim()||void 0})}function a3(e){if(e.error)return!1;let t=hv(e).trim();if(!t)return!1;let n=U_(t);return!n.doc.degenerate&&n.doc.assignments.length>0?n.diagnostics.length===0:!Xg(t).error}function o3({open:e,...t}){return e?(0,q.jsx)(Hge,{...t}):null}function Hge({onClose:e,mode:t,initialWql:n,initialObject:r,initial:i,subsetQuery:a,destination:o,executor:s,rangeStart:c,rangeEnd:l,preferredUnit:u,tokenValues:d,onApply:f,footerExtra:p,applyLabel:m=t===`edit`?`Apply changes`:`Add widget`}){let h=t===`inspect`,[g,_]=(0,K.useState)(()=>i3(n,r,i)),[v,y]=(0,K.useState)(()=>{let e=i3(n,r,i);return{valid:a3(e),error:e.error}}),[b,x]=(0,K.useState)(!1),[S,C]=(0,K.useState)(null),w=async()=>{if(!v.valid||!f||b)return;let t=hv(g).trim();if(!(!t||!a3(g))){x(!0),C(null);try{let n=gv(g).attributes;await f({title:g.title?.trim()||void 0,question:g.description?.trim()||void 0,type:g.view===`table`&&!g.rawViewType?``:g.rawViewType??g.view,spanCols:typeof g.span==`number`?g.span:void 0,spanFull:g.span===`full`||void 0,wql:t,queryObject:g,attributes:Object.keys(n).length>0?n:void 0}),e()}catch(e){C(e instanceof Error?e.message:String(e))}finally{x(!1)}}};return(0,q.jsx)(SD,{open:!0,onClose:e,presentation:`sheet`,title:t===`inspect`?`Inspect widget`:t===`edit`?`Edit widget`:`Add widget`,description:h?`Read-only — clone the dashboard to edit this widget.`:`Dataset, calculation, visualization, preview — then apply.`,footer:h&&!p?void 0:(0,q.jsxs)(q.Fragment,{children:[p,(0,q.jsx)(`div`,{className:`flex-1`}),!h&&(0,q.jsxs)(q.Fragment,{children:[(0,q.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,q.jsx)(`button`,{type:`button`,"data-testid":`widget-composer-apply`,disabled:!v.valid||b,title:v.error,onClick:()=>void w(),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:b?`Applying…`:m})]})]}),children:(0,q.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,q.jsx)(Rj,{density:`studio`,value:g,onChange:_,readOnly:h,subsetQuery:a,destination:o,executor:s,rangeStart:c,rangeEnd:l,preferredUnit:u,tokenValues:d,onValidationChange:y}),S&&(0,q.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:S})]})})}var s3=`__new__`,c3=`__clone__:`;function l3(e){return e.open?(0,q.jsx)(Uge,{...e},e.subsetQuery??`(whole-store)`):null}function Uge({onOpenChange:e,initialQuery:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a}){let o=dt(),{items:s,loading:c}=fU(),l=HP(),u=(0,K.useMemo)(()=>l?aU(l):[],[l]),d=s.filter(e=>e.editable),f=s.filter(e=>!e.editable),[p,m]=(0,K.useState)(d[0]?.slug??s3),[h,g]=(0,K.useState)(``),[_,v]=(0,K.useState)(null),y=()=>e(!1);return(0,q.jsx)(o3,{open:!0,onClose:y,mode:`add`,initialWql:t,subsetQuery:n,executor:sJ,rangeStart:r,rangeEnd:i,preferredUnit:a,onApply:async e=>{v(null);let t={title:e.title,question:e.question,type:e.type,spanCols:e.spanCols,spanFull:e.spanFull,wql:e.wql,queryObject:e.queryObject,attributes:e.attributes};try{if(p===s3){let e=h.trim()||`New Dashboard`,n=await kU.createDashboard(e);await DU.update(n,Pb(n.rawContent,t)),sU();let{meta:r}=ac(n.rawContent),i=typeof r.slug==`string`&&r.slug.trim()?kb(r.slug):kb(e);y(),o(zH(i))}else if(p.startsWith(c3)){let e=p.slice(10),n=u.find(t=>t.slug===e);if(!n)throw Error(`Prebuilt dashboard "${e}" was not found.`);let r=await kU.cloneDashboard(e,n.rawContent);await DU.update(r,Pb(r.rawContent,t)),sU();let{meta:i}=ac(r.rawContent),a=typeof i.slug==`string`&&i.slug.trim()?kb(i.slug):e;y(),o(zH(a))}else{let e=await DU.resolve(p);await DU.update(e,Pb(e.rawContent,t)),sU(),y(),o(zH(p))}}catch(e){let t=e instanceof Error?e.message:String(e);throw v(t),e}},applyLabel:`Add to dashboard`,destination:(0,q.jsxs)(`section`,{children:[(0,q.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Destination`}),c?(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading dashboards…`}):(0,q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[d.map(e=>(0,q.jsx)(`button`,{type:`button`,"aria-pressed":p===e.slug,onClick:()=>m(e.slug),className:`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${p===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)),f.map(e=>(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.DASHBOARD_DEST_CLONE,"aria-pressed":p===`${c3}${e.slug}`,onClick:()=>m(`${c3}${e.slug}`),className:`flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${p===`${c3}${e.slug}`?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,q.jsx)(Gi,{className:`size-3`}),` Clone & add: `,e.title]},`clone-${e.slug}`)),(0,q.jsxs)(`button`,{type:`button`,"data-testid":Q.DASHBOARD_DEST_NEW,"aria-pressed":p===s3,onClick:()=>m(s3),className:`flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${p===s3?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,q.jsx)(ti,{className:`size-3`}),` New dashboard`]})]}),p===s3&&(0,q.jsx)(`input`,{type:`text`,value:h,onChange:e=>g(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`})]}),_&&(0,q.jsxs)(`p`,{role:`alert`,"data-testid":`dashboard-save-error`,className:`mt-2 text-xs text-destructive font-mono`,children:[`Could not save: `,_]})]})})}var Wge=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 Gge(e){let t=e.split(`.`).pop()?.split(`?`)[0]?.toLowerCase()??``;return Wge.has(t)}function Kge(e){return/^https?:\/\//.test(e)||e.startsWith(`//`)}function qge({queryText:e,widgetType:t,widgetError:n,attributes:r}){let i=n3(),a=Qe(),o=i2(),[s,c]=(0,K.useState)(!1),[l,u]=(0,K.useState)(null),d=/^\/dashboards?(?:\/|$)/.test(a.pathname),f=Xg(e),p=!f.error&&Fg(f)?e:null;return i?(0,q.jsxs)(`div`,{className:`my-5 not-prose`,children:[(0,q.jsx)(Vj,{query:e,widgetType:t,widgetError:n,attributes:r,executor:sJ,readOnly:!0,onOpenResults:e=>{let t=AH(e.resultId);o?o(t):typeof window<`u`&&window.location.assign(t)},onAddToDashboard:d?void 0:e=>{e?u(e):c(!0)},noteHref:e=>TG(`blockContentId`in e||`dataType`in e?oG(e):eG(e))}),(0,q.jsx)(l3,{open:s,onOpenChange:c,initialQuery:e,subsetQuery:p}),(0,q.jsx)(o2,{open:l!==null,onOpenChange:e=>{e||u(null)},context:l})]}):(0,q.jsx)(`div`,{className:`my-5 not-prose text-xs text-muted-foreground py-2`,children:`Loading…`})}function Jge(e){let{meta:t,body:n}=ac(e);return Object.keys(t).length===0&&n===e?{fields:null,body:e}:{fields:t,body:n.trim()}}var u3={table({children:e}){return(0,q.jsx)(`div`,{className:`my-6 overflow-x-auto rounded-xl border border-border`,children:(0,q.jsx)(`table`,{className:`w-full text-sm border-collapse`,children:e})})},thead({children:e}){return(0,q.jsx)(`thead`,{className:`bg-muted/50 text-left`,children:e})},tbody({children:e}){return(0,q.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e})},tr({children:e}){return(0,q.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e})},th({children:e}){return(0,q.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,q.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,q.jsxs)(`figure`,{className:`my-6`,children:[(0,q.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,q.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=Vge(e);if(r)return(0,q.jsx)(M,{to:r,className:`underline underline-offset-2 transition-colors text-primary hover:text-primary/70`,children:t})}let r=Kge(n),i=Gge(n),a=r?dme(n):n;return(0,q.jsxs)(`a`,{href:a,rel:r?`noopener noreferrer`:void 0,target:r||i?`_blank`:void 0,className:$(`underline underline-offset-2 transition-colors`,i?`text-primary font-medium`:`text-primary hover:text-primary/70`),children:[t,r&&(0,q.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`↗`}),i&&!r&&(0,q.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(`
|
|
871
871
|
`))return(0,q.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 `)||n.startsWith(`widget:`)){let t=(typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``)).trim(),r=n.replace(/^(?:query|widget)[:\s]?/,``).trim(),i=r?J_(r):void 0;return(0,q.jsx)(qge,{queryText:t,widgetType:i?.type,widgetError:i?.error,attributes:i?.attributes})}return(0,q.jsxs)(`div`,{className:`my-5 rounded-xl overflow-hidden border border-border`,children:[n&&(0,q.jsx)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-muted border-b border-border`,children:(0,q.jsx)(`span`,{className:`text-[10px] font-black tracking-widest uppercase text-muted-foreground`,children:n})}),(0,q.jsx)(`pre`,{className:`overflow-x-auto p-4 bg-muted/30`,children:(0,q.jsx)(`code`,{className:`font-mono text-sm text-foreground`,children:e})})]})},h1({children:e,id:t}){return(0,q.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,q.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,q.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,q.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,q.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,q.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,q.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,q.jsx)(`li`,{className:`leading-relaxed`,children:e})},blockquote({children:e}){return(0,q.jsx)(`blockquote`,{className:`my-5 pl-4 border-l-2 border-primary/40 text-muted-foreground italic text-sm`,children:e})},hr(){return(0,q.jsx)(`hr`,{className:`my-8 border-border/50`})},strong({children:e}){return(0,q.jsx)(`strong`,{className:`font-black text-foreground`,children:e})},em({children:e}){return(0,q.jsx)(`em`,{className:`italic text-foreground/80`,children:e})}},Yge={...u3,p({children:e}){return(0,q.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=K.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,q.jsxs)(`span`,{className:`flex flex-col select-none mt-4 w-full gap-5 sm:gap-7`,children:[(0,q.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,q.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Markdown`}),`.`]}),(0,q.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,q.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,q.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,q.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Analytics`}),`.`]})]}):(0,q.jsx)(`strong`,{className:`font-black text-foreground`,children:e})}},Xge={...u3,p({children:e}){return(0,q.jsx)(`p`,{className:`text-base lg:text-lg font-medium text-foreground/75 leading-relaxed my-4 first:mt-0`,children:e})}},Zge=[Fn];function Qge(e){return e.startsWith(`:`)?e:ki(e)}function d3(e){return e.type===`text`&&typeof e.value==`string`?e.value:(e.children??[]).map(d3).join(``)}function $ge(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu,``).replace(/ /g,`-`).replace(/-+/g,`-`)||`heading`}var e_e=()=>e=>{let t=new Map,n=e=>{if(e.tagName&&/^h[1-6]$/.test(e.tagName)){let n=$ge(d3(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 t_e({fields:e}){let t=Object.entries(e);return t.length===0?null:(0,q.jsxs)(`div`,{className:`my-6 rounded-xl border border-border bg-muted/30 overflow-hidden`,children:[(0,q.jsx)(`div`,{className:`px-4 py-2 border-b border-border bg-muted/50`,children:(0,q.jsx)(`span`,{className:`text-[10px] font-black tracking-[0.2em] uppercase text-muted-foreground`,children:`Metadata`})}),(0,q.jsx)(`dl`,{className:`divide-y divide-border/50`,children:t.map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex items-baseline gap-4 px-4 py-2`,children:[(0,q.jsx)(`dt`,{className:`text-[11px] font-semibold text-muted-foreground uppercase tracking-wide min-w-[100px] shrink-0`,children:e}),(0,q.jsx)(`dd`,{className:`text-sm text-foreground break-words`,children:Array.isArray(t)?t.join(`, `):String(t)})]},e))})]})}var n_e={default:u3,heroLead:Yge,heroBody:Xge};function f3({prose:e,className:t,variant:n=`default`}){if(!e)return null;let{fields:r,body:i}=Jge(e);return(0,q.jsxs)(`div`,{className:$(`prose-canvas`,t),children:[r&&(0,q.jsx)(t_e,{fields:r}),i&&(0,q.jsx)(si,{remarkPlugins:Zge,rehypePlugins:[e_e],urlTransform:Qge,components:n_e[n],children:i})]})}var p3=({activations:e,fullBleed:t,runState:n,deps:r})=>{if(e.length===0)return null;let i=e[0];if(NG(i)&&n){let a=e.slice(1),o=n.isReconnect?(0,q.jsxs)(`button`,{type:`button`,"aria-label":`View active workout timer`,onClick:n.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`,t&&`mx-auto`),children:[(0,q.jsx)(ni,{className:`size-3.5`,"aria-hidden":`true`}),`View`]}):(0,q.jsxs)(`button`,{type:`button`,"aria-label":i.label,onClick:n.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`,t&&`mx-auto`),children:[(()=>{let e=i.icon||Er;return(0,q.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`,"aria-hidden":`true`})})(),(0,q.jsx)(`span`,{children:i.label})]});return(0,q.jsxs)(`div`,{className:$(`flex flex-wrap items-center gap-4 mt-8`,t&&`justify-center`),children:[o,a.map((e,t)=>(0,q.jsx)(`button`,{type:`button`,"aria-label":e.label,onClick:()=>AG(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,q.jsx)(`div`,{className:$(`flex flex-wrap gap-4 mt-8`,t&&`justify-center`),children:e.map((e,t)=>(0,q.jsx)(`button`,{type:`button`,"aria-label":e.label,onClick:()=>AG(e.action,r),className:$(`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))})},r_e=({examples:e,activeIndex:t,onSelect:n})=>e.length===0?null:(0,q.jsx)(`div`,{className:`mt-6 rounded-2xl border border-border/70 bg-card/80 backdrop-blur-sm`,children:(0,q.jsxs)(gi,{"aria-label":`Workout examples`,value:String(t),onValueChange:e=>{e!==null&&n(Number(e))},className:`flex flex-wrap items-center gap-2 px-3 py-3 border-0 bg-transparent p-0`,children:[(0,q.jsx)(we,{}),e.map((e,n)=>{let r=n===t,i=e.anchor===!0&&!r,a=!!e.badge&&i;return(0,q.jsxs)(gn,{value:String(n),"aria-current":r?`true`:void 0,className:$(`relative rounded-full px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] transition-all active:scale-95`,r?`bg-primary text-primary-foreground shadow-lg shadow-primary/25`:i?`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,a?(0,q.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}-${n}`)})]})}),i_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`path`,{d:`M35 35 L65 35 L65 45 L45 45 L45 65 L35 65 Z`,fill:`url(#struct-grad)`}),(0,q.jsx)(`path`,{d:`M55 45 L65 45 L65 65 L45 65 L45 55 L55 55 Z`,fill:`url(#struct-grad)`,opacity:`0.7`})]}),m3=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`circle`,{cx:`50`,cy:`50`,r:`5`,fill:`url(#proto-grad)`}),(0,q.jsx)(`circle`,{cx:`50`,cy:`50`,r:`15`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`2`,strokeDasharray:`4 2`}),(0,q.jsx)(`circle`,{cx:`50`,cy:`50`,r:`25`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`1`,opacity:`0.5`}),(0,q.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:`25`,stroke:`url(#proto-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),a_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`complex-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#F50057`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#D500F9`,stopOpacity:1}})]})}),(0,q.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,q.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)`})]}),h3=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsxs)(`defs`,{children:[(0,q.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]}),(0,q.jsxs)(`filter`,{id:`glow`,x:`-20%`,y:`-20%`,width:`140%`,height:`140%`,children:[(0,q.jsx)(`feGaussianBlur`,{stdDeviation:`3`,result:`blur`}),(0,q.jsx)(`feComposite`,{in:`SourceGraphic`,in2:`blur`,operator:`over`})]})]}),(0,q.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,q.jsx)(`path`,{d:`M55 20 L30 55 L45 55 L40 85 L70 45 L55 45 Z`,fill:`url(#basics-grad)`,filter:`url(#glow)`})]}),o_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`text`,{x:`50`,y:`65`,fontFamily:`monospace`,fontSize:`40`,fontWeight:`bold`,fill:`url(#basics-grad)`,textAnchor:`middle`,children:`10`})]}),s_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`rect`,{x:`30`,y:`30`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,q.jsx)(`rect`,{x:`30`,y:`45`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,q.jsx)(`rect`,{x:`30`,y:`60`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`})]}),c_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,q.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,q.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`})]}),l_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,q.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,q.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,q.jsx)(`text`,{x:`50`,y:`30`,fontFamily:`monospace`,fontSize:`12`,fill:`url(#struct-grad)`,textAnchor:`middle`,children:`21-15-9`})]}),u_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`path`,{d:`M35 35 H65 V55 L50 70 L35 55 Z`,fill:`url(#proto-grad)`}),(0,q.jsx)(`circle`,{cx:`50`,cy:`45`,r:`4`,fill:`#0b1326`})]}),g3=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,q.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,q.jsx)(`rect`,{x:`30`,y:`60`,width:`10`,height:`15`,fill:`url(#metric-grad)`}),(0,q.jsx)(`rect`,{x:`45`,y:`40`,width:`10`,height:`35`,fill:`url(#metric-grad)`}),(0,q.jsx)(`rect`,{x:`60`,y:`25`,width:`10`,height:`50`,fill:`url(#metric-grad)`})]}),d_e=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,q.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,q.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`})]}),_3=e=>(0,q.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,q.jsx)(`defs`,{children:(0,q.jsxs)(`linearGradient`,{id:`dialect-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,q.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#76FF03`,stopOpacity:1}}),(0,q.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00E676`,stopOpacity:1}})]})}),(0,q.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,q.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 v3(e){switch(e){case`trophy`:return h3;case`dumbbell`:return ci;case`timer`:return m3;case`play`:return Er;case`blocks`:return i_e;case`puzzle`:return a_e;case`activity`:return g3;case`file-text`:return _3;default:return an}}function f_e(e){switch(e){case`basics-movement`:return h3;case`basics-reps`:return o_e;case`basics-load`:return s_e;case`structure-rounds`:case`complex-rounds`:case`protocols-rounds`:return c_e;case`structure-repscheme`:return l_e;case`protocols-timer`:case`complex-time`:return m3;case`protocols-tag`:return u_e;case`metrics-custom`:return g3;case`metrics-calc`:return d_e;case`dialects-log`:case`dialects-climb`:return _3;default:return null}}function y3({quest:e,onClick:t,className:n,compact:r=!1,disabled:i=!1}){let a=f_e(e.id),o=t?`Select to jump to its section.`:`Open the editor to begin.`,s=e.isCompleted?`Challenge complete.`:e.result?e.result.pass?`Ready — ${e.result.detail??`looks good`}`:e.result.reason??o:o,c={"data-testid":`challenge-row-${e.id}`,"data-completed":e.isCompleted?`true`:`false`,className:$(`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&&!i&&`cursor-pointer hover:bg-background/80`,i&&`opacity-60 cursor-default`,r&&`px-2.5 py-1.5`,n)},l=(0,q.jsxs)(q.Fragment,{children:[a?(0,q.jsxs)(`span`,{className:$(`relative shrink-0 mt-0.5`,r?`size-5`:`size-6`),children:[(0,q.jsx)(a,{className:`w-full h-full`}),e.isCompleted&&(0,q.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,q.jsx)(zr,{className:`size-2`,strokeWidth:3})})]}):(0,q.jsx)(`span`,{className:$(`mt-0.5 shrink-0`,e.isCompleted?`text-primary`:`text-muted-foreground/50`),"aria-hidden":`true`,children:e.isCompleted?(0,q.jsx)(kt,{className:r?`size-3.5`:`size-4`}):(0,q.jsx)(wee,{className:r?`size-3.5`:`size-4`})}),(0,q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,q.jsx)(`p`,{className:$(`font-semibold`,e.isCompleted?`text-foreground line-through decoration-primary/40`:`text-foreground`,r&&`text-xs`),children:e.label}),e.desc&&!r&&(0,q.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:e.desc}),(0,q.jsx)(`p`,{"data-testid":`challenge-hint-${e.id}`,className:$(`mt-1 text-xs`,e.isCompleted||e.result?.pass?`text-primary/80`:`text-muted-foreground`),children:s})]})]});return t?(0,q.jsx)(`button`,{type:`button`,onClick:t,disabled:i,...c,children:l}):(0,q.jsx)(`div`,{...c,children:l})}function p_e(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 b3=({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,notebookSlug:_=null,workoutItems:v=[],handleSelectWorkout:y,onScrollToSection:b,variant:x=`default`})=>{let S=!!e.isFullBleed,C=!!e.isDark&&x!==`caption`,w=e.density,T=QK[e.theme||`slate`]??QK.slate,E=e.examples??[],D=t===-1,O=K.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`?p_e(a.text.trim()):{lead:``,rest:``},c=e.proseChunks.slice(n+1);return(0,q.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,q.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,q.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,q.jsxs)(`div`,{className:`relative max-w-2xl w-full text-center`,children:[o&&(0,q.jsx)(f3,{prose:o,variant:`heroLead`,className:`mb-5`}),s&&(0,q.jsx)(f3,{prose:s,variant:`heroBody`,className:`mb-2`}),c.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,q.jsx)(f3,{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,q.jsx)(`div`,{className:`my-4 flex justify-center`,children:(0,q.jsx)(y3,{quest:n,onClick:()=>b?.(r),compact:!0})},`hero-challenge-${t}`):null}return null}),t.length>0&&(0,q.jsx)(p3,{activations:t.map((e,t)=>MG(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,q.jsxs)(`div`,{id:r,"data-section-id":i==="default"||i===`before-workouts`?e.id:void 0,className:$(`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,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:$(`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,q.jsx)(`div`,{className:$(`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,q.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,q.jsxs)(`div`,{className:$(`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,q.jsx)(`div`,{className:`mb-4 flex items-center gap-2 select-none min-h-[14px]`,children:O.quest.isCompleted?(0,q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-emerald-800 dark:text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20`,children:[(0,q.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse`}),`Challenge Complete`]}):(0,q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-muted-foreground bg-muted/60 px-2 py-0.5 rounded-full border border-border/50`,children:[(0,q.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500`}),O.chapterTitle,`: Challenge Pending`]})}),a?(0,q.jsx)(`h2`,{className:$(`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,q.jsx)(f3,{prose:n,className:t===0?`mb-6`:`mt-4 mb-6`},`prose-${t}`):null}if(e.kind===`button`)return(0,q.jsx)(p3,{activations:[MG(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,q.jsx)(`div`,{className:`my-6`,children:(0,q.jsx)(Fge,{})},`hero-carousel-${t}`);if(e.widget===`workouts-list`&&g&&_&&y)return(0,q.jsx)(`div`,{id:`notebook-workouts`,className:`border-b border-border/50 bg-card my-6`,children:(0,q.jsx)(`div`,{className:`w-full mx-auto`,children:(0,q.jsx)(t3,{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,q.jsx)(`div`,{className:`my-4`,children:(0,q.jsx)(y3,{quest:n,onClick:()=>b?.(r),compact:!0})},`challenge-${t}`):null}return null}),E.length>0?(0,q.jsx)(r_e,{examples:E,activeIndex:Math.min(p,E.length-1),onSelect:t=>f(e,t)}):null,s&&A?(0,q.jsx)(p3,{activations:e.buttons.map((e,t)=>MG(e,t)),fullBleed:S,runState:l?u:void 0,deps:d}):null]})]},`${e.id}-${i}`)};function m_e({sections:e,activeIndex:t,part:n,args:r}){let[i,a]=(0,K.useState)(null),[o,s]=(0,K.useState)(!1);return(0,K.useEffect)(()=>{if(!i){s(!1);return}i.scrollTop=0;let e=()=>{let e=i.scrollHeight-i.scrollTop-i.clientHeight;s(e>8)};e(),i.addEventListener(`scroll`,e,{passive:!0});let t=typeof ResizeObserver>`u`?void 0:new ResizeObserver(e);return t?.observe(i),()=>{i.removeEventListener(`scroll`,e),t?.disconnect()}},[i,t]),(0,q.jsxs)(`div`,{className:`relative h-full min-h-0 px-0.5`,"data-testid":`guide-captions-${n}`,children:[e.map((e,n)=>{let i=n===t;return(0,q.jsx)(`div`,{ref:i?a:void 0,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,q.jsx)(b3,{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)}),o&&i&&(0,q.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 flex justify-start lg:justify-end bg-gradient-to-t from-background via-background/85 to-transparent pt-6 pb-1 pl-1 lg:pl-0 lg:pr-1`,children:(0,q.jsxs)(`button`,{type:`button`,"data-testid":`guide-captions-more-${n}`,onClick:()=>{i.scrollBy({top:Math.max(120,Math.round(i.clientHeight*.6)),behavior:`smooth`})},className:`pointer-events-auto inline-flex min-h-11 lg:min-h-9 items-center gap-1 rounded-full border border-border bg-card/95 px-3 py-1.5 text-xs font-medium text-foreground shadow-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50`,children:[(0,q.jsx)(`span`,{children:`More below`}),(0,q.jsx)(rt,{className:`size-3.5`,"aria-hidden":`true`})]})})]})}function h_e({sections:e,part:t,partCount:n,title:r,pane:i,cardArgs:a,onActivateSection:o}){let s=(0,K.useRef)(null),c=(0,K.useMemo)(()=>Nge(e),[e]),[l,u]=(0,K.useState)(!1),{slice:d,subscribe:f,resync:p}=X4(s,l,c);(0,K.useEffect)(()=>{if(!l){let e=requestAnimationFrame(p);return()=>cancelAnimationFrame(e)}},[l,p]);let m=(0,K.useRef)(e);m.current=e;let[h,g]=(0,K.useState)(!1);(0,K.useEffect)(()=>{let e=s.current;if(!e||typeof IntersectionObserver>`u`){g(!0);return}let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(g(!0),t.disconnect())},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let _=HY(65),v=(0,K.useRef)(_);v.current=_;let y=()=>{let e=s.current;if(!e)return!1;let{top:t,bottom:n}=e.getBoundingClientRect();return t<=v.current&&n>window.innerHeight},[b,x]=(0,K.useState)(!1);(0,K.useEffect)(()=>f(()=>{let e=y();x(t=>t===e?t:e)}),[f]);let S=(0,K.useRef)(!1),C=(0,K.useRef)(-1),w=(0,K.useRef)(o);w.current=o,(0,K.useEffect)(()=>{let e=S.current,t=C.current;if(S.current=b,C.current=d.index,!b||e&&t===d.index)return;let n=m.current[d.index];n&&w.current(n)},[b,d.index]);let T=e[d.index]??null;return(0,q.jsxs)(`div`,{children:[(0,q.jsxs)(`header`,{"data-testid":`guide-runway-header-${t}`,className:`mx-auto w-full max-w-[1500px] px-4 pt-10 pb-4 sm:px-6 sm:pt-12 sm:pb-6 lg:px-12`,children:[(0,q.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[`Part `,t,` / `,n]}),(0,q.jsx)(`h2`,{className:`mt-1 text-xl font-black uppercase tracking-tight text-foreground`,children:r})]}),(0,q.jsxs)(`div`,{className:`relative`,children:[(0,q.jsx)(Y4,{trackRef:s,height:`${(e.length+1)*100}vh`,stages:c,activeIndex:d.index,pane:h?(0,q.jsx)(`div`,{className:`absolute inset-0`,onFocusCapture:()=>u(!0),onBlurCapture:e=>{let t=e.relatedTarget;t&&e.currentTarget.contains(t)||!t&&typeof document<`u`&&document.documentElement.dataset.mobileEditorOpen===`true`||u(!1)},children:i}):null,captions:(0,q.jsx)(m_e,{sections:e,activeIndex:d.index,part:t,args:a}),status:(0,q.jsxs)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[String(d.index+1).padStart(2,`0`),T?` — ${T.heading}`:``]}),testId:`guide-runway-${t}`}),e.map((t,n)=>(0,q.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} + 160px)`}},t.id))]})]})}function g_e({sections:e,groupKey:t,title:n,pane:r,cardArgs:i,onActivateSection:a}){let{groups:o,tail:s}=Q4(e,t);return(0,q.jsxs)(q.Fragment,{children:[o.map((e,t)=>(0,q.jsx)(h_e,{sections:e,part:t+1,partCount:o.length,title:n,pane:r,cardArgs:i,onActivateSection:a},e[0]?.id??t)),s.length>0&&(0,q.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] sm:px-6 lg:px-12`,"data-testid":`guide-static-tail`,children:(0,q.jsx)(`div`,{className:`lg:max-w-[50%]`,children:s.map((e,t)=>(0,q.jsx)(b3,{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 x3({videoId:e,title:t=`YouTube video`,onClose:n}){return(0,q.jsxs)(Le,{open:!0,onOpenChange:e=>{e||n()},children:[(0,q.jsx)(xt,{className:`bg-black/90`}),(0,q.jsxs)(g,{"data-testid":`youtube-lightbox`,className:`fixed inset-0 z-[100] m-0 w-screen max-w-none h-dvh max-h-none p-4 rounded-none border-0 bg-transparent shadow-none flex items-center justify-center`,onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,q.jsx)(de,{className:`sr-only`,children:t}),(0,q.jsx)(la,{"aria-label":`Close video`,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 p-0 text-foreground transition-colors hover:bg-accent`,children:(0,q.jsx)(ze,{className:`size-5`,"aria-hidden":`true`})}),(0,q.jsx)(`div`,{className:`aspect-video w-full max-w-5xl overflow-hidden rounded-lg border border-border bg-black shadow-2xl`,children:(0,q.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})})]})]})}function S3({index:e,before:t,accentText:n,after:r,accent:i,blurb:a}){return(0,q.jsx)(`header`,{className:`flex items-center px-6 py-14 lg:px-12 xl:py-20 2xl:py-24 xl:px-16`,children:(0,q.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px]`,children:[(0,q.jsxs)(`h2`,{className:`flex items-baseline gap-4 xl:gap-6 text-balance text-[clamp(26px,3.6vw,52px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[(0,q.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:e}),(0,q.jsxs)(`span`,{children:[t,n,r]})]}),(0,q.jsx)(`p`,{className:`mt-3 xl:mt-4 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-pretty text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:a})]})})}var C3=`hsl(var(--primary))`,w3={ink:`hsl(var(--foreground))`,editor:C3,timer:C3,analytics:C3,library:C3,rounds:C3},__e={editor:`WOD Editor & Autocomplete`,timer:`Clock`,analytics:`WQL Analytics`,metrics:`Own the Metrics`,result:`Run Results`},T3={start:`/page/guide-start`,protocols:`/page/guide-protocols`,structure:`/page/guide-structure`,metrics:`/page/guide-metrics`,clock:`/page/guide-clock`,wql:`/page/guide-wql`,dashboards:`/page/guide-dashboards`,sessions:`/page/guide-sessions`,basics:`/page/guide-start`,"custom-metrics":`/page/guide-metrics`,dialects:`/page/guide-sessions#intent`,complex:`/page/guide-sessions#full-session`},E3=`dQw4w9WgXcQ`,v_e=`https://i.ytimg.com/vi/${E3}/hqdefault.jpg`;function D3({variant:e=`index`}){let t=Oq(),{pathname:n}=Qe(),[r,i]=(0,K.useState)(null),a=(0,K.useMemo)(()=>GK(t).flatMap(e=>e.action?.type===`route`?[{id:e.id,label:e.label,to:e.action.to}]:[]),[t]),o=(0,K.useMemo)(()=>{let e=new Map;for(let n of t){if(n.route.startsWith(`/notebook`)||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,q.jsx)(x3,{videoId:E3,title:r.label,onClose:()=>i(null)});return e===`university`?(0,q.jsxs)(`section`,{id:`tour-section-university`,"data-testid":`tour-section-university`,"aria-label":`Wod Wiki University`,children:[(0,q.jsx)(S3,{index:`05`,before:`Wod Wiki `,accentText:`University`,after:``,accent:w3.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,q.jsx)(`nav`,{"aria-label":`Wod Wiki University`,className:`px-6 pb-16 lg:px-12 xl:px-16`,children:(0,q.jsx)(`ul`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-5`,children:a.map((e,t)=>(0,q.jsxs)(`li`,{className:$(`flex flex-col gap-5 rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/30 md:flex-row md:items-center md:gap-8 md:p-6`,t%2==1&&`md:flex-row-reverse`),children:[(0,q.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,q.jsx)(`img`,{src:v_e,alt:``,loading:`lazy`,className:`aspect-video w-full object-cover transition-transform duration-300 group-hover:scale-105`}),(0,q.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/25 transition-colors group-hover:bg-black/40`,children:(0,q.jsx)(Er,{className:`size-9 fill-white text-white`})})]}),(0,q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col items-start gap-1.5`,children:[(0,q.jsx)(M,{to:e.to,className:`inline-flex min-h-10 items-center font-semibold hover:underline`,children:e.label}),(0,q.jsx)(`p`,{className:`text-sm leading-relaxed text-muted-foreground`,children:o.get(e.id)??e.to})]})]},e.id))})}),u]}):(0,q.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,q.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col rounded-lg border border-border overflow-hidden`,children:[(0,q.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,q.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:a.map((e,t)=>(0,q.jsxs)(`li`,{className:`flex items-stretch`,children:[(0,q.jsxs)(M,{to:e.to,"aria-current":t===s?`page`:void 0,className:$(`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,q.jsxs)(`span`,{className:`flex w-full items-baseline justify-between gap-3`,children:[(0,q.jsx)(`span`,{className:`font-medium`,children:e.label}),t===l&&(0,q.jsx)(`span`,{className:`text-xs font-semibold text-primary`,"data-testid":`guide-next-marker`,children:`Next →`})]}),(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.to})]}),(0,q.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,q.jsx)(Er,{className:`size-3.5`}),`Watch`]})]},e.id))})]}),u]})}var y_e=`22rem`,b_e=`42rem`,x_e=`20rem`,S_e=`calc(100dvh - var(--canvas-sticky-top) - 2rem)`;function C_e(e){return{editorWidth:e||`50%`,editorMinWidth:y_e,editorMaxWidth:b_e,editorMinHeight:x_e,editorMaxHeight:S_e}}function O3(e){let t=Math.max(1,e.split(`
|
|
@@ -1165,7 +1165,7 @@ domain: swimming
|
|
|
1165
1165
|
`)?`
|
|
1166
1166
|
`:`
|
|
1167
1167
|
|
|
1168
|
-
`,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 p5({noteId:e,sourceRevision:t,blocks:n={},persistence:r=eR,onRevert:i}){let[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)([]),[l,u]=(0,K.useState)(``),[d,f]=(0,K.useState)(0),[p,m]=(0,K.useState)(0),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(!1);(0,K.useEffect)(()=>{if(!a)return;let t=!1;return g(null),r.getNoteBlockHistory(e).then(e=>{t||c(e.toSorted((e,t)=>e.savedAt-t.savedAt||e.version-t.version))}).catch(e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[a,e,t,r]);let y=Array.from(new Set(s.map(e=>e.blockId))).sort((e,t)=>{let r=n[e]?.from,i=n[t]?.from;return r!==void 0&&i!==void 0?r-i:r===void 0?i===void 0?0:1:-1}),b=y.includes(l)?l:y[0]??``,x=s.filter(e=>e.blockId===b).toSorted((e,t)=>e.version-t.version),S=(e,t)=>{let r=s.filter(t=>t.blockId===e).at(-1),i=r?.dialect?r.sport?`${r.dialect}:${r.sport}`:r.dialect:r?.kind,a=[`Block ${t+1}`];return i&&a.push(i),n[e]||a.push(`not in current note`),a.join(` · `)},C=x.find(e=>e.version===d)??x[0],w=x.find(e=>e.version===p)??x.at(-1),T=async()=>{if(!(!C||!i)){v(!0),g(null);try{await i(C),c(await r.getNoteBlockHistory(e))}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}};return(0,q.jsxs)(`details`,{open:a,onToggle:e=>o(e.currentTarget.open),className:`border-t border-border/50 pt-3`,children:[(0,q.jsx)(`summary`,{className:`cursor-pointer rounded-sm text-xs font-medium text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,onClick:e=>{e.preventDefault(),o(e=>!e)},children:`Saved block history`}),a&&(0,q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[h&&(0,q.jsx)(`p`,{role:`alert`,children:h}),y.length===0?(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No saved actionable blocks.`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`label`,{className:`block text-sm`,children:[`Block occurrence`,(0,q.jsx)(`select`,{className:`mt-1 block max-w-full rounded border bg-background p-2 text-foreground focus-visible:ring-2`,value:b,onChange:e=>{u(e.target.value),f(0),m(0)},children:y.map((e,t)=>(0,q.jsx)(`option`,{value:e,children:S(e,t)},e))})]}),(0,q.jsx)(`ol`,{"aria-label":`Saved versions`,className:`space-y-1 text-sm`,style:{contentVisibility:`auto`},children:x.map(e=>(0,q.jsxs)(`li`,{children:[`v`,e.version,` · `,(0,q.jsx)(`time`,{dateTime:new Date(e.savedAt).toISOString(),children:Pw(new Date(e.savedAt))}),` · `,e.kind,e.dialect?` · ${e.dialect}`:``,e.sport?` · ${e.sport}`:``]},e.version))}),(0,q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[{label:`Compare saved version`,row:C,set:f},{label:`With saved version`,row:w,set:m}].map(({label:e,row:t,set:n})=>(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsxs)(`label`,{className:`block text-sm`,children:[e,(0,q.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:x.map(e=>(0,q.jsxs)(`option`,{value:e.version,children:[`v`,e.version]},e.version))})]}),(0,q.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,q.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:C?.rawContent===w?.rawContent&&C?.kind===w?.kind&&C?.dialect===w?.dialect&&C?.sport===w?.sport?`Saved states are identical.`:`Saved states differ.`}),i&&C&&(0,q.jsx)(`button`,{type:`button`,disabled:_,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2 disabled:opacity-50`,onClick:()=>void T(),children:_?`Saving…`:`Restore v${C.version} as a new saved version`})]})]})]})}var gxe=typeof window<`u`?K.useLayoutEffect:K.useEffect;function m5(e,t){let n=e.match(/^#\s+(.+)$/m),r=n?n[1].trim():t?.title;return r?{title:r}:void 0}function h5(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=t[r],i=e[r];if(!n||i.from!==n.from||i.to!==n.to||i.kind!==n.kind||i.dialect!==n.dialect||i.sport!==n.sport)return!1}return!0}function g5({noteId:e,initialContent:t,initialBlocks:n={},initialRevision:r=0,metadata:i,noteType:a=`note`,onExternalChange:o,onSavedRecord:s}){let[c,l]=(0,K.useState)({blocks:n,sourceRevision:r}),[u,d]=(0,K.useState)(null),[f,p]=(0,K.useState)(null),m=(0,K.useRef)(c.sourceRevision),h=(0,K.useRef)({rawContent:t,blocks:c.blocks,sourceRevision:c.sourceRevision}),g=(0,K.useRef)(null),_=(0,K.useRef)(i);_.current=i;let v=(0,K.useRef)(o);v.current=o;let y=(0,K.useRef)(s);y.current=s;let b=(0,K.useRef)(null);b.current!==e&&r>0&&(b.current=e,m.current=r,h.current={rawContent:t,blocks:n,sourceRevision:r},g.current=h.current,l({blocks:n,sourceRevision:r}));let x=(0,K.useCallback)(e=>{m.current=e.sourceRevision,g.current=e;let t=h.current,n=t.rawContent===e.rawContent&&h5(t.blocks,e.blocks);l(t=>({blocks:n?e.blocks:t.blocks,sourceRevision:e.sourceRevision})),y.current?.(e)},[]),S=(0,K.useCallback)(async t=>{if(UL(e))return h.current;let n=_.current,r={...n,...m5(t.rawContent,n)},i=eR.saveNote({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:m.current,metadata:r,noteType:a});tR.set(e,i);let o=await i.finally(()=>{tR.get(e)===i&&tR.delete(e)}),s=rR()[e];s&&s.rawContent===t.rawContent&&aR(e);let c={rawContent:o.rawContent,blocks:o.blocks??{},sourceRevision:o.sourceRevision??m.current};return x(c),p(null),c},[e,a,x]),C=v$({onSave:async e=>{await S(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:e=>p(`Save failed. ${e instanceof Error?e.message:String(e)} Your draft is kept. Retry saving.`)}),w=(0,K.useCallback)(async()=>C.hasDirtyDraft()?(await C.flush(),!0):!1,[C.hasDirtyDraft,C.flush]);gxe(()=>{if(e)return tde(e,w)},[e,w]);let T=(0,K.useCallback)(t=>{if(UL(e))return;let n=m5(t.rawContent,_.current);ede({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:m.current,...n?{metadata:n}:{},noteType:a,stagedAt:Date.now()})},[e,a]);(0,K.useEffect)(()=>{let e=()=>{let e=h.current,t=g.current;e&&(t&&t.rawContent===e.rawContent&&h5(t.blocks,e.blocks)||T(e))};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[T]);let E=(0,K.useCallback)(e=>{let t=h.current.rawContent!==e.rawContent||!h5(h.current.blocks,e.blocks);h.current=e,t&&(C.onChange(e),T(e))},[C.onChange,T]),D=(0,K.useCallback)(e=>{d(null);let t=Math.max(1,m.current),n=h.current.rawContent===e?h.current.blocks:Vs(e,{sourceRevision:t,blocks:h.current.blocks,registeredWidgets:Ns});E({rawContent:e,blocks:n,sourceRevision:m.current}),v.current?.(e)},[E]),O=(0,K.useCallback)(async e=>{await C.flush();let t=h.current;if(!t)throw Error(`The note draft is unavailable.`);let n=f5({...t,sourceRevision:m.current},e),r=await S(n);h.current=r,d(n.rawContent),v.current?.(n.rawContent)},[C.flush,S]),k=(0,K.useCallback)(async(t,n)=>{p(null);try{await C.flush();let r=h.current,i=await Yz({noteId:e,rawContent:r.rawContent,blocks:r.blocks,expectedSourceRevision:m.current,metadata:_.current,noteType:a},t,n,void 0,void 0,{deferPersist:!0});return x({rawContent:i.note.rawContent,blocks:i.note.blocks,sourceRevision:i.note.sourceRevision}),i}catch(e){let t=`Workout not started. ${e instanceof Error?e.message:String(e)} Your draft is kept.`;throw p(t),e}},[C.flush,e,a,x]),A=(0,K.useCallback)(async()=>{await C.flush()},[C.flush]),j=(0,K.useCallback)(()=>{C.cancel(),h.current=g.current??h.current,aR(e)},[C.cancel,e]);return{content:u??h.current.rawContent,committedBlocks:c.blocks,committedRevision:c.sourceRevision,committedSourceRevision:(0,K.useCallback)(()=>m.current,[]),draftSnapshot:h.current,saveError:f??(C.error?`Save failed. ${C.error instanceof Error?C.error.message:String(C.error)} Your draft is kept. Retry saving.`:null),flush:A,cancel:j,onLineChange:C.onLineChange,onBlur:C.onBlur,onIdentityChange:E,onSourceMutate:D,restoreRevision:O,captureForRun:k,accept:x}}var _xe=new DR;function _5(e){let{entry:t,liveContent:n,isReadOnly:r,copied:i,deletingNote:a,onEditPageSlug:o,onAddWidget:s,onMutateContent:c,onOpenPromotion:l,onOpenPlacement:u,onCopyLink:d,onRequestDelete:f,provider:p}=e;return[...!r&&c?[{id:`add-timer`,label:`Add timer`,group:`author`,onRun:()=>c(t,E$(n))}]:[],...!r&&s?[{id:`add-widget`,label:`Add widget`,group:`author`,onRun:()=>s(t)}]:[],...!r&&o?[{id:`upgrade-to-page`,label:t.slug?`Edit page route`:`Upgrade to Page`,group:`organize`,onRun:()=>o(t)}]:[],{id:`promote-notebooks`,label:`Notebooks & Promotion`,group:`organize`,onRun:()=>l(t)},{id:`placements`,label:`Note placements`,group:`organize`,onRun:()=>u(t,`relationships`)},{id:`clone`,label:`Clone`,group:`organize`,onRun:()=>u(t,`clone`)},{id:`copy-link`,label:i?`Copied`:`Copy link`,group:`share`,onRun:()=>d(t)},{id:`export-md`,label:`Export Note (.md)`,group:`share`,onRun:()=>{sL(t,p,{format:`md`})}},{id:`export-jsonl`,label:`Export Session Data (.jsonl)`,group:`share`,onRun:()=>{sL(t,p,{format:`jsonl`})}},{id:`export-csv`,label:`Export Session Data (.csv)`,group:`share`,onRun:()=>{sL(t,p,{format:`csv`})}},...r?[]:[{id:`delete-note`,label:`Delete note`,icon:Me,group:`danger`,disabled:a,testId:`l3-delete-note`,onRun:()=>f(t)}]]}function v5(e){let{entry:t,liveContent:n,isReadOnly:r=!1,deleteRedirectTo:i=Z.journal,provider:a=_xe,onMutateContent:o,onEditPageSlug:s,onAddWidget:c,onUpdated:l,onCloned:u,onDeleted:d,onBeforeDelete:f}=e,p=dt(),[m,h]=(0,K.useState)(null),[g,_]=(0,K.useState)(!1),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(!1),[S,C]=(0,K.useState)(null),[w,T]=(0,K.useState)(null);(0,K.useEffect)(()=>{if(!v||!t){T(null);return}let e=!1;return Promise.all([CU.listForNote(t.id).catch(()=>[]),X.getSessionsForNote(t.id).catch(()=>[])]).then(([n,r])=>{e||T({schedules:n.length,sessions:r.length,notebooks:t.notebookIds?.length??+!!t.notebookId})}),()=>{e=!0}},[v,t]);let[E,D]=(0,K.useState)(!1);(0,K.useEffect)(()=>{y(!1),C(null),h(null),_(!1)},[t?.id]);let O=(0,K.useCallback)(e=>{let t=`${window.location.origin}${SH(e.id)}`;navigator.clipboard?.writeText(t).then(()=>{D(!0),window.setTimeout(()=>D(!1),1800)}).catch(()=>{})},[]),k=(0,K.useCallback)(async()=>{if(!(!t||r||b)){x(!0),C(null),Que(t.id),f?.(t.id),aR(t.id);try{await lR(t.id),await DU.delete(t.id),aR(t.id),y(!1),d?d(t.id):p(i,{replace:!0})}catch(e){HL(t.id),C(e instanceof Error?e.message:`Failed to delete note.`)}finally{x(!1)}}},[i,b,t,r,p,f,d]);return{helpfulActions:(0,K.useMemo)(()=>t?_5({entry:t,liveContent:n??t.rawContent,isReadOnly:r,copied:E,deletingNote:b,onEditPageSlug:s,onAddWidget:c,onMutateContent:o,onOpenPromotion:()=>_(!0),onOpenPlacement:(e,t)=>h(t),onCopyLink:O,onRequestDelete:()=>{C(null),y(!0)},provider:a}):[],[E,b,t,O,r,n,c,s,o,a]),placement:m,setPlacement:h,promotionOpen:g,setPromotionOpen:_,confirmDeleteOpen:v,setConfirmDeleteOpen:y,deletingNote:b,deleteError:S,copied:E,handleCopyLink:O,handleConfirmDelete:k,dialogs:t?(0,q.jsxs)(q.Fragment,{children:[m!==null&&(0,q.jsx)(mxe,{open:!0,onOpenChange:e=>{e||h(null)},entry:t,mode:m,provider:a,onSaved:e=>l?.(e),onCloned:e=>{u?u(e):p(`${SH(e.id)}?edit=1`)}}),(0,q.jsxs)(ei,{open:v,onOpenChange:e=>{b||(y(e),e||C(null))},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{"data-testid":Q.NOTE_DELETE_DIALOG,children:[(0,q.jsxs)(Do,{children:[(0,q.jsx)(oa,{children:`Delete note?`}),(0,q.jsxs)(Xi,{children:[`Permanently delete “`,t.title||`Untitled note`,`”? This cannot be undone.`,w&&(w.schedules>0||w.sessions>0||w.notebooks>0)&&(0,q.jsxs)(`span`,{className:`mt-2 block text-xs text-muted-foreground`,children:[`Removes `,w.schedules,` scheduled date`,w.schedules===1?``:`s`,` and detaches from`,` `,w.notebooks,` notebook`,w.notebooks===1?``:`s`,`. Existing`,` `,w.sessions,` logged session`,w.sessions===1?``:`s`,` and archived snapshots remain preserved.`]})]})]}),S&&(0,q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:S}),(0,q.jsxs)(Oo,{children:[(0,q.jsx)(Sr,{disabled:b,onClick:()=>C(null),"data-testid":Q.NOTE_DELETE_CANCEL,children:`Cancel`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`destructive`,disabled:b,"data-agent-confirm":`Deletes note "${t.title||`Untitled note`}" permanently`,action:()=>k(),"data-testid":Q.NOTE_DELETE_CONFIRM,children:b?`Deleting…`:`Delete forever`})]})]})]})]}):null}}function y5({noteId:e,noteTitle:t,actions:n}){let[r,i]=(0,K.useState)(!1);if(n.length===0)return null;let a=t?`Note options for ${t}`:`Note options`;return(0,q.jsx)(`div`,{onClick:e=>e.stopPropagation(),children:(0,q.jsxs)(ta,{open:r,onOpenChange:i,children:[(0,q.jsx)(A,{render:(0,q.jsx)(J,{variant:`ghost`,size:`icon`,className:`h-7 w-7 min-h-7 min-w-7 text-muted-foreground hover:text-foreground`,"aria-label":a,title:`Note options`,"data-testid":`note-card-options-${e}`}),children:(0,q.jsx)(Ln,{className:`size-4`,"aria-hidden":`true`})}),(0,q.jsx)(Ot,{align:`end`,sideOffset:6,className:`w-56`,children:n.map(t=>{let n=t.icon;return(0,q.jsxs)(Ft,{value:t.id,disabled:t.disabled,"data-testid":t.testId?`card-${t.testId}-${e}`:void 0,className:t.id===`delete-note`?`text-destructive data-highlighted:text-destructive`:void 0,onClick:()=>{i(!1),t.onRun()},children:[n&&(0,q.jsx)(n,{className:`mr-2 size-4`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:t.label})]},t.id)})})]})})}function b5(e){return(0,q.jsx)(vxe,{...e},e.entry.id)}function vxe({entry:e,onChange:t,registerRun:n,...r}){let i=g5({noteId:e.id,initialContent:e.rawContent,initialBlocks:e.blocks??{},initialRevision:e.sourceRevision??0,onExternalChange:t});return(0,K.useEffect)(()=>(n?.(async(e,t)=>i.captureForRun(e,t)),()=>n?.(null)),[n,i.captureForRun]),(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(M4,{...r,noteId:e.id,value:i.content,noteBlocks:i.committedBlocks,sourceRevision:i.committedRevision,onIdentityChange:i.onIdentityChange,onSaved:i.accept,beforeRun:async()=>(await i.flush(),i.committedSourceRevision()),onSaveRequest:i.flush,onChange:i.onSourceMutate,onBlur:i.onBlur,onCursorPositionChange:i.onLineChange,onCommitChange:i.flush}),i.saveError?(0,q.jsx)(`p`,{role:`alert`,children:i.saveError}):null,(0,q.jsx)(p5,{noteId:e.id,blocks:i.committedBlocks,sourceRevision:i.committedRevision,onRevert:i.restoreRevision})]})}function yxe({plannedEntry:e,journalDate:t,onForked:n}){let{item:r,note:i,pairedSessions:a}=e,o=r.status===`completed`||a.length>0,s=r.status===`skipped`,[c,l]=(0,K.useState)(r.notes??``),[u,d]=(0,K.useState)(r.notes??``),[f,p]=(0,K.useState)(!1),[m,h]=(0,K.useState)(!1),[g,_]=(0,K.useState)(null);(0,K.useEffect)(()=>{let e=r.notes??``;l(e),d(e)},[r.id,r.notes]);let v=c.trim()!==u.trim(),y=async()=>{h(!0),_(null),p(!1);try{let e=c.trim();await CU.updateItem(r.id,{notes:e}),d(e),l(e),p(!0)}catch(e){_(e instanceof Error?e.message:`Could not save day cue.`)}finally{h(!1)}},b=async()=>{h(!0),_(null);try{n((await i5({scheduleItemId:r.id,sourceNoteId:r.noteId,date:t,fallbackTitle:i?.title||r.fallbackTitle})).id)}catch(e){_(e instanceof Error?e.message:`Could not fork copy for this day.`)}finally{h(!1)}};return(0,q.jsxs)(`li`,{className:`space-y-2.5 rounded-md border border-border/60 bg-background px-3 py-2.5 text-xs`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsx)(M,{to:SH(r.noteId),className:`truncate font-semibold text-foreground hover:underline`,children:i?.title||r.fallbackTitle||`Untitled workout`}),r.slot&&(0,q.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[11px] font-bold uppercase text-muted-foreground`,children:r.slot}),(0,q.jsx)(`span`,{className:`rounded-full px-2 py-0.5 text-[11px] font-semibold ${o?`bg-emerald-500/15 text-emerald-800 dark:text-emerald-200`:s?`bg-muted text-muted-foreground line-through`:`bg-primary/10 text-primary`}`,children:o?`Completed`:s?`Skipped`:`Planned`})]})}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void b(),"data-testid":Q.DAY_PLAN_FORK_BTN,className:`h-7 max-lg:min-h-11 gap-1 px-2 text-[11px]`,children:[(0,q.jsx)(Pe,{className:`size-3`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Fork for this day`})]}),!s&&(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void CU.updateItem(r.id,{status:`skipped`}),className:`h-7 max-lg:min-h-11 px-2 text-[11px]`,children:`Skip`}),s&&(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void CU.updateItem(r.id,{status:`planned`}),className:`h-7 max-lg:min-h-11 px-2 text-[11px]`,children:`Restore`}),(0,q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:m,onClick:()=>void CU.removeItem(r.id),className:`h-7 max-lg:min-h-11 px-2 text-[11px] text-muted-foreground hover:text-destructive`,children:`Unschedule`})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsx)(`input`,{type:`text`,value:c,onChange:e=>{l(e.target.value),f&&p(!1)},disabled:m,placeholder:`Add day cue (keeps canonical Note unchanged)…`,"aria-label":`Day cue for ${i?.title||r.fallbackTitle||`workout`}`,"data-testid":Q.DAY_PLAN_CUE_INPUT,className:`h-8 max-lg:min-h-11 min-w-0 flex-1 rounded-md border border-input bg-card px-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m||!v,onClick:()=>void y(),"data-testid":Q.DAY_PLAN_CUE_SAVE,className:`h-8 max-lg:min-h-11 gap-1 px-2.5 text-[11px]`,children:[(0,q.jsx)(qi,{className:`size-3`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Save`})]}),f&&!v&&(0,q.jsx)(`span`,{className:`text-[11px] font-semibold text-emerald-700 dark:text-emerald-300`,children:`Saved`})]}),g&&(0,q.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:g})]})}function bxe({journalDate:e,theme:t,onViewCreated:n}){let[r,i]=(0,K.useState)(null),[a,o]=(0,K.useState)(null),[s,c]=(0,K.useState)(0);(0,K.useEffect)(()=>xU(()=>c(e=>e+1)),[]),(0,K.useEffect)(()=>mR(()=>c(e=>e+1)),[]);let[l,u]=be(),d=dt(),f=hY(),[p,m]=(0,K.useState)(!1),[h,g]=(0,K.useState)(`write`),_=(0,K.useCallback)((e=`write`)=>{g(e),m(!0)},[]),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(null),[w,T]=(0,K.useState)(null),[E,D]=(0,K.useState)(null),O=(0,K.useRef)(null);O.current=E;let k=(0,K.useRef)(null),A=(0,K.useRef)(!1),j=(0,K.useRef)(null),N=(0,K.useRef)(null),P=(0,K.useRef)(new Map),[F,I]=(0,K.useState)(null),ee=(0,K.useCallback)(async()=>{let e=O.current;if(e)return e.block;let t=j.current;if(!t||!S)throw Error(`The pending workout is unavailable.`);return t.captured?(N.current=t.captured,t.captured.block):(N.current||=t.snapshot?await Yz(t.snapshot,t.block,S,t.origin,void 0,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}):await Xz(t.noteId,t.block,S,t.origin,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}),N.current.block)},[S]),[L,R]=(0,K.useState)({}),z=(0,K.useCallback)((e,t)=>{R(n=>n[e]===t?n:{...n,[e]:t})},[]),B=(0,K.useRef)(new Map),V=(0,K.useRef)(null),[H,U]=(0,K.useState)(null),te=(0,K.useCallback)((e,t)=>{B.current.set(e,t),V.current||(V.current=t,U(t),n?.(t))},[n]),W=l.get(`note`);(0,K.useEffect)(()=>{if(!W||!r)return;let e=document.getElementById(`note-${W}`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},[W,r]);let ne=l.toString();(0,K.useEffect)(()=>{let e=new URLSearchParams(ne).get(`autoStart`);if(!e)return;let t=Dz.get(e);t&&(Dz.delete(e),j.current=t,N.current=null,k.current={runtimeId:e,block:t.block,noteId:t.noteId,captured:t.captured},A.current=!1,x(t.block),C(e),T(t.noteId),y(!0)),u(e=>(e.delete(`autoStart`),e),{replace:!0})},[ne,u]),(0,K.useEffect)(()=>{if(v)return;let t=Mz(e);t&&(D(t),j.current={block:t.block,noteId:t.noteId,captured:t.captured},N.current=t.captured??null,k.current={runtimeId:t.runtimeId,block:t.block,noteId:t.noteId,captured:t.captured},x(t.block),C(t.runtimeId),T(t.noteId),y(!0))},[e,v]);let re=(0,K.useCallback)((e,t)=>{i(n=>n?.map(n=>n.id===e&&n.rawContent!==t?{...n,rawContent:t,blocks:Vs(t,{sourceRevision:Math.max(1,n.sourceRevision??1),blocks:n.blocks,registeredWidgets:Ns})}:n)??n)},[]),ie=(0,K.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=N.current;if(!a)return Promise.reject(Error(`The saved run pin is unavailable.`));A.current=!0,Nz(a.session.id);let o=a.session.id,s=B.current.get(a.session.noteId);if(s&&!s.state.doc.toString().includes(qN(o))){let e=YN(s.state,a.session.blockId,o);e&&s.dispatch({changes:e})}return _R.record({blockId:a.session.blockId,noteId:a.session.noteId,resultId:o,data:t,createdAt:t.endTime})},[]),ae=BZ(),[oe,se]=(0,K.useState)(!1),ce=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=!1;return ce.current!==e&&(ce.current=e,i(null)),Promise.all([DU.listByDate(e),CU.getDayOverlay(e).catch(()=>null)]).then(([n,r])=>{t||(ce.current=e,i(n),o(r))}).catch(()=>{t||(ce.current=e,i([]),o(null))}),()=>{t=!0}},[e,s]),(0,K.useEffect)(()=>QX(r===null),[r]),(0,K.useEffect)(()=>{if(r!==null){se(!1);return}let e=setTimeout(()=>se(!0),3e3);return()=>clearTimeout(e)},[r]);let le=/^\d{4}-\d{2}-\d{2}$/.test(e),ue=(0,K.useMemo)(()=>{if(!le)return null;let[t,n,r]=e.split(`-`).map(Number);return{prev:pU(new Date(t,n-1,r-1)),next:pU(new Date(t,n-1,r+1))}},[e,le]),{setL3Items:de,setL3Actions:fe}=NV(),[pe,me]=(0,K.useState)({}),he=r?.map(e=>e.id).join(`|`)??``,ge=(0,K.useMemo)(()=>he?he.split(`|`):[],[he]);(0,K.useEffect)(()=>{if(ge.length===0)return;let e=!1;for(let t of ge)X.getSessionsForNote(t).then(n=>{e||me(e=>({...e,[t]:n}))}).catch(()=>{});return()=>{e=!0}},[ge]),(0,K.useEffect)(()=>mR(e=>{X.getSessionsForNote(e.noteId).then(t=>{me(n=>({...n,[e.noteId]:t}))}).catch(()=>{})}),[]);let _e=r!==null&&r.length===1?r[0]:null,ve=_e?pe[_e.id]:void 0,[ye,xe]=(0,K.useState)(null),Se=(0,K.useMemo)(()=>new DR,[]),Ce=_e??ye,we=v5({entry:Ce,isReadOnly:!1,deleteRedirectTo:bH(e),provider:Se,onMutateContent:(e,t)=>re(e.id,t),onUpdated:()=>{DU.listByDate(e).then(i).catch(()=>{})},onDeleted:e=>{xe(null),i(t=>t&&t.filter(t=>t.id!==e))}}),Te=(0,K.useCallback)(e=>_5({entry:e,liveContent:e.rawContent,isReadOnly:!1,copied:we.copied&&Ce?.id===e.id,deletingNote:we.deletingNote&&Ce?.id===e.id,onMutateContent:(e,t)=>re(e.id,t),onOpenPromotion:e=>{xe(e),we.setPromotionOpen(!0)},onOpenPlacement:(e,t)=>{xe(e),we.setPlacement(t)},onCopyLink:e=>{xe(e),we.handleCopyLink(e)},onRequestDelete:e=>{xe(e),we.setConfirmDeleteOpen(!0)},provider:Se}),[Ce?.id,Se,re,we]),Ee=(0,K.useCallback)(async(t,n,r)=>{try{let i=P.current.get(t);if(!i)throw Error(`The saved note editor is unavailable.`);let o=Br(),s=r??a?.planned.find(e=>e.item.noteId===t&&e.item.status===`planned`)?.item.id,c=await i(n,o);Dz.set(o,{noteId:t,block:c.block,captured:c,returnTo:bH(e),...s?{scheduleItemId:s}:{},sessionDate:e}),d(DH(o))}catch(e){I(e instanceof Error?e.message:String(e))}},[e,d,a]),G=(0,K.useCallback)(e=>{_e&&Ee(_e.id,e)},[_e,Ee]),De=(0,K.useMemo)(()=>_e?[{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},...we.helpfulActions]:[],[_e,_,we.helpfulActions]);s6({content:_e?.rawContent??``,scriptBlocks:_e?L[_e.id]??[]:[],onStartWorkout:G,results:ve,noteId:_e?.id,helpfulActions:De,enabled:!!_e});let Oe=(0,K.useCallback)(e=>t=>{Ee(e,t)},[Ee]),ke=(0,K.useMemo)(()=>{if(!r||r.length<=1)return[];let e=[];for(let t of r){let n=t.title||`Untitled note`,r=o6(D$(t.rawContent),L[t.id]??[],Oe(t.id),pe[t.id]);for(let i of r)e.push(...O$([{...i,id:`note-${t.id}:${i.id}`,label:`${n} · ${i.label}`}]))}return e},[r,L,pe,Oe]),Ae=r&&r.length>1?r[0]:null,je=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(Ae)return je.current=!0,de(ke),fe?.([{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},{id:`helpful-add-timer`,label:`Add timer`,group:`author`,onRun:()=>re(Ae.id,E$(Ae.rawContent))}]),()=>{je.current&&(je.current=!1,de([]),fe?.([]))}},[ke,Ae,re,_,de,fe]),FV(`notebooks`);let Ne=e6(),Pe=(0,K.useMemo)(()=>le?(0,q.jsx)(i6,{selectedDate:new Date(`${e}T12:00:00`),onDateSelect:e=>d(bH(pU(e))),entryDates:Ne}):void 0,[le,e,Ne,d]),Fe=r!==null&&r.length===0,Ie=(0,K.useRef)(!1);return(0,K.useEffect)(()=>{if(Fe)return Ie.current=!0,de([]),fe?.([{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},{id:`day-jump-today`,label:`Jump to today`,icon:Re,group:`organize`,onRun:()=>d(bH(pU(new Date)))},{id:`day-open-journal`,label:`Open Journal`,icon:Xt,group:`organize`,onRun:()=>d(`/journal`)},{id:`day-empty-notebooks`,label:`Notebooks & Promotion`,group:`organize`,disabled:!0,onRun:()=>{}},{id:`day-empty-clone`,label:`Clone`,group:`organize`,disabled:!0,onRun:()=>{}},{id:`day-copy-link`,label:`Copy day link`,icon:Gi,group:`share`,onRun:()=>{let t=typeof window<`u`?`${window.location.origin}${bH(e)}`:bH(e);navigator.clipboard?.writeText(t).catch(()=>void 0)}},{id:`day-empty-export`,label:`Export Note (.md)`,group:`share`,disabled:!0,onRun:()=>{}},{id:`day-empty-delete`,label:`Delete note`,icon:Me,group:`danger`,disabled:!0,testId:`l3-delete-note`,onRun:()=>{}}]),()=>{Ie.current&&(Ie.current=!1,de([]),fe?.([]))}},[Fe,e,d,_,fe,de]),r?W?(0,q.jsx)(at,{to:SH(W),replace:!0}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(Q3,{data:{efforts:[],related:[],backlinks:[]},up:{id:`journal`,title:`Journal`,to:`/journal`},calendar:Pe}),(0,q.jsx)(YY,{title:e,subtitle:`${r.length} ${r.length===1?`note`:`notes`}`,actions:f?(0,q.jsx)(lX,{primary:(0,q.jsxs)(J,{type:`button`,onClick:()=>_(`write`),"aria-label":`+ Add note`,title:`New note`,children:[(0,q.jsx)(ti,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`+ Add`]})}):void 0,editor:(0,q.jsxs)(`div`,{className:`flex flex-col gap-8 px-4 py-6 sm:px-6`,children:[F&&(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,F,` Your draft is kept.`]}),(0,q.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,q.jsx)(`button`,{type:`button`,onClick:()=>jde()?d(-1):d(`/journal`),className:`rounded-pill border border-border px-2 py-0.5 hover:bg-accent hover:text-foreground transition-colors`,children:`‹ Journal`}),ue&&(0,q.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,q.jsxs)(M,{to:bH(ue.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:[`‹ `,ue.prev]}),(0,q.jsx)(`span`,{className:`font-semibold text-foreground`,children:e}),(0,q.jsxs)(M,{to:bH(ue.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:[ue.next,` ›`]})]})]}),a&&(a.planned.length>0||a.adhocSessions.length>0)&&(0,q.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[a.planned.length>0&&(0,q.jsxs)(`section`,{"data-testid":Q.DAY_SCHEDULED_SECTION,"aria-label":`Scheduled workouts`,className:`rounded-lg border border-border/60 bg-muted/20 p-3.5 space-y-2.5`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-between`,children:(0,q.jsxs)(`h2`,{className:`text-xs font-bold uppercase tracking-wider text-muted-foreground`,children:[`Scheduled Plans (`,a.planned.length,`)`]})}),(0,q.jsx)(`ul`,{className:`space-y-2`,children:a.planned.map(t=>(0,q.jsx)(yxe,{plannedEntry:t,journalDate:e,onForked:e=>{c(e=>e+1),d(`${SH(e)}?edit=1`)}},t.item.id))})]}),(a.planned.some(e=>e.pairedSessions.length>0)||a.adhocSessions.length>0)&&(0,q.jsxs)(`section`,{"data-testid":Q.DAY_LOGGED_SECTION,"aria-label":`Logged sessions`,className:`rounded-lg border border-border/60 bg-muted/20 p-3.5 space-y-2.5`,children:[(0,q.jsx)(`h2`,{className:`text-xs font-bold uppercase tracking-wider text-muted-foreground`,children:`Logged Sessions`}),(0,q.jsxs)(`ul`,{className:`space-y-2`,children:[a.planned.flatMap(({item:e,note:t,pairedSessions:n})=>n.map(n=>(0,q.jsxs)(`li`,{className:`flex items-center justify-between gap-2 rounded-md border border-emerald-500/30 bg-background px-3 py-2 text-xs`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(M,{to:`/results/${encodeURIComponent(n.id)}`,className:`font-semibold text-foreground hover:underline`,children:t?.title||`Session`}),(0,q.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Paired with `,e.slot?`${e.slot} plan`:`scheduled plan`,n.noteSourceRevision?` · v${n.noteSourceRevision}`:``]})]}),typeof n.duration==`number`&&n.duration>0&&(0,q.jsx)(`span`,{className:`font-mono text-[11px] text-emerald-700 dark:text-emerald-300`,children:ps(n.duration)})]},n.id))),a.adhocSessions.map(({session:t,note:n})=>(0,q.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-md border border-sky-500/30 bg-background px-3 py-2 text-xs`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(M,{to:`/results/${encodeURIComponent(t.id)}`,className:`font-semibold text-foreground hover:underline`,children:n?.title||`Ad-hoc workout`}),(0,q.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Ad-hoc log`,t.noteSourceRevision?` · v${t.noteSourceRevision}`:``]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.planned.filter(e=>e.item.noteId===t.noteId&&e.pairedSessions.length===0).slice(0,1).map(n=>(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void CU.attributeSession({sessionId:t.id,sessionDate:e,scheduleItemId:n.item.id}),className:`h-7 px-2 text-[11px]`,children:`Pair with plan`},n.item.id)),typeof t.duration==`number`&&t.duration>0&&(0,q.jsx)(`span`,{className:`font-mono text-[11px] text-sky-700 dark:text-sky-300`,children:ps(t.duration)})]})]},t.id))]})]})]}),r.length>1&&(0,q.jsx)(`nav`,{"aria-label":`Notes on this date`,className:`flex flex-wrap gap-2`,children:r.map(e=>(0,q.jsx)(M,{to:SH(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,q.jsxs)(`div`,{className:`flex flex-col items-start gap-3 rounded-lg border border-dashed border-border p-6`,children:[(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Notes on this date yet.`}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsxs)(J,{type:`button`,size:`lg`,onClick:()=>_(`write`),children:[(0,q.jsx)(ti,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Create a note`]}),(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`lg`,onClick:()=>_(`pick`),children:[(0,q.jsx)(ci,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Pick / Log workout`]})]})]}):r.length===1?(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/40 pb-2`,children:[(0,q.jsx)(M,{to:SH(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,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(a$,{noteId:r[0].id,notebookId:r[0].notebookId,sessions:pe[r[0].id],isReadOnlyFeedNote:!1,open:we.promotionOpen&&Ce?.id===r[0].id,onOpenChange:e=>{e&&xe(r[0]),we.setPromotionOpen(e)},onCloneRequest:()=>{xe(r[0]),we.setPlacement(`clone`)},onChanged:()=>{DU.listByDate(e).then(i).catch(()=>{})}}),(0,q.jsx)(y5,{noteId:r[0].id,noteTitle:r[0].title,actions:Te(r[0])})]})]}),(0,q.jsx)(b5,{entry:r[0],registerRun:e=>{e?P.current.set(r[0].id,e):P.current.delete(r[0].id)},onChange:e=>re(r[0].id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>z(r[0].id,e),onCompleteWorkout:(e,t,n,i)=>ie(e,t,n,i,r[0].id),onViewCreated:e=>te(r[0].id,e)},r[0].id)]}):(0,q.jsx)(`div`,{className:`space-y-6`,children:r.map((n,r)=>(0,q.jsxs)(`div`,{id:`note-${n.id}`,className:`border-t border-border/60 pt-6 first:border-t-0 first:pt-0 space-y-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/40 pb-2`,children:[(0,q.jsx)(M,{to:SH(n.id),className:`text-sm font-semibold hover:underline text-foreground`,children:n.title||`Note ${r+1}`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(a$,{noteId:n.id,notebookId:n.notebookId,sessions:pe[n.id],isReadOnlyFeedNote:!1,open:we.promotionOpen&&Ce?.id===n.id,onOpenChange:e=>{e&&xe(n),we.setPromotionOpen(e)},onCloneRequest:()=>{xe(n),we.setPlacement(`clone`)},onChanged:()=>{DU.listByDate(e).then(i).catch(()=>{})}}),(0,q.jsx)(y5,{noteId:n.id,noteTitle:n.title||`Note ${r+1}`,actions:Te(n)})]})]}),(0,q.jsx)(b5,{entry:n,registerRun:e=>{e?P.current.set(n.id,e):P.current.delete(n.id)},onChange:e=>re(n.id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>z(n.id,e),onCompleteWorkout:(e,t,r,i)=>ie(e,t,r,i,n.id),onViewCreated:e=>te(n.id,e)})]},n.id))})]})}),we.dialogs,(0,q.jsx)(R$,{open:p,onOpenChange:m,defaultDate:e,defaultNoteMode:h,onCreated:t=>{DU.listByDate(e).then(i).catch(()=>{}),d(SH(t.id))}}),v&&b&&(0,q.jsx)(z2,{block:b,prepareRun:ee,onClose:()=>{y(!1),C(null),T(null),D(null),A.current=!0;let e=k.current;e&&Nz(e.runtimeId),k.current=null},resultId:S??void 0,onCompleteWorkout:(e,t)=>ie(e,t),autoStart:!0,adoptRuntime:E?.runtime??null,parkOnUnmount:!0,onPark:t=>{let n=k.current;if(!n||A.current){t.dispose();return}kz({runtimeId:n.runtimeId,block:n.block,noteId:n.noteId,captured:n.captured,runtime:t,journalDate:e})},onRuntimeReady:e=>{let t=k.current;if(!t)return;let n=Az(t.runtimeId);n&&n.runtime!==e&&n.runtime.dispose()}})]}):(0,q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`flex-1 flex flex-col items-center justify-center gap-1.5 p-8 text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`text-sm`,children:`Loading…`}),oe&&(0,q.jsx)(`span`,{className:`text-xs`,"data-testid":`journal-slow-loading-hint`,children:ae?nZ(ae):`Opening local journal index — large vaults may take a few seconds…`})]})}var xxe=()=>(0,q.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,q.jsx)(`div`,{className:`mt-0.5 flex-shrink-0 text-primary`,children:(0,q.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,"aria-hidden":`true`,children:[(0,q.jsx)(`circle`,{cx:`9`,cy:`9`,r:`8`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,q.jsx)(`path`,{d:`M9 5v4.5M9 11.5v1`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}),(0,q.jsxs)(`div`,{className:`flex-1 text-sm leading-relaxed text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Ready to try it?`}),` `,`Press the`,` `,(0,q.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,q.jsx)(`div`,{className:`pointer-events-none absolute -bottom-4 right-8 text-primary/50`,"aria-hidden":`true`,children:(0,q.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 20 20`,fill:`none`,children:[(0,q.jsx)(`path`,{d:`M3 3 L17 3 L17 17`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,q.jsx)(`path`,{d:`M11 11 L17 17 L23 11`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]});function x5({config:e,onAction:t}){return!e.headline||!e.subtitle||e.pillars.length===0?(0,q.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,q.jsx)(`code`,{children:`attention`}),` widget config.`]}):(0,q.jsxs)(`section`,{className:`p-8`,children:[(0,q.jsx)(`p`,{className:`mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:`Playground`}),(0,q.jsx)(`h1`,{className:`text-3xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-100 sm:text-4xl`,children:e.headline}),(0,q.jsx)(`p`,{className:`mt-4 max-w-3xl text-base leading-7 text-zinc-600 dark:text-zinc-300`,children:e.subtitle}),(0,q.jsx)(`div`,{className:`mt-7 grid gap-3 md:grid-cols-3`,children:e.pillars.map(e=>(0,q.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,q.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,q.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.label}),(0,q.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]},e.label))}),(0,q.jsx)(`div`,{className:`mt-7 flex flex-wrap gap-3`,children:e.actions.map(e=>(0,q.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,q.jsx)(ae,{className:`size-4`,"aria-hidden":`true`})]},`${e.action}-${e.label}`))})]})}function S5({config:e,isDarkMode:t,onRun:n}){let r=(0,K.useRef)(null),i=(0,K.useRef)(null),a=(0,K.useMemo)(()=>e.lines.map(e=>e.code).join(`
|
|
1168
|
+
`,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 p5({noteId:e,sourceRevision:t,blocks:n={},persistence:r=eR,onRevert:i}){let[a,o]=(0,K.useState)(!1),[s,c]=(0,K.useState)([]),[l,u]=(0,K.useState)(``),[d,f]=(0,K.useState)(0),[p,m]=(0,K.useState)(0),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(!1);(0,K.useEffect)(()=>{if(!a)return;let t=!1;return g(null),r.getNoteBlockHistory(e).then(e=>{t||c(e.toSorted((e,t)=>e.savedAt-t.savedAt||e.version-t.version))}).catch(e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[a,e,t,r]);let y=Array.from(new Set(s.map(e=>e.blockId))).sort((e,t)=>{let r=n[e]?.from,i=n[t]?.from;return r!==void 0&&i!==void 0?r-i:r===void 0?i===void 0?0:1:-1}),b=y.includes(l)?l:y[0]??``,x=s.filter(e=>e.blockId===b).toSorted((e,t)=>e.version-t.version),S=(e,t)=>{let r=s.filter(t=>t.blockId===e).at(-1),i=r?.dialect?r.sport?`${r.dialect}:${r.sport}`:r.dialect:r?.kind,a=[`Block ${t+1}`];return i&&a.push(i),n[e]||a.push(`not in current note`),a.join(` · `)},C=x.find(e=>e.version===d)??x[0],w=x.find(e=>e.version===p)??x.at(-1),T=async()=>{if(!(!C||!i)){v(!0),g(null);try{await i(C),c(await r.getNoteBlockHistory(e))}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}};return(0,q.jsxs)(`details`,{open:a,onToggle:e=>o(e.currentTarget.open),className:`border-t border-border/50 pt-3`,children:[(0,q.jsx)(`summary`,{className:`cursor-pointer rounded-sm text-xs font-medium text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,onClick:e=>{e.preventDefault(),o(e=>!e)},children:`Saved block history`}),a&&(0,q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[h&&(0,q.jsx)(`p`,{role:`alert`,children:h}),y.length===0?(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No saved actionable blocks.`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`label`,{className:`block text-sm`,children:[`Block occurrence`,(0,q.jsx)(`select`,{className:`mt-1 block max-w-full rounded border bg-background p-2 text-foreground focus-visible:ring-2`,value:b,onChange:e=>{u(e.target.value),f(0),m(0)},children:y.map((e,t)=>(0,q.jsx)(`option`,{value:e,children:S(e,t)},e))})]}),(0,q.jsx)(`ol`,{"aria-label":`Saved versions`,className:`space-y-1 text-sm`,style:{contentVisibility:`auto`},children:x.map(e=>(0,q.jsxs)(`li`,{children:[`v`,e.version,` · `,(0,q.jsx)(`time`,{dateTime:new Date(e.savedAt).toISOString(),children:Pw(new Date(e.savedAt))}),` · `,e.kind,e.dialect?` · ${e.dialect}`:``,e.sport?` · ${e.sport}`:``]},e.version))}),(0,q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[{label:`Compare saved version`,row:C,set:f},{label:`With saved version`,row:w,set:m}].map(({label:e,row:t,set:n})=>(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsxs)(`label`,{className:`block text-sm`,children:[e,(0,q.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:x.map(e=>(0,q.jsxs)(`option`,{value:e.version,children:[`v`,e.version]},e.version))})]}),(0,q.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,q.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:C?.rawContent===w?.rawContent&&C?.kind===w?.kind&&C?.dialect===w?.dialect&&C?.sport===w?.sport?`Saved states are identical.`:`Saved states differ.`}),i&&C&&(0,q.jsx)(`button`,{type:`button`,disabled:_,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2 disabled:opacity-50`,onClick:()=>void T(),children:_?`Saving…`:`Restore v${C.version} as a new saved version`})]})]})]})}var gxe=typeof window<`u`?K.useLayoutEffect:K.useEffect;function m5(e,t){let n=e.match(/^#\s+(.+)$/m),r=n?n[1].trim():t?.title;return r?{title:r}:void 0}function h5(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=t[r],i=e[r];if(!n||i.from!==n.from||i.to!==n.to||i.kind!==n.kind||i.dialect!==n.dialect||i.sport!==n.sport)return!1}return!0}function g5({noteId:e,initialContent:t,initialBlocks:n={},initialRevision:r=0,metadata:i,noteType:a=`note`,onExternalChange:o,onSavedRecord:s}){let[c,l]=(0,K.useState)({blocks:n,sourceRevision:r}),[u,d]=(0,K.useState)(null),[f,p]=(0,K.useState)(null),m=(0,K.useRef)(c.sourceRevision),h=(0,K.useRef)({rawContent:t,blocks:c.blocks,sourceRevision:c.sourceRevision}),g=(0,K.useRef)(null),_=(0,K.useRef)(i);_.current=i;let v=(0,K.useRef)(o);v.current=o;let y=(0,K.useRef)(s);y.current=s;let b=(0,K.useRef)(null);b.current!==e&&r>0&&(b.current=e,m.current=r,h.current={rawContent:t,blocks:n,sourceRevision:r},g.current=h.current,l({blocks:n,sourceRevision:r}));let x=(0,K.useCallback)(e=>{m.current=e.sourceRevision,g.current=e;let t=h.current,n=t.rawContent===e.rawContent&&h5(t.blocks,e.blocks);l(t=>({blocks:n?e.blocks:t.blocks,sourceRevision:e.sourceRevision})),y.current?.(e)},[]),S=(0,K.useCallback)(async t=>{if(UL(e))return h.current;let n=_.current,r={...n,...m5(t.rawContent,n)},i=eR.saveNote({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:m.current,metadata:r,noteType:a});tR.set(e,i);let o=await i.finally(()=>{tR.get(e)===i&&tR.delete(e)}),s=rR()[e];s&&s.rawContent===t.rawContent&&aR(e);let c={rawContent:o.rawContent,blocks:o.blocks??{},sourceRevision:o.sourceRevision??m.current};return x(c),p(null),c},[e,a,x]),C=v$({onSave:async e=>{await S(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:e=>p(`Save failed. ${e instanceof Error?e.message:String(e)} Your draft is kept. Retry saving.`)}),w=(0,K.useCallback)(async()=>C.hasDirtyDraft()?(await C.flush(),!0):!1,[C.hasDirtyDraft,C.flush]);gxe(()=>{if(e)return tde(e,w)},[e,w]);let T=(0,K.useCallback)(t=>{if(UL(e))return;let n=m5(t.rawContent,_.current);ede({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:m.current,...n?{metadata:n}:{},noteType:a,stagedAt:Date.now()})},[e,a]);(0,K.useEffect)(()=>{let e=()=>{let e=h.current,t=g.current;e&&(t&&t.rawContent===e.rawContent&&h5(t.blocks,e.blocks)||T(e))};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[T]);let E=(0,K.useCallback)(e=>{let t=h.current.rawContent!==e.rawContent||!h5(h.current.blocks,e.blocks);h.current=e,t&&(C.onChange(e),T(e))},[C.onChange,T]),D=(0,K.useCallback)(e=>{d(null);let t=Math.max(1,m.current),n=h.current.rawContent===e?h.current.blocks:Vs(e,{sourceRevision:t,blocks:h.current.blocks,registeredWidgets:Ns});E({rawContent:e,blocks:n,sourceRevision:m.current}),v.current?.(e)},[E]),O=(0,K.useCallback)(async e=>{await C.flush();let t=h.current;if(!t)throw Error(`The note draft is unavailable.`);let n=f5({...t,sourceRevision:m.current},e),r=await S(n);h.current=r,d(n.rawContent),v.current?.(n.rawContent)},[C.flush,S]),k=(0,K.useCallback)(async(t,n)=>{p(null);try{await C.flush();let r=h.current,i=await Yz({noteId:e,rawContent:r.rawContent,blocks:r.blocks,expectedSourceRevision:m.current,metadata:_.current,noteType:a},t,n,void 0,void 0,{deferPersist:!0});return x({rawContent:i.note.rawContent,blocks:i.note.blocks,sourceRevision:i.note.sourceRevision}),i}catch(e){let t=`Workout not started. ${e instanceof Error?e.message:String(e)} Your draft is kept.`;throw p(t),e}},[C.flush,e,a,x]),A=(0,K.useCallback)(async()=>{await C.flush()},[C.flush]),j=(0,K.useCallback)(()=>{C.cancel(),h.current=g.current??h.current,aR(e)},[C.cancel,e]);return{content:u??h.current.rawContent,committedBlocks:c.blocks,committedRevision:c.sourceRevision,committedSourceRevision:(0,K.useCallback)(()=>m.current,[]),draftSnapshot:h.current,saveError:f??(C.error?`Save failed. ${C.error instanceof Error?C.error.message:String(C.error)} Your draft is kept. Retry saving.`:null),flush:A,cancel:j,onLineChange:C.onLineChange,onBlur:C.onBlur,onIdentityChange:E,onSourceMutate:D,restoreRevision:O,captureForRun:k,accept:x}}var _xe=new DR;function _5(e){let{entry:t,liveContent:n,isReadOnly:r,copied:i,deletingNote:a,onEditPageSlug:o,onAddWidget:s,onMutateContent:c,onOpenPromotion:l,onOpenPlacement:u,onCopyLink:d,onRequestDelete:f,provider:p}=e;return[...!r&&c?[{id:`add-timer`,label:`Add timer`,group:`author`,onRun:()=>c(t,E$(n))}]:[],...!r&&s?[{id:`add-widget`,label:`Add widget`,group:`author`,onRun:()=>s(t)}]:[],...!r&&o?[{id:`upgrade-to-page`,label:t.slug?`Edit page route`:`Upgrade to Page`,group:`organize`,onRun:()=>o(t)}]:[],{id:`promote-notebooks`,label:`Notebooks & Promotion`,group:`organize`,onRun:()=>l(t)},{id:`placements`,label:`Note placements`,group:`organize`,onRun:()=>u(t,`relationships`)},{id:`clone`,label:`Clone`,group:`organize`,onRun:()=>u(t,`clone`)},{id:`copy-link`,label:i?`Copied`:`Copy link`,group:`share`,onRun:()=>d(t)},{id:`export-md`,label:`Export Note (.md)`,group:`share`,onRun:()=>{sL(t,p,{format:`md`})}},{id:`export-jsonl`,label:`Export Session Data (.jsonl)`,group:`share`,onRun:()=>{sL(t,p,{format:`jsonl`})}},{id:`export-csv`,label:`Export Session Data (.csv)`,group:`share`,onRun:()=>{sL(t,p,{format:`csv`})}},...r?[]:[{id:`delete-note`,label:`Delete note`,icon:Me,group:`danger`,disabled:a,testId:`l3-delete-note`,onRun:()=>f(t)}]]}function v5(e){let{entry:t,liveContent:n,isReadOnly:r=!1,deleteRedirectTo:i=Z.journal,provider:a=_xe,onMutateContent:o,onEditPageSlug:s,onAddWidget:c,onUpdated:l,onCloned:u,onDeleted:d,onBeforeDelete:f}=e,p=dt(),[m,h]=(0,K.useState)(null),[g,_]=(0,K.useState)(!1),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(!1),[S,C]=(0,K.useState)(null),[w,T]=(0,K.useState)(null);(0,K.useEffect)(()=>{if(!v||!t){T(null);return}let e=!1;return Promise.all([CU.listForNote(t.id).catch(()=>[]),X.getSessionsForNote(t.id).catch(()=>[])]).then(([n,r])=>{e||T({schedules:n.length,sessions:r.length,notebooks:t.notebookIds?.length??+!!t.notebookId})}),()=>{e=!0}},[v,t]);let[E,D]=(0,K.useState)(!1);(0,K.useEffect)(()=>{y(!1),C(null),h(null),_(!1)},[t?.id]);let O=(0,K.useCallback)(e=>{let t=`${window.location.origin}${SH(e.id)}`;navigator.clipboard?.writeText(t).then(()=>{D(!0),window.setTimeout(()=>D(!1),1800)}).catch(()=>{})},[]),k=(0,K.useCallback)(async()=>{if(!(!t||r||b)){x(!0),C(null),Que(t.id),f?.(t.id),aR(t.id);try{await lR(t.id),await DU.delete(t.id),aR(t.id),y(!1),d?d(t.id):p(i,{replace:!0})}catch(e){HL(t.id),C(e instanceof Error?e.message:`Failed to delete note.`)}finally{x(!1)}}},[i,b,t,r,p,f,d]);return{helpfulActions:(0,K.useMemo)(()=>t?_5({entry:t,liveContent:n??t.rawContent,isReadOnly:r,copied:E,deletingNote:b,onEditPageSlug:s,onAddWidget:c,onMutateContent:o,onOpenPromotion:()=>_(!0),onOpenPlacement:(e,t)=>h(t),onCopyLink:O,onRequestDelete:()=>{C(null),y(!0)},provider:a}):[],[E,b,t,O,r,n,c,s,o,a]),placement:m,setPlacement:h,promotionOpen:g,setPromotionOpen:_,confirmDeleteOpen:v,setConfirmDeleteOpen:y,deletingNote:b,deleteError:S,copied:E,handleCopyLink:O,handleConfirmDelete:k,dialogs:t?(0,q.jsxs)(q.Fragment,{children:[m!==null&&(0,q.jsx)(mxe,{open:!0,onOpenChange:e=>{e||h(null)},entry:t,mode:m,provider:a,onSaved:e=>l?.(e),onCloned:e=>{u?u(e):p(`${SH(e.id)}?edit=1`)}}),(0,q.jsxs)(ei,{open:v,onOpenChange:e=>{b||(y(e),e||C(null))},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{"data-testid":Q.NOTE_DELETE_DIALOG,children:[(0,q.jsxs)(Do,{children:[(0,q.jsx)(oa,{children:`Delete note?`}),(0,q.jsxs)(Xi,{children:[`Permanently delete “`,t.title||`Untitled note`,`”? This cannot be undone.`,w&&(w.schedules>0||w.sessions>0||w.notebooks>0)&&(0,q.jsxs)(`span`,{className:`mt-2 block text-xs text-muted-foreground`,children:[`Removes `,w.schedules,` scheduled date`,w.schedules===1?``:`s`,` and detaches from`,` `,w.notebooks,` notebook`,w.notebooks===1?``:`s`,`. Existing`,` `,w.sessions,` logged session`,w.sessions===1?``:`s`,` and archived snapshots remain preserved.`]})]})]}),S&&(0,q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:S}),(0,q.jsxs)(Oo,{children:[(0,q.jsx)(Sr,{disabled:b,onClick:()=>C(null),"data-testid":Q.NOTE_DELETE_CANCEL,children:`Cancel`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`destructive`,disabled:b,"data-agent-confirm":`Deletes note "${t.title||`Untitled note`}" permanently`,action:()=>k(),"data-testid":Q.NOTE_DELETE_CONFIRM,children:b?`Deleting…`:`Delete forever`})]})]})]})]}):null}}function y5({noteId:e,noteTitle:t,actions:n}){let[r,i]=(0,K.useState)(!1);if(n.length===0)return null;let a=t?`Note options for ${t}`:`Note options`;return(0,q.jsx)(`div`,{onClick:e=>e.stopPropagation(),children:(0,q.jsxs)(ta,{open:r,onOpenChange:i,children:[(0,q.jsx)(A,{render:(0,q.jsx)(J,{variant:`ghost`,size:`icon`,className:`h-7 w-7 min-h-7 min-w-7 text-muted-foreground hover:text-foreground`,"aria-label":a,title:`Note options`,"data-testid":`note-card-options-${e}`}),children:(0,q.jsx)(Ln,{className:`size-4`,"aria-hidden":`true`})}),(0,q.jsx)(Ot,{align:`end`,sideOffset:6,className:`w-56`,children:n.map(t=>{let n=t.icon;return(0,q.jsxs)(Ft,{value:t.id,disabled:t.disabled,"data-testid":t.testId?`card-${t.testId}-${e}`:void 0,className:t.id===`delete-note`?`text-destructive data-highlighted:text-destructive`:void 0,onClick:()=>{i(!1),t.onRun()},children:[n&&(0,q.jsx)(n,{className:`mr-2 size-4`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:t.label})]},t.id)})})]})})}function b5(e){return(0,q.jsx)(vxe,{...e},e.entry.id)}function vxe({entry:e,onChange:t,registerRun:n,...r}){let i=g5({noteId:e.id,initialContent:e.rawContent,initialBlocks:e.blocks??{},initialRevision:e.sourceRevision??0,onExternalChange:t});return(0,K.useEffect)(()=>(n?.(async(e,t)=>i.captureForRun(e,t)),()=>n?.(null)),[n,i.captureForRun]),(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(M4,{...r,noteId:e.id,value:i.content,noteBlocks:i.committedBlocks,sourceRevision:i.committedRevision,onIdentityChange:i.onIdentityChange,onSaved:i.accept,beforeRun:async()=>(await i.flush(),i.committedSourceRevision()),onSaveRequest:i.flush,onChange:i.onSourceMutate,onBlur:i.onBlur,onCursorPositionChange:i.onLineChange,onCommitChange:i.flush}),i.saveError?(0,q.jsx)(`p`,{role:`alert`,children:i.saveError}):null,(0,q.jsx)(p5,{noteId:e.id,blocks:i.committedBlocks,sourceRevision:i.committedRevision,onRevert:i.restoreRevision})]})}function yxe({plannedEntry:e,journalDate:t,onForked:n}){let{item:r,note:i,pairedSessions:a}=e,o=r.status===`completed`||a.length>0,s=r.status===`skipped`,[c,l]=(0,K.useState)(r.notes??``),[u,d]=(0,K.useState)(r.notes??``),[f,p]=(0,K.useState)(!1),[m,h]=(0,K.useState)(!1),[g,_]=(0,K.useState)(null);(0,K.useEffect)(()=>{let e=r.notes??``;l(e),d(e)},[r.id,r.notes]);let v=c.trim()!==u.trim(),y=async()=>{h(!0),_(null),p(!1);try{let e=c.trim();await CU.updateItem(r.id,{notes:e}),d(e),l(e),p(!0)}catch(e){_(e instanceof Error?e.message:`Could not save day cue.`)}finally{h(!1)}},b=async()=>{h(!0),_(null);try{n((await i5({scheduleItemId:r.id,sourceNoteId:r.noteId,date:t,fallbackTitle:i?.title||r.fallbackTitle})).id)}catch(e){_(e instanceof Error?e.message:`Could not fork copy for this day.`)}finally{h(!1)}};return(0,q.jsxs)(`li`,{className:`space-y-2.5 rounded-md border border-border/60 bg-background px-3 py-2.5 text-xs`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsx)(M,{to:SH(r.noteId),className:`truncate font-semibold text-foreground hover:underline`,children:i?.title||r.fallbackTitle||`Untitled workout`}),r.slot&&(0,q.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[11px] font-bold uppercase text-muted-foreground`,children:r.slot}),(0,q.jsx)(`span`,{className:`rounded-full px-2 py-0.5 text-[11px] font-semibold ${o?`bg-emerald-500/15 text-emerald-800 dark:text-emerald-200`:s?`bg-muted text-muted-foreground line-through`:`bg-primary/10 text-primary`}`,children:o?`Completed`:s?`Skipped`:`Planned`})]})}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void b(),"data-testid":Q.DAY_PLAN_FORK_BTN,className:`h-7 max-lg:min-h-11 gap-1 px-2 text-[11px]`,children:[(0,q.jsx)(Pe,{className:`size-3`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Fork for this day`})]}),!s&&(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void CU.updateItem(r.id,{status:`skipped`}),className:`h-7 max-lg:min-h-11 px-2 text-[11px]`,children:`Skip`}),s&&(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m,onClick:()=>void CU.updateItem(r.id,{status:`planned`}),className:`h-7 max-lg:min-h-11 px-2 text-[11px]`,children:`Restore`}),(0,q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:m,onClick:()=>void CU.removeItem(r.id),className:`h-7 max-lg:min-h-11 px-2 text-[11px] text-muted-foreground hover:text-destructive`,children:`Unschedule`})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,q.jsx)(`input`,{type:`text`,value:c,onChange:e=>{l(e.target.value),f&&p(!1)},disabled:m,placeholder:`Add day cue (keeps canonical Note unchanged)…`,"aria-label":`Day cue for ${i?.title||r.fallbackTitle||`workout`}`,"data-testid":Q.DAY_PLAN_CUE_INPUT,className:`h-8 max-lg:min-h-11 min-w-0 flex-1 rounded-md border border-input bg-card px-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:m||!v,onClick:()=>void y(),"data-testid":Q.DAY_PLAN_CUE_SAVE,className:`h-8 max-lg:min-h-11 gap-1 px-2.5 text-[11px]`,children:[(0,q.jsx)(qi,{className:`size-3`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Save`})]}),f&&!v&&(0,q.jsx)(`span`,{className:`text-[11px] font-semibold text-emerald-700 dark:text-emerald-300`,children:`Saved`})]}),g&&(0,q.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:g})]})}function bxe({journalDate:e,theme:t,onViewCreated:n}){let[r,i]=(0,K.useState)(null),[a,o]=(0,K.useState)(null),[s,c]=(0,K.useState)(0);(0,K.useEffect)(()=>xU(()=>c(e=>e+1)),[]),(0,K.useEffect)(()=>mR(()=>c(e=>e+1)),[]);let[l,u]=be(),d=dt(),f=hY(),[p,m]=(0,K.useState)(!1),[h,g]=(0,K.useState)(`write`),_=(0,K.useCallback)((e=`write`)=>{g(e),m(!0)},[]),[v,y]=(0,K.useState)(!1),[b,x]=(0,K.useState)(null),[S,C]=(0,K.useState)(null),[w,T]=(0,K.useState)(null),[E,D]=(0,K.useState)(null),O=(0,K.useRef)(null);O.current=E;let k=(0,K.useRef)(null),A=(0,K.useRef)(!1),j=(0,K.useRef)(null),N=(0,K.useRef)(null),P=(0,K.useRef)(new Map),[F,I]=(0,K.useState)(null),ee=(0,K.useCallback)(async()=>{let e=O.current;if(e)return e.block;let t=j.current;if(!t||!S)throw Error(`The pending workout is unavailable.`);return t.captured?(N.current=t.captured,t.captured.block):(N.current||=t.snapshot?await Yz(t.snapshot,t.block,S,t.origin,void 0,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}):await Xz(t.noteId,t.block,S,t.origin,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}),N.current.block)},[S]),[L,R]=(0,K.useState)({}),z=(0,K.useCallback)((e,t)=>{R(n=>n[e]===t?n:{...n,[e]:t})},[]),B=(0,K.useRef)(new Map),V=(0,K.useRef)(null),[H,U]=(0,K.useState)(null),te=(0,K.useCallback)((e,t)=>{B.current.set(e,t),V.current||(V.current=t,U(t),n?.(t))},[n]),W=l.get(`note`);(0,K.useEffect)(()=>{if(!W||!r)return;let e=document.getElementById(`note-${W}`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},[W,r]);let ne=l.toString();(0,K.useEffect)(()=>{let e=new URLSearchParams(ne).get(`autoStart`);if(!e)return;let t=Dz.get(e);t&&(Dz.delete(e),j.current=t,N.current=null,k.current={runtimeId:e,block:t.block,noteId:t.noteId,captured:t.captured},A.current=!1,x(t.block),C(e),T(t.noteId),y(!0)),u(e=>(e.delete(`autoStart`),e),{replace:!0})},[ne,u]),(0,K.useEffect)(()=>{if(v)return;let t=Mz(e);t&&(D(t),j.current={block:t.block,noteId:t.noteId,captured:t.captured},N.current=t.captured??null,k.current={runtimeId:t.runtimeId,block:t.block,noteId:t.noteId,captured:t.captured},x(t.block),C(t.runtimeId),T(t.noteId),y(!0))},[e,v]);let re=(0,K.useCallback)((e,t)=>{i(n=>n?.map(n=>n.id===e&&n.rawContent!==t?{...n,rawContent:t,blocks:Vs(t,{sourceRevision:Math.max(1,n.sourceRevision??1),blocks:n.blocks,registeredWidgets:Ns})}:n)??n)},[]),ie=(0,K.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=N.current;if(!a)return Promise.reject(Error(`The saved run pin is unavailable.`));A.current=!0,Nz(a.session.id);let o=a.session.id,s=B.current.get(a.session.noteId);if(s&&!s.state.doc.toString().includes(qN(o))){let e=YN(s.state,a.session.blockId,o);e&&s.dispatch({changes:e})}return _R.record({blockId:a.session.blockId,noteId:a.session.noteId,resultId:o,blockVersion:a.revision.version,blockContentId:a.session.blockContentId,blockContent:a.block.content,...a.block.dialect?{blockDialect:a.block.dialect}:{},...a.block.sport?{blockSport:a.block.sport}:{},...a.session.origin?{origin:a.session.origin}:{},...a.session.scheduleItemId?{scheduleItemId:a.session.scheduleItemId}:{},...a.session.sessionDate?{sessionDate:a.session.sessionDate}:{},data:t,createdAt:t.endTime})},[]),ae=BZ(),[oe,se]=(0,K.useState)(!1),ce=(0,K.useRef)(null);(0,K.useEffect)(()=>{let t=!1;return ce.current!==e&&(ce.current=e,i(null)),Promise.all([DU.listByDate(e),CU.getDayOverlay(e).catch(()=>null)]).then(([n,r])=>{t||(ce.current=e,i(n),o(r))}).catch(()=>{t||(ce.current=e,i([]),o(null))}),()=>{t=!0}},[e,s]),(0,K.useEffect)(()=>QX(r===null),[r]),(0,K.useEffect)(()=>{if(r!==null){se(!1);return}let e=setTimeout(()=>se(!0),3e3);return()=>clearTimeout(e)},[r]);let le=/^\d{4}-\d{2}-\d{2}$/.test(e),ue=(0,K.useMemo)(()=>{if(!le)return null;let[t,n,r]=e.split(`-`).map(Number);return{prev:pU(new Date(t,n-1,r-1)),next:pU(new Date(t,n-1,r+1))}},[e,le]),{setL3Items:de,setL3Actions:fe}=NV(),[pe,me]=(0,K.useState)({}),he=r?.map(e=>e.id).join(`|`)??``,ge=(0,K.useMemo)(()=>he?he.split(`|`):[],[he]);(0,K.useEffect)(()=>{if(ge.length===0)return;let e=!1;for(let t of ge)X.getSessionsForNote(t).then(n=>{e||me(e=>({...e,[t]:n}))}).catch(()=>{});return()=>{e=!0}},[ge]),(0,K.useEffect)(()=>mR(e=>{X.getSessionsForNote(e.noteId).then(t=>{me(n=>({...n,[e.noteId]:t}))}).catch(()=>{})}),[]);let _e=r!==null&&r.length===1?r[0]:null,ve=_e?pe[_e.id]:void 0,[ye,xe]=(0,K.useState)(null),Se=(0,K.useMemo)(()=>new DR,[]),Ce=_e??ye,we=v5({entry:Ce,isReadOnly:!1,deleteRedirectTo:bH(e),provider:Se,onMutateContent:(e,t)=>re(e.id,t),onUpdated:()=>{DU.listByDate(e).then(i).catch(()=>{})},onDeleted:e=>{xe(null),i(t=>t&&t.filter(t=>t.id!==e))}}),Te=(0,K.useCallback)(e=>_5({entry:e,liveContent:e.rawContent,isReadOnly:!1,copied:we.copied&&Ce?.id===e.id,deletingNote:we.deletingNote&&Ce?.id===e.id,onMutateContent:(e,t)=>re(e.id,t),onOpenPromotion:e=>{xe(e),we.setPromotionOpen(!0)},onOpenPlacement:(e,t)=>{xe(e),we.setPlacement(t)},onCopyLink:e=>{xe(e),we.handleCopyLink(e)},onRequestDelete:e=>{xe(e),we.setConfirmDeleteOpen(!0)},provider:Se}),[Ce?.id,Se,re,we]),Ee=(0,K.useCallback)(async(t,n,r)=>{try{let i=P.current.get(t);if(!i)throw Error(`The saved note editor is unavailable.`);let o=Br(),s=r??a?.planned.find(e=>e.item.noteId===t&&e.item.status===`planned`)?.item.id,c=await i(n,o);Dz.set(o,{noteId:t,block:c.block,captured:c,returnTo:bH(e),...s?{scheduleItemId:s}:{},sessionDate:e}),d(DH(o))}catch(e){I(e instanceof Error?e.message:String(e))}},[e,d,a]),G=(0,K.useCallback)(e=>{_e&&Ee(_e.id,e)},[_e,Ee]),De=(0,K.useMemo)(()=>_e?[{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},...we.helpfulActions]:[],[_e,_,we.helpfulActions]);s6({content:_e?.rawContent??``,scriptBlocks:_e?L[_e.id]??[]:[],onStartWorkout:G,results:ve,noteId:_e?.id,helpfulActions:De,enabled:!!_e});let Oe=(0,K.useCallback)(e=>t=>{Ee(e,t)},[Ee]),ke=(0,K.useMemo)(()=>{if(!r||r.length<=1)return[];let e=[];for(let t of r){let n=t.title||`Untitled note`,r=o6(D$(t.rawContent),L[t.id]??[],Oe(t.id),pe[t.id]);for(let i of r)e.push(...O$([{...i,id:`note-${t.id}:${i.id}`,label:`${n} · ${i.label}`}]))}return e},[r,L,pe,Oe]),Ae=r&&r.length>1?r[0]:null,je=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(Ae)return je.current=!0,de(ke),fe?.([{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},{id:`helpful-add-timer`,label:`Add timer`,group:`author`,onRun:()=>re(Ae.id,E$(Ae.rawContent))}]),()=>{je.current&&(je.current=!1,de([]),fe?.([]))}},[ke,Ae,re,_,de,fe]),FV(`notebooks`);let Ne=e6(),Pe=(0,K.useMemo)(()=>le?(0,q.jsx)(i6,{selectedDate:new Date(`${e}T12:00:00`),onDateSelect:e=>d(bH(pU(e))),entryDates:Ne}):void 0,[le,e,Ne,d]),Fe=r!==null&&r.length===0,Ie=(0,K.useRef)(!1);return(0,K.useEffect)(()=>{if(Fe)return Ie.current=!0,de([]),fe?.([{id:`day-add-note`,label:`Add note`,icon:ti,group:`primary`,onRun:()=>_(`write`)},{id:`day-pick-workout`,label:`Pick / Log workout`,icon:ci,group:`author`,onRun:()=>_(`pick`)},{id:`day-jump-today`,label:`Jump to today`,icon:Re,group:`organize`,onRun:()=>d(bH(pU(new Date)))},{id:`day-open-journal`,label:`Open Journal`,icon:Xt,group:`organize`,onRun:()=>d(`/journal`)},{id:`day-empty-notebooks`,label:`Notebooks & Promotion`,group:`organize`,disabled:!0,onRun:()=>{}},{id:`day-empty-clone`,label:`Clone`,group:`organize`,disabled:!0,onRun:()=>{}},{id:`day-copy-link`,label:`Copy day link`,icon:Gi,group:`share`,onRun:()=>{let t=typeof window<`u`?`${window.location.origin}${bH(e)}`:bH(e);navigator.clipboard?.writeText(t).catch(()=>void 0)}},{id:`day-empty-export`,label:`Export Note (.md)`,group:`share`,disabled:!0,onRun:()=>{}},{id:`day-empty-delete`,label:`Delete note`,icon:Me,group:`danger`,disabled:!0,testId:`l3-delete-note`,onRun:()=>{}}]),()=>{Ie.current&&(Ie.current=!1,de([]),fe?.([]))}},[Fe,e,d,_,fe,de]),r?W?(0,q.jsx)(at,{to:SH(W),replace:!0}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(Q3,{data:{efforts:[],related:[],backlinks:[]},up:{id:`journal`,title:`Journal`,to:`/journal`},calendar:Pe}),(0,q.jsx)(YY,{title:e,subtitle:`${r.length} ${r.length===1?`note`:`notes`}`,actions:f?(0,q.jsx)(lX,{primary:(0,q.jsxs)(J,{type:`button`,onClick:()=>_(`write`),"aria-label":`+ Add note`,title:`New note`,children:[(0,q.jsx)(ti,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`+ Add`]})}):void 0,editor:(0,q.jsxs)(`div`,{className:`flex flex-col gap-8 px-4 py-6 sm:px-6`,children:[F&&(0,q.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,F,` Your draft is kept.`]}),(0,q.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,q.jsx)(`button`,{type:`button`,onClick:()=>jde()?d(-1):d(`/journal`),className:`rounded-pill border border-border px-2 py-0.5 hover:bg-accent hover:text-foreground transition-colors`,children:`‹ Journal`}),ue&&(0,q.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,q.jsxs)(M,{to:bH(ue.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:[`‹ `,ue.prev]}),(0,q.jsx)(`span`,{className:`font-semibold text-foreground`,children:e}),(0,q.jsxs)(M,{to:bH(ue.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:[ue.next,` ›`]})]})]}),a&&(a.planned.length>0||a.adhocSessions.length>0)&&(0,q.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[a.planned.length>0&&(0,q.jsxs)(`section`,{"data-testid":Q.DAY_SCHEDULED_SECTION,"aria-label":`Scheduled workouts`,className:`rounded-lg border border-border/60 bg-muted/20 p-3.5 space-y-2.5`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-between`,children:(0,q.jsxs)(`h2`,{className:`text-xs font-bold uppercase tracking-wider text-muted-foreground`,children:[`Scheduled Plans (`,a.planned.length,`)`]})}),(0,q.jsx)(`ul`,{className:`space-y-2`,children:a.planned.map(t=>(0,q.jsx)(yxe,{plannedEntry:t,journalDate:e,onForked:e=>{c(e=>e+1),d(`${SH(e)}?edit=1`)}},t.item.id))})]}),(a.planned.some(e=>e.pairedSessions.length>0)||a.adhocSessions.length>0)&&(0,q.jsxs)(`section`,{"data-testid":Q.DAY_LOGGED_SECTION,"aria-label":`Logged sessions`,className:`rounded-lg border border-border/60 bg-muted/20 p-3.5 space-y-2.5`,children:[(0,q.jsx)(`h2`,{className:`text-xs font-bold uppercase tracking-wider text-muted-foreground`,children:`Logged Sessions`}),(0,q.jsxs)(`ul`,{className:`space-y-2`,children:[a.planned.flatMap(({item:e,note:t,pairedSessions:n})=>n.map(n=>(0,q.jsxs)(`li`,{className:`flex items-center justify-between gap-2 rounded-md border border-emerald-500/30 bg-background px-3 py-2 text-xs`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(M,{to:`/results/${encodeURIComponent(n.id)}`,className:`font-semibold text-foreground hover:underline`,children:t?.title||`Session`}),(0,q.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Paired with `,e.slot?`${e.slot} plan`:`scheduled plan`,n.noteSourceRevision?` · v${n.noteSourceRevision}`:``]})]}),typeof n.duration==`number`&&n.duration>0&&(0,q.jsx)(`span`,{className:`font-mono text-[11px] text-emerald-700 dark:text-emerald-300`,children:ps(n.duration)})]},n.id))),a.adhocSessions.map(({session:t,note:n})=>(0,q.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-md border border-sky-500/30 bg-background px-3 py-2 text-xs`,children:[(0,q.jsxs)(`div`,{className:`min-w-0`,children:[(0,q.jsx)(M,{to:`/results/${encodeURIComponent(t.id)}`,className:`font-semibold text-foreground hover:underline`,children:n?.title||`Ad-hoc workout`}),(0,q.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Ad-hoc log`,t.noteSourceRevision?` · v${t.noteSourceRevision}`:``]})]}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.planned.filter(e=>e.item.noteId===t.noteId&&e.pairedSessions.length===0).slice(0,1).map(n=>(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void CU.attributeSession({sessionId:t.id,sessionDate:e,scheduleItemId:n.item.id}),className:`h-7 px-2 text-[11px]`,children:`Pair with plan`},n.item.id)),typeof t.duration==`number`&&t.duration>0&&(0,q.jsx)(`span`,{className:`font-mono text-[11px] text-sky-700 dark:text-sky-300`,children:ps(t.duration)})]})]},t.id))]})]})]}),r.length>1&&(0,q.jsx)(`nav`,{"aria-label":`Notes on this date`,className:`flex flex-wrap gap-2`,children:r.map(e=>(0,q.jsx)(M,{to:SH(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,q.jsxs)(`div`,{className:`flex flex-col items-start gap-3 rounded-lg border border-dashed border-border p-6`,children:[(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Notes on this date yet.`}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,q.jsxs)(J,{type:`button`,size:`lg`,onClick:()=>_(`write`),children:[(0,q.jsx)(ti,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Create a note`]}),(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`lg`,onClick:()=>_(`pick`),children:[(0,q.jsx)(ci,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Pick / Log workout`]})]})]}):r.length===1?(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/40 pb-2`,children:[(0,q.jsx)(M,{to:SH(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,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(a$,{noteId:r[0].id,notebookId:r[0].notebookId,sessions:pe[r[0].id],isReadOnlyFeedNote:!1,open:we.promotionOpen&&Ce?.id===r[0].id,onOpenChange:e=>{e&&xe(r[0]),we.setPromotionOpen(e)},onCloneRequest:()=>{xe(r[0]),we.setPlacement(`clone`)},onChanged:()=>{DU.listByDate(e).then(i).catch(()=>{})}}),(0,q.jsx)(y5,{noteId:r[0].id,noteTitle:r[0].title,actions:Te(r[0])})]})]}),(0,q.jsx)(b5,{entry:r[0],registerRun:e=>{e?P.current.set(r[0].id,e):P.current.delete(r[0].id)},onChange:e=>re(r[0].id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>z(r[0].id,e),onCompleteWorkout:(e,t,n,i)=>ie(e,t,n,i,r[0].id),onViewCreated:e=>te(r[0].id,e)},r[0].id)]}):(0,q.jsx)(`div`,{className:`space-y-6`,children:r.map((n,r)=>(0,q.jsxs)(`div`,{id:`note-${n.id}`,className:`border-t border-border/60 pt-6 first:border-t-0 first:pt-0 space-y-2`,children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b border-border/40 pb-2`,children:[(0,q.jsx)(M,{to:SH(n.id),className:`text-sm font-semibold hover:underline text-foreground`,children:n.title||`Note ${r+1}`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(a$,{noteId:n.id,notebookId:n.notebookId,sessions:pe[n.id],isReadOnlyFeedNote:!1,open:we.promotionOpen&&Ce?.id===n.id,onOpenChange:e=>{e&&xe(n),we.setPromotionOpen(e)},onCloneRequest:()=>{xe(n),we.setPlacement(`clone`)},onChanged:()=>{DU.listByDate(e).then(i).catch(()=>{})}}),(0,q.jsx)(y5,{noteId:n.id,noteTitle:n.title||`Note ${r+1}`,actions:Te(n)})]})]}),(0,q.jsx)(b5,{entry:n,registerRun:e=>{e?P.current.set(n.id,e):P.current.delete(n.id)},onChange:e=>re(n.id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>z(n.id,e),onCompleteWorkout:(e,t,r,i)=>ie(e,t,r,i,n.id),onViewCreated:e=>te(n.id,e)})]},n.id))})]})}),we.dialogs,(0,q.jsx)(R$,{open:p,onOpenChange:m,defaultDate:e,defaultNoteMode:h,onCreated:t=>{DU.listByDate(e).then(i).catch(()=>{}),d(SH(t.id))}}),v&&b&&(0,q.jsx)(z2,{block:b,prepareRun:ee,onClose:()=>{y(!1),C(null),T(null),D(null),A.current=!0;let e=k.current;e&&Nz(e.runtimeId),k.current=null},resultId:S??void 0,onCompleteWorkout:(e,t)=>ie(e,t),autoStart:!0,adoptRuntime:E?.runtime??null,parkOnUnmount:!0,onPark:t=>{let n=k.current;if(!n||A.current){t.dispose();return}kz({runtimeId:n.runtimeId,block:n.block,noteId:n.noteId,captured:n.captured,runtime:t,journalDate:e})},onRuntimeReady:e=>{let t=k.current;if(!t)return;let n=Az(t.runtimeId);n&&n.runtime!==e&&n.runtime.dispose()}})]}):(0,q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`flex-1 flex flex-col items-center justify-center gap-1.5 p-8 text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`text-sm`,children:`Loading…`}),oe&&(0,q.jsx)(`span`,{className:`text-xs`,"data-testid":`journal-slow-loading-hint`,children:ae?nZ(ae):`Opening local journal index — large vaults may take a few seconds…`})]})}var xxe=()=>(0,q.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,q.jsx)(`div`,{className:`mt-0.5 flex-shrink-0 text-primary`,children:(0,q.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,"aria-hidden":`true`,children:[(0,q.jsx)(`circle`,{cx:`9`,cy:`9`,r:`8`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,q.jsx)(`path`,{d:`M9 5v4.5M9 11.5v1`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}),(0,q.jsxs)(`div`,{className:`flex-1 text-sm leading-relaxed text-muted-foreground`,children:[(0,q.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Ready to try it?`}),` `,`Press the`,` `,(0,q.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,q.jsx)(`div`,{className:`pointer-events-none absolute -bottom-4 right-8 text-primary/50`,"aria-hidden":`true`,children:(0,q.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 20 20`,fill:`none`,children:[(0,q.jsx)(`path`,{d:`M3 3 L17 3 L17 17`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,q.jsx)(`path`,{d:`M11 11 L17 17 L23 11`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]});function x5({config:e,onAction:t}){return!e.headline||!e.subtitle||e.pillars.length===0?(0,q.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,q.jsx)(`code`,{children:`attention`}),` widget config.`]}):(0,q.jsxs)(`section`,{className:`p-8`,children:[(0,q.jsx)(`p`,{className:`mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:`Playground`}),(0,q.jsx)(`h1`,{className:`text-3xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-100 sm:text-4xl`,children:e.headline}),(0,q.jsx)(`p`,{className:`mt-4 max-w-3xl text-base leading-7 text-zinc-600 dark:text-zinc-300`,children:e.subtitle}),(0,q.jsx)(`div`,{className:`mt-7 grid gap-3 md:grid-cols-3`,children:e.pillars.map(e=>(0,q.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,q.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,q.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.label}),(0,q.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]},e.label))}),(0,q.jsx)(`div`,{className:`mt-7 flex flex-wrap gap-3`,children:e.actions.map(e=>(0,q.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,q.jsx)(ae,{className:`size-4`,"aria-hidden":`true`})]},`${e.action}-${e.label}`))})]})}function S5({config:e,isDarkMode:t,onRun:n}){let r=(0,K.useRef)(null),i=(0,K.useRef)(null),a=(0,K.useMemo)(()=>e.lines.map(e=>e.code).join(`
|
|
1169
1169
|
`),[e.lines]);return(0,K.useEffect)(()=>{if(r.current)return i.current?.destroy(),i.current=new mo({state:qa.create({doc:a,extensions:[Ha(),ho(),qa.readOnly.of(!1),mo.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)`}}),mo.theme({"&":{"--cm-border":t?`rgba(82, 82, 91, 0.7)`:`rgba(212, 212, 216, 0.9)`}},{dark:t}),...t?[Va]:[]]}),parent:r.current}),()=>{i.current?.destroy(),i.current=null}},[t,a]),e.lines.length===0?(0,q.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,q.jsx)(`code`,{children:`code-example`}),` widget config.`]}):(0,q.jsxs)(`section`,{className:`p-5`,children:[(0,q.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,q.jsx)(`h2`,{className:`text-base font-semibold text-zinc-900 dark:text-zinc-100`,children:`Code example`}),(0,q.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,q.jsx)(Er,{className:`size-3.5`,"aria-hidden":`true`}),e.cta]})]}),(0,q.jsx)(`div`,{ref:r}),(0,q.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,q.jsxs)(`li`,{className:`flex gap-2`,children:[(0,q.jsx)(`span`,{className:`mt-1 inline-block size-1.5 rounded-full bg-zinc-400`,"aria-hidden":`true`}),(0,q.jsxs)(`span`,{children:[(0,q.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 C5({config:e,onOpenDocs:t}){return!e.category||!e.title||!e.docsPath?(0,q.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,q.jsx)(`code`,{children:`syntax-group`}),` widget config.`]}):(0,q.jsxs)(`article`,{className:`p-5`,children:[(0,q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`p`,{className:`text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:e.category}),(0,q.jsxs)(`h3`,{className:`mt-2 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[(0,q.jsx)(`span`,{className:`mr-2`,"aria-hidden":`true`,children:e.icon}),e.title]}),(0,q.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]}),(0,q.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,q.jsx)(wi,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,q.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,q.jsx)(`code`,{children:e.example})})]})}function Sxe(e){return({config:t})=>(0,q.jsx)(x5,{config:t,onAction:e})}function Cxe(e,t){return({config:n})=>(0,q.jsx)(S5,{config:n,isDarkMode:e,onRun:t})}function wxe(e){return({config:t})=>(0,q.jsx)(C5,{config:t,onOpenDocs:e})}var w5=[`visitedLanding`,`editedNote`,`ranWorkout`,`loggedEffort`,`openedReview`],T5=`wodwiki.onboarding.v1`,E5={visitedLanding:!1,editedNote:!1,ranWorkout:!1,loggedEffort:!1,openedReview:!1};function D5(){if(typeof window>`u`||!window.localStorage)return{...E5};try{let e=window.localStorage.getItem(T5);if(!e)return{...E5};let t=JSON.parse(e),n={...E5};for(let e of w5)n[e]=t[e]===!0;return n}catch{return{...E5}}}function Txe(e){if(!(typeof window>`u`||!window.localStorage))try{window.localStorage.setItem(T5,JSON.stringify(e))}catch{}}function Exe(){let[e,t]=(0,K.useState)(D5);(0,K.useEffect)(()=>{let e=e=>{e.key===T5&&t(D5())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let n=(0,K.useCallback)(e=>{t(t=>{if(t[e])return t;let n={...t,[e]:!0};return Txe(n),n})},[]),r=w5.length,i=w5.reduce((t,n)=>t+ +!!e[n],0);return{progress:e,stepsComplete:i,totalSteps:r,isComplete:i===r,mark:n}}function Dxe(){let{mark:e}=Exe();return{onEditNote:(0,K.useCallback)(()=>{e(`editedNote`)},[e]),onRunWorkout:(0,K.useCallback)(()=>{e(`ranWorkout`)},[e]),onLogEffort:(0,K.useCallback)(()=>{e(`loggedEffort`)},[e])}}function Oxe({theme:e,onViewCreated:t,onScrollToSection:n,onSearch:r}){let{id:i}=te(),a=i??`playground`,o=GQ(`playground`,a),s=dt(),{openPeek:c,closePeek:l}=NV(),u=!i||i===`playground`,{content:d,loading:f,entryId:p,entryTitle:m,noteBlocks:h,sourceRevision:g,onIdentityChange:_,onSaved:v,error:y,onChange:b,onLineChange:x,onBlur:S,flush:C,committedSourceRevision:w,resetToOriginal:T}=a6({category:`playground`,name:a,mdContent:A$.content,seedOnMount:u}),E=(0,K.useMemo)(()=>m?Ww(m):i?Ww(i):`Playground`,[m,i]),D=p??o,{onEditNote:O,onRunWorkout:k,onLogEffort:A}=Dxe(),j=(0,K.useCallback)(e=>{O(),b(e)},[O,b]),[M,N]=(0,K.useState)([]),P=(0,K.useCallback)(()=>{X.getSessionsForNote(D).then(e=>N(e.filter(e=>e.completed))).catch(()=>{})},[D]);(0,K.useEffect)(()=>{P()},[P]);let F=(0,K.useRef)(!1),I=(0,K.useRef)(null),ee=(0,K.useCallback)(e=>{if(I.current=e,t?.(e),F.current)return;F.current=!0;let n=Math.min(A$.cursorOffset,e.state.doc.length);e.dispatch({selection:_o.cursor(n)})},[t]),L=(0,K.useCallback)(async e=>{try{await C();let t=Br(),n=await X.getNote(D).catch(()=>void 0)?await Xz(D,e,t,`playground`,{deferPersist:!0}):await Yz({noteId:D,rawContent:d,blocks:h,expectedSourceRevision:w(),metadata:{title:E},noteType:`playground`},e,t,`playground`,void 0,{deferPersist:!0});v({rawContent:n.note.rawContent,blocks:n.note.blocks,sourceRevision:n.note.sourceRevision}),Dz.set(t,{block:n.block,noteId:n.session.noteId,captured:n,origin:`playground`,returnTo:`/playground/${encodeURIComponent(a)}`}),k(),s(DH(t))}catch(e){CQ({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[D,d,h,w,E,a,s,k,C,v]),R=(0,K.useCallback)(async e=>{try{A();let t=await c$({workoutName:E,category:`playground`,sourceNoteLabel:E,sourceNotePath:`/playground/${a}`,wodContent:e.content}),n=Fw(new Date);CQ({title:`Added to journal`,description:t.journalDate===n?`Added to today's journal`:`Added to ${t.journalDate}`,action:{label:`Open`,onAction:()=>s(bH(t.journalDate??n))}})}catch{CQ({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[E,a,s,A]),[z,B]=(0,K.useState)(null),[V,H]=(0,K.useState)(!1),U=(0,K.useCallback)(async e=>{let t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`;try{await Tde(D,t),CQ({title:`Moved to journal`,description:`This playground now lives on ${t}.`,action:{label:`Open`,onAction:()=>s(bH(t))}}),s(SH(D))}catch{CQ({title:`Error`,description:`Could not move to journal`,variant:`destructive`})}},[D,s]),W=(0,K.useCallback)(async(e,t)=>{let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await c$({workoutName:E,category:`playground`,sourceNoteLabel:E,sourceNotePath:`/playground/${a}`,wodContent:e.content,date:t}),s(bH(n)),CQ({title:`Scheduled`,description:`Added to journal for ${n}`,action:{label:`Open`,onAction:()=>s(bH(n))}})}catch{CQ({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[E,a,s]),[ne,re]=(0,K.useState)([]),ie=(0,K.useCallback)(async()=>{try{let e=await T$(d);CQ({title:`Cloned`,description:`A playground copy was created.`}),s(yH(e))}catch{CQ({title:`Error`,description:`Could not clone playground`,variant:`destructive`})}},[d,s]),ae=ne[0]??null,oe=s6({content:d,scriptBlocks:ne,onStartWorkout:e=>{L(e)},results:M,noteId:D,helpfulActions:[...ae?[{id:`run-workout`,label:`Run Workout`,icon:Er,group:`primary`,onRun:()=>void L(ae)}]:[],{id:`move-to-journal`,label:`Move to journal`,icon:ye,testId:Q.L3_PLAYGROUND_MOVE_JOURNAL,group:ae?`organize`:`primary`,onRun:()=>H(!0)},{id:`add-timer`,label:`Add timer`,group:`author`,onRun:()=>j(E$(d))},{id:`clone`,label:`Clone`,group:`organize`,onRun:()=>void ie()},{id:`reset`,label:`Reset to default`,group:`danger`,onRun:()=>void T()}]}),se=(0,K.useMemo)(()=>J3({id:D,type:`playground`}),[D]),ce=se.up??{id:`playgrounds`,title:`Playgrounds`,to:MH()},le=Z3({noteId:D,stamps:se.stamps,liveContent:d,revision:g}),[ue,de]=(0,K.useState)(null);(0,K.useEffect)(()=>{let e=!1;return X.getNote(D).then(t=>{if(e||!t?.sourceId)return;let n=Y3(t.sourceId);n&&de({noteId:D,link:n})}).catch(()=>{}),()=>{e=!0}},[D]);let fe=(0,q.jsx)(R3,{mode:`playground`,currentWorkout:{name:E,content:d},index:[]}),pe=c6(`playground`,{onPlay:e=>{L(e)},onShare:f6,onAddToToday:e=>{R(e)},onSchedule:B}),me=(0,K.useCallback)(e=>{if(e===`scroll-to-workout`){let e=oe.find(e=>e.type===`time`||e.type===`log`);e&&n?.(e.id)}else e===`open-search`&&r?.()},[oe,n,r]),he=(0,K.useCallback)(e=>{let t={id:`code-example-block`,line:0,endLine:e.split(`
|
|
1170
1170
|
`).length,content:e};L(t)},[L]),ge=(0,K.useCallback)(e=>{e.startsWith(`/`)?window.open(e,`_blank`):s(e)},[s]),_e=(0,K.useCallback)((e,t)=>{if(e===`route`&&t.route)s(t.route);else if(e===`start-workout`){let e=ne[0];e&&L(e)}else e===`new-note`&&s(`/playground`)},[s,ne,L]),ve=(0,K.useMemo)(()=>new Map([[`playground-run-tip`,xxe],[`attention`,Sxe(me)],[`code-example`,Cxe(e===`dark`,he)],[`syntax-group`,wxe(ge)]]),[me,he,ge,e]);return(0,K.useEffect)(()=>{document.title=`Wod.Wiki - ${E}`},[E]),f?(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(YY,{parent:ce.to?{label:ce.title,to:ce.to}:null,title:E,actions:fe,editor:(0,q.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,q.jsx)(Q3,{data:le,up:ce,source:ue?.noteId===D?ue.link:null,peekMode:!0,onPeekEntity:c}),(0,q.jsx)(M4,{value:d,onChange:j,onCursorPositionChange:x,onBlur:S,noteId:D,noteBlocks:h,sourceRevision:g,onIdentityChange:e=>_({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:v,beforeRun:async()=>(await C(),w()),onSaveRequest:C,onCommitChange:C,commands:pe,enableInlineRuntime:!1,onViewCreated:ee,theme:e,showLineNumbers:!1,onBlocksChange:re,onButtonAction:_e,onPeekEntity:c,onClosePeek:l,widgetComponents:ve}),y?(0,q.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,y instanceof Error?y.message:String(y),` Your draft is kept.`]}):null,(0,q.jsx)(p5,{noteId:D,blocks:h,sourceRevision:g,onRevert:async e=>{await C();let t=I.current?.state.field(cM);if(!t)throw Error(`The current note editor is unavailable.`);let n=f5({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:w()},e);_({rawContent:n.rawContent,noteBlocks:n.blocks,sourceRevision:n.sourceRevision}),await C()}})]})}),z&&(0,q.jsx)(SD,{open:!0,onClose:()=>B(null),title:`Schedule workout`,children:(0,q.jsx)(i6,{selectedDate:null,onDateSelect:e=>{W(z,e),B(null)}})}),V&&(0,q.jsx)(SD,{open:!0,onClose:()=>H(!1),title:`Move playground to Journal`,description:`Choose a date. This keeps the workout's existing results and attachments.`,children:(0,q.jsx)(i6,{selectedDate:null,onDateSelect:e=>{H(!1),U(e)}})})]})}function kxe({category:e,name:t,mdContent:n,theme:r,runMode:i,hidePlanningCommands:a,onViewCreated:o}){let s=i?i===`inline`:Dde.has(e),c=!Ode[e],l=GQ(e,t),u=dt(),{openPeek:d,closePeek:f}=NV(),[p]=be(),m=p.get(`feed`)??void 0,h=p.get(`remote`)??void 0,[g,_]=(0,K.useState)(null),[v,y]=(0,K.useState)(null),[b,x]=(0,K.useState)(c),[S,C]=(0,K.useState)(!1),[w,T]=(0,K.useState)(null),[E,D]=(0,K.useState)(0),[O,k]=(0,K.useState)([]),[A,j]=(0,K.useState)(!1),{content:M,loading:N,entryId:P,noteBlocks:F,sourceRevision:I,onIdentityChange:ee,onSaved:L,error:R,onChange:z,onLineChange:B,onBlur:V,flush:H,committedSourceRevision:U}=a6({category:e,name:t,mdContent:n,seedOnMount:!c});(0,K.useEffect)(()=>{if(!c){_(null),y(null),T(null),C(!1),x(!1);return}let r=!1;return x(!0),_(null),y(null),T(null),(async()=>{try{let i=h??l,a=await X.getNote(i).catch(()=>void 0);if(r)return;if(a){_(a),y(null);return}let o=await X.getAllNotes().catch(()=>[]);if(r)return;let s=Cs(e),c=o.find(n=>n.id===h||n.sourceId===`notebook:${e}/${t}`||n.notebookIds?.includes(s)&&n.title?.toLowerCase()===t.toLowerCase());if(c){_(c),y(null);return}if(n&&n.trim().length>0)return;let u=await BL.getRemoteNotebookNotes(e,m).catch(()=>[]);if(r)return;let d=u.find(e=>{let n=SC(e.id),r=n.isRemote?n.uuid:e.id;return h&&(r===h||e.id===h)||e.title.toLowerCase()===t.toLowerCase()||e.sourceId?.toLowerCase().endsWith(`/${t.toLowerCase()}`)||e.sourcePath?.toLowerCase().includes(`/${t.toLowerCase()}.`)}),f=h&&m?`remote:${m}:${h}`:d?d.id:h;if(!f)return;C(!0);try{let e=await ML(f,{storage:X.storage,...m?{feedId:m}:{}});if(r)return;e?(y(e),_(e.note)):T(`This workout could not be fetched from its feed.`)}catch(e){r||T(e instanceof Error?e.message:`Unable to fetch workout from feed.`)}finally{r||C(!1)}}finally{r||x(!1)}})(),()=>{r=!0}},[c,h,m,l,e,t,n,E]);let te=v?.note.rawContent??g?.rawContent??M,W=v?.note.blocks??g?.blocks??F,ne=v?.note.sourceRevision??g?.sourceRevision??I,re=v?.note.title||g?.title||t,ie=v?.canonicalNoteId??g?.id??P??l,ae=v?.remoteNoteId??ie;(0,K.useEffect)(()=>{k([]);let e=()=>{X.getSessionsForNote(ie).then(k).catch(()=>{})};e();let t=mR(t=>{t.noteId===ie&&e()});return()=>{t()}},[ie]);let oe=(0,K.useMemo)(()=>{let t=v?.note??g;return e$(t,{noteId:ae,notebookOrigin:t?Wy(t):m?`feed`:void 0,resolvedNotebookId:c?Cs(e):void 0,fallbackReadOnly:c})},[v?.note,g,ae,m,c,e]),se=(0,K.useCallback)(()=>async t=>{let n=await ML(t,{storage:X.storage,...m?{feedId:m}:{}}).catch(()=>void 0);if(!n)return;let r=DL(t);return{...n.note?{note:n.note}:{},row:n.row,canonicalNoteId:n.canonicalNoteId,remoteNoteId:n.remoteNoteId,feedId:n.feedId,notebookSlug:r?.notebookSlug??e,record:r?.record}},[m,e]),ce=(0,K.useMemo)(()=>c?{label:`${e}-${t}`,path:TH(e,t)}:null,[e,c,t]),[le,ue]=(0,K.useState)(null),de=(0,K.useCallback)(async n=>{let r=Br();if(s||!c){try{await H();let e=await Yz({noteId:ie,rawContent:te,blocks:W,expectedSourceRevision:U(),metadata:{title:re},noteType:`playground`},n,r,void 0,void 0,{deferPersist:!0});L({rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision}),Dz.set(r,{block:e.block,noteId:e.session.noteId,captured:e}),u(DH(r))}catch(e){CQ({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}return}try{let i=se();if(g||v){let a=await Xz(ae,n,r,`journal`,{resolveRemoteWorkout:i}),o=await X.getNote(a.note.id).catch(()=>void 0);o&&_(o),Dz.set(r,{block:a.block,noteId:a.note.id,captured:a,returnTo:TH(e,t)}),u(DH(a.session.id));return}let a=await Yz({noteId:ie,rawContent:te,blocks:W,expectedSourceRevision:ne,metadata:{title:re}},n,r,`journal`,void 0,{deferPersist:!0});Dz.set(r,{block:a.block,noteId:a.note.id,captured:a,returnTo:TH(e,t)}),u(DH(a.session.id))}catch(e){CQ({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[s,c,ie,ae,te,W,ne,re,g,v,se,t,e,u,H,U,L]),fe=(0,K.useCallback)(async(n,r)=>{let i=jw(r),a;try{a=(await c$({workoutName:re,category:e,sourceNoteId:ae,sourceNoteLabel:oe.feedLabel??ce?.label,sourceNotePath:ce?.path,wodContent:n.content,date:r,wrapInWod:!0,resolveRemoteWorkout:se()})).journalDate??``}catch{CQ({variant:`destructive`,title:`Could not save workout`,description:`Failed to add "${t}" to ${i}. Please try again.`});return}u(bH(a));let o=bH(a);CQ({title:`Added to ${i}`,description:`"${re}" was added to your journal.`,action:{label:`View Note`,onAction:()=>u(o)},duration:7e3})},[re,e,ae,oe.feedLabel,se,ce,u]),pe=c6(`notebook-readonly`,{onPlay:e=>{de(e)},onShare:f6,onAddToToday:a?void 0:e=>{fe(e,new Date)},onSchedule:a?void 0:ue,onOpenInPlayground:e=>{d6(e,u)}}),[me,he]=(0,K.useState)([]),ge=(0,K.useCallback)(()=>{u(SH(l))},[u,l]),_e=(0,K.useMemo)(()=>me.find(e=>e.dialect===`time`||e.dialect===`log`)??null,[me]),ve=(0,K.useMemo)(()=>{let e=c?[]:[{id:`add-timer`,label:`Add timer`,onRun:()=>z(E$(te))}];return _e?[...e,...a?[]:[{id:`add-to-today`,label:`Add to today`,onRun:()=>void fe(_e,new Date)},{id:`plan`,label:`Plan for a date`,onRun:()=>ue(_e)}],{id:`open-in-playground`,label:`Open in playground`,onRun:()=>void d6(_e,u)}]:e},[c,_e,te,a,fe,u,z]);s6({content:te,scriptBlocks:me,onStartWorkout:e=>{de(e)},onEditNote:c?ge:void 0,noteId:ie,helpfulActions:ve});let ye=(0,K.useMemo)(()=>c?J3({id:l,type:`note`}):null,[c,l]),xe=Z3({noteId:l,stamps:ye?.stamps??[],liveContent:c?te:void 0,revision:ne}),Se=(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(lX,{}),(0,q.jsx)(R3,{mode:`notebook-readonly`,currentWorkout:{name:re,content:te},index:[]})]}),Ce=c||oe.isNonOwned?(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border bg-card/60 px-3 py-2`,children:[(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 min-w-0`,children:[(0,q.jsx)(i$,{presentation:oe}),(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:oe.guidanceCopy})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 shrink-0`,children:[_e&&(0,q.jsxs)(J,{type:`button`,size:`sm`,onClick:()=>void de(_e),className:`h-8 gap-1.5 px-3 text-xs`,children:[(0,q.jsx)(Er,{className:`size-3.5`,"aria-hidden":`true`}),`Start / Log Workout`]}),(0,q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>j(!0),className:`h-8 gap-1.5 px-3 text-xs`,children:[(0,q.jsx)(Pe,{className:`size-3.5`,"aria-hidden":`true`}),`Fork to My Notes`]})]})]}):null;return N||b||S?(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-sm text-muted-foreground`,role:`status`,children:S?`Loading workout from feed…`:`Loading…`}):w||c&&!te.trim()?(0,q.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 px-4 text-center`,role:`alert`,children:[(0,q.jsx)(`p`,{className:`text-sm font-semibold text-foreground`,children:`Workout unavailable`}),(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:w??`Could not find "${t}" in notebook "${e}".`}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsxs)(J,{variant:`default`,size:`sm`,onClick:()=>D(e=>e+1),className:`gap-1.5`,children:[(0,q.jsx)(pi,{className:`size-3.5`,"aria-hidden":`true`}),`Retry`]}),(0,q.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>u(`/feeds`),children:`Browse feeds`})]})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(YY,{title:re,actions:Se,editor:(0,q.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,q.jsx)(Q3,{data:xe,up:ye?.up,peekMode:!0,onPeekEntity:d}),Ce,(0,q.jsx)(M4,{value:te,onChange:c?()=>{}:z,...!c&&s?{onCursorPositionChange:B,onBlur:V,onIdentityChange:e=>ee({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:L,beforeRun:async()=>(await H(),U()),onSaveRequest:H,onCommitChange:H}:{},noteId:ie,noteBlocks:W,sourceRevision:ne,readonly:!0,enableInlineRuntime:s,commands:pe,onViewCreated:o,theme:r,showLineNumbers:!1,onBlocksChange:he,onPeekEntity:d,onClosePeek:f},ie),R?(0,q.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,R instanceof Error?R.message:String(R),` Your draft is kept.`]}):null,(0,q.jsx)(r$,{sessions:O})]})}),(0,q.jsx)(n$,{open:A,onOpenChange:j,sourceNoteId:ae,sourceTitle:re,storageInstance:X.storage,resolveRemoteWorkoutFn:se(),fallbackRemote:!g&&te?{title:re,content:te,feedId:m,notebookSlug:e}:void 0,onForked:e=>{u(`${SH(e.id)}?edit=1`)}}),le&&(0,q.jsx)(SD,{open:!0,onClose:()=>ue(null),title:`Schedule ${t}`,children:(0,q.jsx)(i6,{selectedDate:null,onDateSelect:e=>{e&&fe(le,e),ue(null)}})})]})}function Axe(e,t){let{effort:n,errors:r}=Ld(e,t);return{item:n,errors:r}}function jxe(e,t){return{...e,derivation:{parentSlug:t.slug,coefficients:{},hardOverrides:{}}}}function Mxe(e){let{registry:t,isReady:n,revision:r,refresh:i}=CV(),{item:a,...o}=x$({kind:`effort`,slug:e,isReady:n,revision:r,resolveDirect:(0,K.useCallback)(e=>t.resolve(e),[t]),resolveByAlias:(0,K.useCallback)(e=>t.resolveByAlias(e),[t]),toDocument:Rd,fromDocument:Axe,applyCloneFields:jxe,refresh:i});return{...o,effort:a}}function O5({open:e,onOpenChange:t,kind:n,slug:r,label:i,rawContent:a,storageOverride:o,onSaved:s}){let c=o??YP,[l,u]=(0,K.useState)([]),[d,f]=(0,K.useState)(!1),[p,m]=(0,K.useState)(``),[h,g]=(0,K.useState)(!1),_=(0,K.useCallback)(async()=>{try{let[e,t]=await Promise.all([c.readonly(`notes`).getAll(),uS(c,{kind:n,slug:r})]),i=new Set(t.map(e=>e.notebookId));f(i.has(`notebook/custom`));let a=[];for(let t of e)if(xc(t)||t.id.startsWith(`notebook/`)&&t.type===`notebook`&&!xs(t.id)&&t.feedOrigin!==`feed`&&t.seedOrigin!==`seed`){let e=Cs(t.id);a.push({id:e,slug:Ss(e),title:t.title||Ss(e),hasExistingOverride:i.has(e)})}u(a)}catch{}},[c,n,r]);(0,K.useEffect)(()=>{e&&_()},[e,_]);let v=async e=>{if(!h){g(!0);try{await lS(c,{targetNotebookId:e,kind:n,slug:r,rawContent:a,title:i}),CQ({title:`Override saved`,description:e===`notebook/custom`?`Saved '${r}' to your personal Custom runtime.`:`Scoped '${r}' override to ${e}.`}),s?.(e),t(!1)}catch(e){CQ({title:`Could not save override`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(!1)}}},y=async e=>{e.preventDefault();let t=p.trim();if(!(!t||h)){g(!0);try{let e=await VS(c,t);m(``),g(!1),await v(e)}catch(e){g(!1),CQ({title:`Could not create Notebook`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}}};return(0,q.jsxs)(Fr,{open:e,onOpenChange:t,children:[(0,q.jsx)(We,{className:`bg-black/30`}),(0,q.jsxs)(lt,{initialFocus:`content`,"aria-label":`Override ${i}`,"data-testid":`property-override-sheet`,className:`w-full lg:max-w-md max-h-[85dvh] overflow-y-auto rounded-t-xl border border-border bg-card text-foreground p-5 sm:p-6 space-y-5`,children:[(0,q.jsx)(`div`,{"aria-hidden":`true`,className:`mx-auto h-1 w-10 rounded-full bg-border lg:hidden`}),(0,q.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-border pb-3.5`,children:[(0,q.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,q.jsxs)(ve,{className:`text-sm font-semibold tracking-tight`,children:[`Override `,i]}),(0,q.jsxs)(H,{className:`font-mono text-[11px] text-muted-foreground`,children:[`Canonical slug: `,r]})]}),(0,q.jsx)(Xe,{"aria-label":`Close override sheet`,className:`min-h-9 min-w-9 h-auto w-auto p-0 inline-flex items-center justify-center rounded-md border border-border bg-transparent text-xs font-mono text-muted-foreground hover:text-foreground`,children:(0,q.jsx)(ze,{className:`size-3.5`,"aria-hidden":`true`})})]}),(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(`span`,{className:`font-mono text-[11px] uppercase tracking-wider text-muted-foreground`,children:`Personal Runtime`}),(0,q.jsxs)(`button`,{type:`button`,disabled:h,onClick:()=>void v(`notebook/custom`),"data-testid":`override-target-notebook/custom`,className:`w-full min-h-12 text-left rounded-lg border border-border bg-muted/30 hover:border-foreground p-3.5 transition-colors flex items-center justify-between gap-3`,children:[(0,q.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,q.jsx)(`div`,{className:`text-xs font-semibold`,children:`My Custom Runtime (notebook/custom)`}),(0,q.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:`Processes workouts in your personal runtime using this definition on the same canonical slug.`})]}),d&&(0,q.jsx)(`span`,{className:`shrink-0 rounded-full bg-success/15 text-success px-2.5 py-0.5 font-mono text-[10px] uppercase tracking-wider`,children:`Active`})]})]}),(0,q.jsxs)(`div`,{className:`space-y-2 border-t border-border pt-4`,children:[(0,q.jsx)(`span`,{className:`font-mono text-[11px] uppercase tracking-wider text-muted-foreground`,children:`Shared User Notebooks (Promoted on Publish)`}),l.length>0&&(0,q.jsx)(`div`,{className:`space-y-1.5`,children:l.map(e=>(0,q.jsxs)(`button`,{type:`button`,disabled:h,onClick:()=>void v(e.id),"data-testid":`override-target-${e.id}`,className:`w-full min-h-11 text-left rounded-lg border border-border hover:border-foreground px-3.5 py-2.5 transition-colors flex items-center justify-between gap-3 text-xs`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`div`,{className:`font-medium`,children:e.title}),(0,q.jsxs)(`div`,{className:`font-mono text-[10px] text-muted-foreground`,children:[`notebook/`,e.slug]})]}),e.hasExistingOverride&&(0,q.jsx)(`span`,{className:`rounded-full bg-primary/10 text-primary px-2.5 py-0.5 font-mono text-[11px] uppercase tracking-wider`,children:`Overridden`})]},e.id))}),(0,q.jsxs)(`form`,{onSubmit:e=>void y(e),className:`flex items-center gap-2 pt-1`,children:[(0,q.jsx)(Eo,{type:`text`,value:p,onValueChange:m,placeholder:`Override in new Notebook...`,"aria-label":`New shared Notebook name`,"data-testid":`override-new-notebook-input`,className:`min-h-11 h-11 flex-1 text-xs`}),(0,q.jsx)(J,{type:`submit`,disabled:h||!p.trim(),"data-testid":`override-new-notebook-submit`,className:`min-h-11 px-3.5 text-xs`,children:`Save`})]})]})]})]})}function Nxe({resolved:e,effort:t}){return(0,q.jsxs)(`div`,{className:`my-6 p-4 border rounded-lg bg-muted/30 space-y-4`,children:[(0,q.jsxs)(`h3`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,q.jsx)(ni,{className:`size-4`}),`Effective Resolution`]}),(0,q.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Effective MET`}),(0,q.jsx)(`p`,{className:`text-xl font-bold`,children:e.met.toFixed(1)}),Math.abs(e.met-(t.baseAttributes.met||0))>.01&&(0,q.jsxs)(`span`,{className:`text-xs text-amber-600 dark:text-amber-400`,children:[`(base: `,t.baseAttributes.met.toFixed(1),`)`]})]}),(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Discipline Factor`}),(0,q.jsxs)(`p`,{className:`text-xl font-bold`,children:[e.disciplineFactor.toFixed(2),`×`]})]})]}),Object.keys(e.modifiers).length>0&&(0,q.jsxs)(`div`,{className:`border-t pt-3`,children:[(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-2`,children:`Applied Modifiers`}),(0,q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Object.entries(e.modifiers).map(([e,t])=>(0,q.jsxs)(To,{variant:`outline`,children:[e,`: `,t]},e))})]}),e.definition.derivation?.parentSlug&&(0,q.jsxs)(`div`,{className:`border-t pt-3 text-sm`,children:[(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-1`,children:`Parent`}),(0,q.jsx)(`span`,{className:`font-mono text-primary`,children:e.definition.derivation.parentSlug})]})]})}function Pxe(){let{slug:e,tag:t}=te(),n=e??t,[i]=be(),a=dt(),{theme:o}=So(),s=o===`dark`?`dark`:`vs`,{registry:c,isReady:l,revision:u,refresh:d}=CV(),{document:f,setDocument:p,isLoading:m,effort:h,isEditable:g,notFound:_,remove:v,cloneForEdit:y,error:b,onLineChange:x,onBlur:S,flush:C}=Mxe(n),w=i.get(`notebook`)?.trim()??``,T=(0,K.useMemo)(()=>{if(!w)return null;let e=Cs(w);return e===`notebook/custom`?null:e},[w]),[E,D]=(0,K.useState)(``),[O,k]=(0,K.useState)(null),[A,j]=(0,K.useState)(null),M=T&&n?`${T}::${n}`:null,N=!!(M&&O!==M);(0,K.useEffect)(()=>{if(!T||!n||!M){k(null),j(null);return}let e=!1;return uS(X.storage,{notebookId:T,kind:`effort`,slug:n}).then(t=>{if(e)return;let r=t[0];r?(D(r.rawContent),j(r.ownerNoteId),k(M)):f&&(D(f),j(`override/${Ss(T)}/effort/${n}`),k(M))}).catch(()=>{e||k(M)}),()=>{e=!0}},[T,n,M,f]);let{onChange:P,onLineChange:F,onBlur:I,flush:ee}=v$({onSave:(0,K.useCallback)(async e=>{if(!T||!h||!e.trim())return;let{effort:t,errors:n}=Ld(e,h);if(n.length>0){CQ({title:`Invalid YAML`,description:n.join(`
|
|
1171
1171
|
`),variant:`destructive`});return}let r=await lS(X.storage,{targetNotebookId:T,kind:`effort`,slug:h.slug,rawContent:e,title:t.label.trim()||h.label});j(r.ownerNoteId)},[T,h])}),L=(0,K.useCallback)(e=>{D(e),P(e)},[P]),[R,z]=(0,K.useState)(!1),[B,V]=(0,K.useState)(!1),[H,U]=(0,K.useState)(null),W=(0,K.useRef)(!1),ne=T?E:f,re=T?L:p,ie=T?F:x,ae=(0,K.useCallback)(()=>{W.current||(T?I():S())},[T,I,S]),oe=(0,K.useCallback)(()=>W.current?Promise.resolve():T?ee():C(),[T,ee,C]),se=!!T||g,ce=(0,K.useCallback)(async()=>{if(!(!h||B)){V(!0),U(null),W.current=!0;try{if(T){let e=sS(T,`effort`,h.slug),t=A??`override/${Ss(T)}/effort/${h.slug}`;await X.storage.transaction([`notes`,`property_overrides`],`readwrite`,async n=>{await n.readwrite(`property_overrides`).delete(e),await n.readwrite(`notes`).delete(t)}),await d(),z(!1),CQ({title:`Override deleted`,description:`Removed the ${Ss(T)} override for "${h.label}".`}),a(BH(h.slug),{replace:!0});return}if(h.sourceId===`notebook/custom`||h.ownerNoteId?.startsWith(`override/`)){let e=sS(`notebook/custom`,`effort`,h.slug),t=h.ownerNoteId??`override/custom/effort/${h.slug}`;await X.storage.transaction([`notes`,`property_overrides`],`readwrite`,async n=>{await n.readwrite(`property_overrides`).delete(e),await n.readwrite(`notes`).delete(t)}),await d()}else await v();z(!1),CQ({title:`Effort deleted`,description:`Deleted custom effort "${h.label}".`}),a(NH(),{replace:!0})}catch(e){W.current=!1,U(e instanceof Error?e.message:`Failed to delete effort.`)}finally{V(!1)}}},[h,B,T,A,d,v,a]),le=(0,K.useRef)(h?.slug);(0,K.useEffect)(()=>{let e=le.current;h&&e&&h.slug!==e&&h.registrySource===`user`&&a(BH(h.slug)),le.current=h?.slug},[h,a]);let[ue,de]=(0,K.useState)([]),[fe]=(0,K.useState)([]),[pe,me]=(0,K.useState)(null),[he,ge]=(0,K.useState)(!1),[_e,ve]=(0,K.useState)(!1),[ye,xe]=(0,K.useState)(!1),Se=(0,K.useMemo)(()=>n?zb({kind:`effort`,slug:n,label:h?.label??n}):null,[n,h?.label]),Ce=VH(i).mode===`create`||n===`new`,we=(0,K.useCallback)(e=>{let t=e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``,n=t?wP(t):``;return`${Rd({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()})}\n\n`},[]),[Te,Ee]=(0,K.useState)(()=>we(n)),G=(0,K.useRef)(Te),De=(0,K.useRef)(null),Oe=(0,K.useRef)(n);(0,K.useEffect)(()=>{if(!Ce){De.current=null;return}if(Oe.current!==n){Oe.current=n;let e=we(n);G.current=e,Ee(e)}},[Ce,n,we]);let ke=(0,K.useCallback)(e=>{G.current=e,Ee(e)},[]),[Ae,je]=(0,K.useState)(!1),[Ne,Pe]=(0,K.useState)(``),{isSettling:Fe}=_$({loading:m||N,missing:!h&&!b&&_}),Ie=(0,K.useMemo)(()=>c?[...c.list()].sort((e,t)=>e.label.localeCompare(t.label)):[],[c,u]),Le=(0,K.useCallback)(async()=>{if(!(!n||!Ne||!c))try{await $d(c,Ne,n),await d(),CQ({title:`Alias Linked`,description:`Linked "${n}" as an alias to ${Ne}.`}),a(BH(Ne))}catch(e){CQ({title:`Failed to link alias`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[n,Ne,c,d,a]),Re=(0,K.useCallback)(async()=>{let e=De.current?.state.doc.toString()??G.current,{effort:t,errors:n}=Ld(e);if(n.length>0){CQ({title:`Invalid YAML`,description:n.join(`
|
|
@@ -1197,7 +1197,7 @@ segmentVolume = reps * resistance (library) when has(reps) and has(resistance)
|
|
|
1197
1197
|
5 Burpees
|
|
1198
1198
|
rest 1:00`,docsPath:t?.docsPath??`/page/guide-protocols?h=required-rest`},{category:`Structure`,icon:`🏋️`,title:`Rep Schemes`,description:n?.subtitle??`Rep counts per movement.`,example:n?.workout??`21-15-9
|
|
1199
1199
|
Thrusters`,docsPath:n?.docsPath??`/page/guide-structure?h=rep-schemes`}]},[a]),l=(0,K.useMemo)(()=>t===`dark`||t!==`light`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches,[t]),u=Oq(),d=(0,K.useCallback)(async()=>{let t=await jQ.getState().open({wql:{initialQuery:e1(),execute:n1,preferredChoices:t1()},sources:[Q$(),$$(ZQ(u))]});t.dismissed||r1(t.item,t=>{e(t)})},[e,u]),f=(0,K.useCallback)(e=>{if(e===`scroll-to-workout`){r.current?.scrollIntoView({behavior:`smooth`,block:`start`});return}e===`open-search`&&d()},[d]),p=(0,K.useCallback)(async t=>{let n=await T$([`# Playground Widget Example`,``,"```time",t,"```",``,`[▶ Run Workout]{.button action=start-workout}`,``].join(`
|
|
1200
|
-
`));e(yH(n))},[e]),m=(0,K.useCallback)(t=>{if(/^https?:\/\//i.test(t)){window.open(t,`_blank`,`noopener,noreferrer`);return}e(t)},[e]);return(0,q.jsxs)(twe,{actionsSlot:(0,q.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,q.jsx)(fn,{className:`size-4 text-zinc-500`,"aria-hidden":`true`}),(0,q.jsx)(un,{checked:l,onCheckedChange:e=>n(e?`dark`:`light`),"aria-label":`Toggle dark mode`,children:(0,q.jsx)(Cn,{})}),(0,q.jsx)(zt,{className:`size-4 text-zinc-500`,"aria-hidden":`true`})]}),heroSlot:(0,q.jsx)(x5,{config:nwe,onAction:f}),children:[(0,q.jsxs)(`section`,{ref:r,id:`workout-widget-surface`,className:`mt-8 grid grid-cols-1 gap-4 xl:grid-cols-3`,children:[(0,q.jsx)(`div`,{className:`xl:col-span-2`,children:(0,q.jsx)(S5,{config:s,isDarkMode:l,onRun:p})}),(0,q.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,q.jsx)(C5,{config:e,onOpenDocs:m},e.title))})]}),(0,q.jsx)(j6,{})]})}function _9(e){let[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)({});(0,K.useEffect)(()=>{i(Y0()),n(!0);let e=e=>{e.key===`wodwiki.quests.v1`&&i(Y0())};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 iwe({activeIndex:e,onCommand:t,captions:n}){return(0,q.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`tour-captions`,children:n.map((n,r)=>(0,q.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,q.jsx)(awe,{cap:n,onCommand:t})},n.id))})}function awe({cap:e,onCommand:t}){return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`h3`,{className:`mb-3.5 xl:mb-5 text-[clamp(22px,2vw,32px)] font-extrabold leading-[1.12] tracking-[-0.03em]`,children:[(0,q.jsx)(`span`,{className:`mr-2 align-[0.2em] font-mono text-[0.5em] font-semibold tracking-[0.08em] text-muted-foreground`,children:e.num}),e.title]}),(0,q.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,q.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,q.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,q.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,q.jsx)(`span`,{children:e})]},t))}),e.foot&&(0,q.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`,children:e.foot}),e.extra&&(0,q.jsx)(`div`,{className:`mt-3`,children:e.extra}),e.commands&&e.commands.length>0&&t&&(0,q.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,q.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,q.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,q.jsx)(M,{to:e.href,onClick:()=>$R.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 owe({visible:e,children:t}){return(0,q.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 swe=(0,K.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,K.useRef)(null),f=(0,K.useRef)(null),[p,m]=(0,K.useState)(null),h=(0,K.useCallback)(e=>{f.current=e,m(e)},[]),{slice:g,subscribe:_,resync:v,runwayReached:y}=X4(d,!1,r,e),b=lwe(d);(0,K.useEffect)(()=>{o?.(b)},[b,o]),(0,K.useEffect)(()=>{s?.(y)},[y,s]);let[x,S]=(0,K.useState)(!1),C=cwe(d);(0,K.useEffect)(()=>{(C||y)&&S(!0)},[C,y]);let w=g.stage?.screen??`editor`,T=(0,K.useRef)(null);return(0,K.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,K.useImperativeHandle)(u,()=>({scrollToStage:e=>{let t=d.current,n=r.find(t=>t.id===e);!t||!n||jge(t,Math.min(n.range[0]+.02,n.range[1]-.005))},subscribe:_,resync:v}),[r,_,v]),(0,q.jsxs)(`section`,{id:`tour-section-${e}`,"data-testid":`tour-section-${e}`,children:[n,(0,q.jsx)(Y4,{trackRef:d,height:t,stages:r,activeIndex:g.index,segmentId:e,testId:`tour-runway`,pane:(0,q.jsx)(`div`,{ref:h,className:`absolute inset-0 flex flex-col justify-center`,children:(0,q.jsxs)(y6,{children:[(0,q.jsx)(Hve,{ringKey:`editor.window`,el:p}),(0,q.jsx)(r2,{title:__e[w],className:`relative h-full max-h-[760px]`,children:(0,q.jsx)(J4,{gateId:`${e}-pane`,segmentId:e,className:`relative h-full`,children:l&&(0,q.jsx)(owe,{visible:w===`editor`,children:(0,q.jsx)(M6,{doc:l.doc,onDocChange:l.onDocChange,onBlocksChange:l.onBlocksChange,onRun:l.onRun,theme:l.theme,withRingTargets:!0})})})}),(0,q.jsx)(Uve,{target:g.ring?.key?{key:g.ring.key}:null,accent:g.stage.accent??w3.editor,canvasRef:f})]})}),captions:(0,q.jsx)(iwe,{activeIndex:g.index,captions:i,onCommand:c})})]})});function cwe(e){let[t,n]=(0,K.useState)(!1);return(0,K.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 lwe(e){let[t,n]=(0,K.useState)(()=>typeof IntersectionObserver>`u`);return(0,K.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 uwe={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`},v9={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`]}},dwe=[{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 fwe({chapters:e=[],allQuests:t=[],theme:n,wodFiles:r={},onRun:i}){let a=(0,K.useMemo)(()=>{let t=(e??[]).filter(e=>e.id!==`home-tour`);return t.length>0?t:dwe},[e]),o=t2(`(prefers-reduced-motion: reduce)`),{markComplete:s}=Q0(`/`,t),{chapters:c}=_9(a),[l,u]=(0,K.useState)(()=>a[0]?.id??`basics`),[d,f]=(0,K.useState)(``),p=(0,K.useRef)([]),m=(0,K.useRef)(l);m.current=l;let h=(0,K.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,fY(uwe[e.id]??``,r)])),[a,r]);(0,K.useEffect)(()=>{p.current=[],f(h[l]??``)},[l,h]);let g=(0,K.useCallback)(e=>{p.current=e},[]),_=(0,K.useCallback)(()=>{let e=m.current;s(`${e}-run`),i?.(e,p.current[0]??null,d)},[d,s,i]),v=(0,K.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,K.useMemo)(()=>Object.fromEntries(c.map(e=>[e.chapter.id,e])),[c]),b=(0,K.useMemo)(()=>a.map((e,t)=>{let n=v9[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,q.jsx)(`span`,{"data-testid":`chapter-picker-progress-${e.id}`,className:$(`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:T3[e.id]??`/page/guide-start`,event:ez.chapterGuideClicked,data:{chapter:e.id},testId:`chapter-picker-guide-${e.id}`}]}}),[a,y]);return(0,q.jsxs)(`section`,{id:`tour-chapter-picker`,"data-testid":`tour-chapter-picker`,className:`flex flex-col`,children:[(0,q.jsx)(S3,{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,q.jsx)(pwe,{chapters:a,selectedId:l,onSelect:u,doc:d,onDocChange:f,theme:n,onBlocksChange:g,onRun:_,progressByChapter:y}):(0,q.jsx)(swe,{id:`learn`,heightVh:`600vh`,stages:v,captions:b,onActiveStageChange:u,editor:{doc:d,theme:n,onDocChange:f,onBlocksChange:g,onRun:_}})]})}function pwe({chapters:e,selectedId:t,onSelect:n,doc:r,onDocChange:i,theme:a,onBlocksChange:o,onRun:s,progressByChapter:c}){return(0,q.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,q.jsxs)(`div`,{className:`flex flex-col gap-10 lg:flex-row lg:items-start lg:gap-12 xl:gap-16`,children:[(0,q.jsx)(`div`,{className:`w-full lg:w-[58%] xl:w-[60%] lg:sticky lg:top-[110px] z-10 flex-none`,children:(0,q.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,q.jsx)(r2,{title:T3[t]?.split(`/`).pop()??`example.md`,subtitle:`Lesson: ${e.find(e=>e.id===t)?.title??t}`,className:`h-full`,children:(0,q.jsx)(M6,{doc:r,onDocChange:i,onBlocksChange:o,onRun:s,theme:a,withRingTargets:!1})})})}),(0,q.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=v3(e.badge),o=e.id===t,s=v9[e.id];return(0,q.jsxs)(`div`,{"data-testid":`chapter-picker-row-${e.id}`,className:$(`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,q.jsxs)(`div`,{children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsxs)(`span`,{className:`font-mono text-xs font-bold uppercase tracking-wider text-primary`,children:[`Chapter 0`,r+1]}),a&&(0,q.jsx)(a,{className:`size-4 text-primary`})]}),(0,q.jsx)(`span`,{className:$(`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,q.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground sm:text-3xl`,children:e.title}),(0,q.jsx)(`p`,{className:`mt-3 text-sm sm:text-base leading-relaxed text-muted-foreground`,children:s?.summary??e.title}),s?.bullets&&(0,q.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,q.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,q.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,q.jsx)(`span`,{children:e})]},t))})]}),(0,q.jsxs)(`div`,{className:`mt-6 flex flex-wrap items-center gap-3 pt-4 border-t border-border/50`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>n(e.id),"data-testid":`chapter-picker-select-${e.id}`,"aria-pressed":o,className:$(`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,q.jsx)(Er,{className:`size-3.5 fill-current`}),(0,q.jsx)(`span`,{children:o?`Loaded in editor`:`Load example`})]}),(0,q.jsxs)(M,{to:T3[e.id]??`/page/guide-start`,"data-testid":`chapter-picker-guide-${e.id}`,"aria-label":`Read guide for ${e.title}`,onClick:()=>$R.record(ez.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,q.jsx)(fe,{className:`size-3.5`}),(0,q.jsx)(`span`,{children:`Read guide →`})]})]})]},e.id)})})]})})}function mwe({chapters:e}){let t=()=>$R.record(ez.lessonStarted),n=()=>$R.record(ez.cheatsheetOpened),{chapters:r}=_9(e),i=r.filter(e=>e.chapter.id!==`home-tour`);return(0,q.jsxs)(`section`,{"data-testid":`tour-learn`,className:`mx-auto max-w-5xl px-6 py-16 border-b border-border/60`,children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-bold tracking-tight`,children:`Learn the Language`}),(0,q.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,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,q.jsx)(M,{to:`/page/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,q.jsx)(M,{to:`/page/guide-start?h=reference`,onClick:n,className:`text-sm font-semibold text-primary underline-offset-2 hover:underline`,children:`Cheat sheet →`})]})]}),(0,q.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=T3[e.id]??`/page/guide-start`,a=v3(e.badge);return(0,q.jsxs)(M,{to:i,"data-testid":`learn-progress-chip-${e.id}`,className:$(`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,q.jsx)(a,{className:`size-3.5 text-muted-foreground`}),(0,q.jsx)(`span`,{className:`text-[12px] font-semibold text-foreground`,children:e.title}),(0,q.jsx)(`span`,{className:$(`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 hwe=mwe;function gwe(){let e=HP(),t=(0,K.useMemo)(()=>h6(e??{}),[e]),{theme:n}=So(),[r,i]=(0,K.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches);(0,K.useEffect)(()=>{if(n!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>i(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[n]);let a=(0,K.useMemo)(()=>n===`system`?r?`vs-dark`:`vs`:n===`dark`?`vs-dark`:`vs`,[n,r]),o=Oq(),s=m6.chapters,c=m6.quests,l=(0,K.useMemo)(()=>{let e={};for(let t of m6.quests)e[t.id]=t.label;for(let{page:t}of o)for(let n of t.quests)e[n.id]=n.label;return e},[o]),u=tz()?.track,{run:d,start:f,finalize:p,end:m}=K0(),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(0),[y,b]=(0,K.useState)(!1),x=(0,K.useCallback)(()=>{g(null),b(!1)},[]),S=(0,K.useCallback)(async(e,t,n)=>{if(t){u?.(ez.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(),CQ({title:`Could not start workout`,variant:`destructive`})}}},[x,f,u]),C=(0,K.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),CQ({title:`Session not saved`,variant:`destructive`}),e}},[x,m,p]);return(0,q.jsx)(y6,{children:(0,q.jsxs)(`div`,{"data-testid":`syntax-view`,children:[(0,q.jsx)(S3,{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,q.jsx)(fwe,{wodFiles:t,chapters:s,allQuests:c,theme:a,onRun:S}),(0,q.jsx)(hwe,{quests:c,chapters:s,questLabels:l}),(0,q.jsx)(D3,{}),(0,q.jsx)(w6,{}),h&&y&&d&&(0,q.jsx)(z2,{block:d.block,resultId:d.resultId,autoStart:!0,onClose:x,onCompleteWorkout:C},_)]})})}function _we(){let e=dt();return(0,q.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Not found navigation`,className:`flex items-center gap-5 px-6 py-3 border-b bg-background`,children:[(0,q.jsx)(`span`,{className:`text-sm font-semibold tracking-tight`,children:`WOD Wiki`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-home`,onClick:()=>e(`/`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Home`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-journal`,onClick:()=>e(`/journal`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Journal`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-notebooks`,onClick:()=>e(`/notebooks`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`})]}),(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`flex-1 flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,q.jsx)(Ri,{className:`w-8 h-8 text-muted-foreground`})}),(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Page not found`}),(0,q.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`The page you are looking for does not exist or has been moved.`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`notfound-go-home`,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,q.jsx)(da,{className:`w-4 h-4`}),`Go home`]})]})]})}function vwe(){return(0,q.jsx)(at,{to:`/sessions?q=%3Asegment%7B%7D%20last%208w`,replace:!0})}function ywe(){let{runtimeId:e}=te();return(0,q.jsx)(at,{to:DH(e),replace:!0})}function y9(){let{runtimeId:e,noteId:t,resultId:n}=te(),r=n??e;return r?(0,q.jsx)(at,{to:AH(r),replace:!0}):t?(0,q.jsx)(at,{to:`/sessions?q=${encodeURIComponent(`:session{note:${t}}`)}`,replace:!0}):(0,q.jsx)(at,{to:`/sessions`,replace:!0})}function bwe(){let e=Qe().search,t=e&&e.startsWith(`?`)?`${e}&mode=plan`:`?mode=plan`;return(0,q.jsx)(at,{to:`/journal${t}`,replace:!0})}var b9=null;async function xwe(e,t,n){(!b9||b9.attempt!==e)&&(b9={attempt:e,promise:t(A$.content)});try{let t=await b9.promise;return!n()&&b9?.attempt===e&&(b9=null),t}catch(t){throw b9?.attempt===e&&(b9=null),t}}var Swe=()=>T$(A$.content);function Cwe({createPage:e=Swe}={}){let t=dt(),n=(0,K.useRef)(t);(0,K.useLayoutEffect)(()=>{n.current=t},[t]);let[r,i]=(0,K.useState)(!1),[a,o]=(0,K.useState)(0);return(0,K.useEffect)(()=>{let t=!1;return(async()=>{try{let r=await xwe(a,e,()=>t);t||n.current(yH(r),{replace:!0})}catch{t||i(!0)}})(),()=>{t=!0}},[a,e]),r?(0,q.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,q.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{i(!1),o(e=>e+1)},children:`Try again`})]}):(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function wwe(e){if(!e)return null;let t=e.trim();if(!t)return null;let n=_I(t);if(n&&n.id!==`core`)return n;let r=iI(t);return r?xI().find(e=>iI(e.url)===r)??null:null}function Twe(){let e=Qe(),t=dt(),n=(0,K.useMemo)(()=>new URLSearchParams(e.search),[e.search]),r=n.get(`source`)??n.get(`feed`),[i,a]=(0,K.useState)(()=>r??``),[o,s]=(0,K.useState)(()=>r),[c,l]=(0,K.useState)(null);(0,K.useEffect)(()=>{a(r??``),s(r)},[r]);let u=(0,K.useMemo)(()=>wwe(o),[o]),d=(0,K.useSyncExternalStore)(GI,()=>xI().map(e=>`${e.id}:${BI(e.id)?`1`:`0`}`).join(`,`)),f=(0,K.useMemo)(()=>xI().filter(e=>!BI(e.id)),[d]),p=(0,K.useCallback)(async e=>{if(c===null){l(e.id);try{if(await cV(e.id,{offlinePolicy:`index-only`})===`error`){CQ({title:`${e.label} sync failed`,description:`Check your connection and try again.`,variant:`destructive`});return}t(`${Z.notebooks}?q=:notebook{feed:${e.id}}`)}finally{l(null)}}},[c,t]);return(0,q.jsxs)(`div`,{className:`min-h-svh flex flex-col bg-background text-foreground overflow-x-hidden`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Subscribe navigation`,className:`flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3 sm:px-6`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,q.jsx)(sr,{className:`size-4 text-primary`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`WOD Wiki Feeds`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4 text-xs`,children:[(0,q.jsx)(M,{to:Z.feeds,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Browse Feeds`}),(0,q.jsx)(M,{to:Z.notebooks,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`}),(0,q.jsx)(M,{to:Z.settingsSync,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Sync Settings`})]})]}),(0,q.jsxs)(`main`,{"data-agent-status":c?`loading`:`ready`,"aria-busy":c!==null,"data-testid":Q.FEED_SUBSCRIPTION_INTAKE,className:`w-full max-w-2xl min-w-0 mx-auto flex-1 px-4 py-8 sm:px-6 space-y-6`,children:[(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`h1`,{className:`text-xl font-bold tracking-tight`,children:`Subscribe to a Feed`}),(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground text-pretty max-w-prose`,children:`Inspect any workout catalog URL before subscribing. Choose which notebooks to include and keep workouts lightweight until you open them.`})]}),(0,q.jsxs)(`section`,{className:`rounded-xl border border-border bg-card p-4 sm:p-5 space-y-3`,children:[(0,q.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Inspect a Feed URL`}),(0,q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=i.trim();t&&s(t)},className:`flex flex-col sm:flex-row gap-2`,children:[(0,q.jsx)(Eo,{type:`url`,value:i,onValueChange:a,placeholder:`https://example.com/seed/`,"aria-label":`Feed directory URL`,className:`w-full sm:w-auto sm:flex-1 min-w-0 h-10 text-sm`}),(0,q.jsx)(J,{type:`submit`,className:`h-10 shrink-0`,disabled:!i.trim()||c!==null,children:`Inspect Feed`})]})]}),o&&u?(0,q.jsx)(H3,{registeredFeed:u,testId:Q.REGISTERED_FEED_INTAKE_CARD,subscribeButtonTestId:Q.REGISTERED_FEED_SUBSCRIBE_BTN,previewHref:EH(u.id),cancelLabel:`Decline`,onCancel:()=>t(Z.feeds),onSubscribed:e=>t(`${Z.notebooks}?q=:notebook{feed:${e}}`)}):o?(0,q.jsx)(U3,{feedParam:o,showUrlInputWhenInvalid:!1,onDismiss:()=>t(Z.notebooks),onSubscribed:e=>t(`${Z.notebooks}?q=:notebook{feed:${e}}`)}):null,!o&&f.length>0&&(0,q.jsxs)(`section`,{className:`space-y-3`,children:[(0,q.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Available Community Feeds`}),(0,q.jsx)(`div`,{className:`divide-y divide-border rounded-xl border border-border bg-card`,children:f.map(e=>(0,q.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-4`,children:[(0,q.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5`,children:[(0,q.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,q.jsx)(M,{to:EH(e.id),className:`no-underline hover:underline text-sm font-semibold text-foreground`,children:e.label})}),e.description&&(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground text-pretty max-w-prose`,children:e.description})]}),(0,q.jsxs)(`div`,{className:`flex items-center justify-end gap-2 shrink-0`,children:[(0,q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:c!==null,onClick:()=>{a(e.url),s(e.id)},children:`Inspect`}),(0,q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,"data-testid":`subscribe-catalog-${e.id}`,disabled:c!==null,onClick:()=>void p(e),children:c===e.id?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(ot,{className:`size-3.5 animate-spin`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Subscribing…`})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(Cr,{className:`size-3.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Subscribe`})]})})]})]},e.id))})]})]})]})}async function Ewe(e,t,n){let r=await X.getNote(e);if(!r||r.feedOrigin===`feed`||r.retention===`schedule-pinned`||r.retention===`session-pinned`||Array.isArray(r.notebookIds)&&r.notebookIds.length>0&&r.type!==`journal`&&r.type!==`playground`)return;let i=qN(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${JN(n)}${r.rawContent.slice(a.to)}`;await new DR().updateRecord(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function Dwe(e){if(!e)return{pending:void 0,adoptedRuntime:null};let t=Dz.get(e);if(t)return{pending:t,adoptedRuntime:null};let n=jz(e);return n?{pending:{block:n.block,noteId:n.noteId,captured:n.captured,origin:n.origin,returnTo:n.returnTo,scheduleItemId:n.scheduleItemId,sessionDate:n.sessionDate},adoptedRuntime:n.runtime}:{pending:void 0,adoptedRuntime:null}}function Owe(){let{runtimeId:e}=te();return(0,q.jsx)(kwe,{runtimeId:e},e??`missing`)}function kwe({runtimeId:e}){let[t]=be(),n=dt(),[r]=(0,K.useState)(()=>Dwe(e)),i=(0,K.useRef)(r.pending),a=t.get(`note`),o=t.get(`block`),[s,c]=(0,K.useState)(()=>!r.pending&&!!a),[l,u]=(0,K.useState)(void 0),d=(0,K.useRef)(r.pending?.captured??null),f=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(i.current||!a||!e){c(!1);return}let t=!1;return c(!0),X.getNote(a).then(e=>{if(t)return;if(!e){c(!1);return}let n=Object.values(e.blocks??{}).filter(e=>e.kind===`wod`),r=o?n.find(e=>e.id===o):n[0];if(!r){c(!1);return}let a=e.rawContent.slice(r.from,r.to),s=zs(a,{registeredWidgets:Ns})[0],l=s?.scriptBlock?.content??a,d=nu().read(l,r.sport).statements??[],f={block:{id:r.id,contentId:s?.scriptBlock?.contentId,dialect:r.dialect??`time`,sport:r.sport,startLine:0,endLine:Math.max(0,a.split(/\r?\n/).length-1),content:l,statements:d,state:`idle`,version:r.version,createdAt:e.createdAt,widgetIds:{}},noteId:e.id};i.current=f,u(f),c(!1)}).catch(()=>{t||c(!1)}),()=>{t=!0}},[a,o,e]);let p=(0,K.useCallback)(async()=>{let t=i.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(d.current=t.captured,t.captured.block):(d.current||=t.snapshot?await Yz(t.snapshot,t.block,e,t.origin,void 0,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}):await Xz(t.noteId,t.block,e,t.origin,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}),d.current.block)},[e]);(0,K.useEffect)(()=>{e&&Dz.delete(e)},[e]);let m=r.pending??l,h=(0,K.useRef)(!1),g=(0,K.useCallback)((t,n)=>!n||!e||!m?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):(h.current=n.completed,_R.record({runBlock:m.block,blockId:m.block.id,noteId:m.noteId,resultId:e,data:n,createdAt:n.endTime||Date.now(),...m.origin?{origin:m.origin}:{},...m.scheduleItemId?{scheduleItemId:m.scheduleItemId}:{},...m.sessionDate?{sessionDate:m.sessionDate}:{}}).then(async()=>{if(bU(),f.current=!0,Nz(e),n.completed)try{await Ewe(m.noteId,m.block.id,e)}catch{}})),[e,m]),_=(0,K.useCallback)(()=>{if(f.current=!0,e&&Nz(e),!m){n(`/`);return}if(h.current&&e){n(AH(e),{replace:!0});return}if(m.returnTo){n(m.returnTo,{replace:!0});return}n(BW(zW(m.noteId)),{replace:!0})},[e,m,n]),v=(0,K.useCallback)(t=>{let n=i.current;if(!e||!n||f.current){t.dispose();return}kz({runtimeId:e,block:n.block,noteId:n.noteId,captured:d.current??n.captured,origin:n.origin,returnTo:n.returnTo,scheduleItemId:n.scheduleItemId,sessionDate:n.sessionDate,runtime:t})},[e]),y=(0,K.useCallback)(t=>{if(!e)return;let n=Az(e);n&&n.runtime!==t&&n.runtime.dispose()},[e]);if(s)return(0,q.jsx)(`main`,{"data-agent-status":`loading`,"aria-busy":!0,role:`status`,className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Preparing workout timer…`});if(!m)return(0,q.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Workout runner navigation`,className:`flex items-center gap-5 px-6 py-3 border-b bg-background`,children:[(0,q.jsx)(`span`,{className:`text-sm font-semibold tracking-tight`,children:`WOD Wiki`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-home`,onClick:()=>n(`/`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Home`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-journal`,onClick:()=>n(`/journal`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Journal`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-notebooks`,onClick:()=>n(`/notebooks`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`})]}),(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`flex-1 flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,q.jsx)(W0,{}),(0,q.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,q.jsx)(Ri,{className:`w-8 h-8 text-muted-foreground`})}),(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Workout session not found`}),(0,q.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`Runtime not found. Please start the workout from the editor.`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`run-notfound-go-home`,onClick:()=>n(`/`),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,q.jsx)(da,{className:`w-4 h-4`}),`Go home`]})]})]});let b=m.captured?.note.rawContent??m.snapshot?.rawContent,x=m.scheduleItemId?`Scheduled${m.sessionDate?` · ${m.sessionDate}`:``}`:m.sessionDate?`Logged for ${m.sessionDate}`:`Ad-hoc · Today`;return(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`contents`,children:[(0,q.jsx)(`div`,{"data-testid":Q.RUNNER_CONTEXT_PILL,className:`pointer-events-none fixed left-1/2 top-2.5 z-50 -translate-x-1/2 rounded-full border border-border/70 bg-background/90 px-3 py-1 text-[11px] font-semibold text-foreground shadow-sm backdrop-blur-sm`,children:x}),(0,q.jsx)(z2,{block:m.block,noteContent:b,prepareRun:p,onClose:_,onCompleteWorkout:g,resultId:e,noteId:m.noteId,autoStart:!0,adoptRuntime:r.adoptedRuntime,parkOnUnmount:!0,onPark:v,onRuntimeReady:y})]})}var Awe=new DR;function jwe(){let e=dt(),[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)(null),a=(0,K.useRef)(null),o=async r=>{if(!(!r||t)){n(!0),i(null);try{let t=await lL(r,Awe);if(t.imported+(t.sessionsImported??0)===0){i(t.errors.length>0?t.errors.slice(0,2).join(`; `):`No portable notes or sessions were found in that bundle.`);return}CQ({title:`Imported ${t.imported} note(s), ${t.sessionsImported??0} session(s)`,description:t.errors.length>0?t.errors.slice(0,2).join(`; `):`Import complete.`}),e(Z.home)}catch(e){i(e instanceof Error?e.message:`That file is not a valid portable bundle (.zip).`)}finally{n(!1)}}};return(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":t,"data-testid":`load-zip-intake`,className:`w-full max-w-xl min-w-0 mx-auto px-4 py-10 sm:px-6 flex flex-col gap-4 overflow-x-hidden`,children:[(0,q.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Workout Bundle`}),(0,q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`A portable bundle is the `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.zip`}),` (or`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.md`}),` / `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.jsonl`}),` /`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.csv`}),`) export from Settings → Data, or a`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`wod export`}),` archive. Importing never runs the workout.`]}),(0,q.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border bg-card p-5 flex flex-col items-center gap-3 text-center`,children:[(0,q.jsx)(_n,{className:`size-6 text-muted-foreground`,"aria-hidden":`true`}),(0,q.jsx)(`input`,{ref:a,type:`file`,accept:`.zip,.md,.markdown,.jsonl,.csv`,"data-testid":`bundle-file-input`,className:`text-xs text-muted-foreground file:mr-3 file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-primary-foreground hover:file:opacity-90 max-w-full`,"aria-label":`Portable bundle file`,disabled:t,onChange:e=>{o(e.target.files?.[0]),e.target.value=``}}),r&&(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`bundle-import-error`,className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:[(0,q.jsx)($i,{className:`size-4 mt-0.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>e(HH(`data`)),children:`Storage settings`}),(0,q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>e(`/`),children:`Back to Home`})]})]})}function Mwe(){let[e]=V(`zip`),[t]=V(`z`),n=Qe(),[r]=(0,K.useState)(()=>{let e=new URLSearchParams(n.search||window.location.search);return!!(e.get(`zip`)||e.get(`z`))}),i=new URLSearchParams(n.search);return e||t||i.get(`zip`)||i.get(`z`)||r?(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,q.jsx)(`div`,{className:`flex-1 flex items-start justify-center`,children:(0,q.jsx)(jwe,{})})}async function x9(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 S9(e={}){let{decodeZip:t=x9,getTodayDateKey:n=mU,isDateInPast:r=hU,journalNotes:i=DU,toast:a=CQ}=e,o=dt(),s=Qe(),{date:c}=te(),[l]=V(`zip`),[u,d]=(0,K.useState)({state:`loading`});return(0,K.useEffect)(()=>{if(!(s.pathname===`/load/journal`||s.pathname.startsWith(`/load/journal/`)))return;if(!l){d({state:`missing-zip`});return}let e=!1,u=async()=>{try{d({state:`loading`});let i;try{i=await t(l)}catch(e){console.error(`Failed to decode zip:`,e),d({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{u()}}),a({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(e)return;let s;if(c){let e=gU(c);if(!e){d({state:`error`,error:`Invalid date format`}),a({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),o(Z.journal,{replace:!0});return}s=e.dateKey}else s=n();if(e)return;if(r(s)){d({state:`pending-confirmation`,content:i,dateKey:s,onConfirmBackdate:async()=>{e||await f(i,s)}});return}await f(i,s)}catch(t){console.error(`Unexpected error in journal zip processor:`,t),e||(d({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{u()}}),a({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},f=async(t,n)=>{if(!e)try{d({state:`creating`});let r=await i.create({journalDate:n,title:n,rawContent:t});e||(o(SH(r.id),{replace:!0}),d({state:`success`,content:t,dateKey:n}))}catch(r){console.error(`Failed to create journal entry:`,r),e||(d({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{f(t,n)}}),a({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return u(),()=>{e=!0}},[l,c,o,t,n,r,i,a]),u}var Nwe=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,K.useState)(!1),[c,u]=(0,K.useState)(!1),d=async()=>{u(!0);try{await t()}finally{u(!1)}},f=async e=>{u(!0),s(!1);try{await n(e)}finally{u(!1)}},p=e?Mw(e):`Date`,m=i||c;return(0,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:()=>void d(),disabled:m,className:$(`flex items-center gap-2 px-3 py-2 transition-colors hover:bg-accent hover:text-accent-foreground`,m&&`opacity-60 cursor-not-allowed`),children:[c?(0,q.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,q.jsx)(kt,{className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Import Today`})]}),(0,q.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,q.jsxs)(nt,{open:o,onOpenChange:s,children:[(0,q.jsxs)(l,{disabled:m,"aria-label":`Plan for future date`,title:`Select a date to plan for the future`,className:$(`flex h-auto rounded-none border-0 bg-transparent items-center gap-1.5 px-2.5 py-2 transition-colors hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,m&&`opacity-60 cursor-not-allowed`),children:[(0,q.jsx)(Re,{className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),e&&(0,q.jsx)(`span`,{className:`leading-none text-xs`,children:p})]}),(0,q.jsx)(Rr,{align:`end`,sideOffset:6,"aria-label":`Plan date`,className:`p-0 w-auto`,children:(0,q.jsx)(i6,{selectedDate:e||null,onDateSelect:e=>void f(e),entryDates:r})})]})]})},Pwe=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let i=jw(new Date(`${e}T00:00:00`));return(0,q.jsxs)(ei,{open:!0,onOpenChange:(e,t)=>{!e&&t.reason!==`action`&&!r&&n()},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{className:`max-w-sm`,children:[(0,q.jsxs)(Do,{children:[(0,q.jsx)(oa,{children:`Backdate Journal Entry`}),(0,q.jsxs)(Xi,{children:[`The date you selected (`,i,`) is in the past. This will create a journal entry for the selected date.`]})]}),(0,q.jsxs)(Oo,{children:[(0,q.jsx)(Sr,{disabled:r,onClick:n,children:`Cancel`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`solid`,disabled:r,action:()=>t(),children:r?`Importing…`:`Import`})]})]})]})},Fwe=new DR,Iwe={h1:({children:e})=>(0,q.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,q.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,q.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,q.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,q.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,q.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,q.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,q.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,q.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,q.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,q.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,q.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,q.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,q.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,q.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,q.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,q.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,q.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,q.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,q.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,q.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,q.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,q.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,q.jsx)(`hr`,{className:`my-6 border-border/50`})};function C9(){let e=dt(),t=S9(),[n,r]=(0,K.useState)(!1),[i,a]=(0,K.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,q.jsxs)(`main`,{"data-agent-status":o===`loading`?`loading`:`ready`,"aria-busy":o===`loading`,className:`flex flex-col flex-1 min-h-0 bg-background`,children:[(0,q.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,q.jsx)(`button`,{type:`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,q.jsx)(je,{className:`h-5 w-5`})}),(0,q.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,q.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,q.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,q.jsx)(J,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`||o===`missing-zip`?null:(0,q.jsx)(Nwe,{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:!1})]}),(0,q.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`missing-zip`&&(0,q.jsx)(Lwe,{}),o===`loading`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,q.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,q.jsx)($i,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,q.jsx)(J,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,q.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,q.jsxs)(`div`,{className:`text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,q.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,q.jsxs)(`div`,{className:`text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,q.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,q.jsx)(si,{remarkPlugins:[Fn],components:Iwe,children:s})}):null]}),n&&c&&(0,q.jsx)(Pwe,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function Lwe(){let e=dt(),[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)(null),a=async r=>{if(!(!r||t)){n(!0),i(null);try{let t=await lL(r,Fwe);CQ({title:`Imported ${t.imported} note(s)`,description:t.errors.length>0?t.errors.slice(0,2).join(`; `):`Open the entry from your journal.`}),e(Z.journal)}catch(e){i(e instanceof Error?e.message:`That file is not a valid portable bundle (.zip).`)}finally{n(!1)}}};return(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center gap-4 max-w-md min-w-0 mx-auto text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground`,children:`This import link is missing its bundle`}),(0,q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`The journal import link carries a compressed bundle in its`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`?zip=`}),` parameter. Re-open the original link, or import a portable bundle file directly — entries land in your journal.`]}),(0,q.jsx)(`input`,{type:`file`,accept:`.zip,.md,.markdown,.jsonl,.csv`,"data-testid":`journal-zip-upload`,"aria-label":`Journal bundle file`,disabled:t,className:`text-xs text-muted-foreground file:mr-3 file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-primary-foreground hover:file:opacity-90 max-w-full`,onChange:e=>{a(e.target.files?.[0]),e.target.value=``}}),r&&(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`journal-zip-error`,className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:[(0,q.jsx)($i,{className:`size-4 mt-0.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r})]}),(0,q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>e(Z.journal),children:`Back to Journal`})]})}function Rwe(){let{slug:e}=te(),t=Qe(),n=e?.startsWith(`guide-`)?e:`guide-${e??`start`}`;return(0,q.jsx)(at,{to:`/page/${encodeURIComponent(n)}${t.search}${t.hash}`,replace:!0})}function zwe({searchHandlerRef:e,canvasRouteList:t=[],rootUnavailable:n,pageSettlingFallback:r}){return(0,q.jsxs)(lee,{children:[(0,q.jsx)(f,{path:Z.home,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`*`,element:n??(0,q.jsx)(_we,{})}),(0,q.jsx)(f,{path:`/proto/calc-authoring`,element:(0,q.jsx)(iCe,{})}),(0,q.jsx)(f,{path:`/proto/query-block-composer`,element:(0,q.jsx)(mCe,{})}),(0,q.jsx)(f,{path:`/settings`,element:(0,q.jsx)(at,{to:`/settings/appearance`,replace:!0})}),(0,q.jsx)(f,{path:`/settings/appearance`,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsProfile,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:vH.settingsData,element:(0,q.jsx)(at,{to:Z.settingsStorage,replace:!0})}),(0,q.jsx)(f,{path:vH.settingsDatabase,element:(0,q.jsx)(at,{to:Z.settingsStorage,replace:!0})}),(0,q.jsx)(f,{path:Z.settingsStorage,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsSync,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/settings/system`,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:vH.settingsQueries,element:(0,q.jsx)(at,{to:Z.journal,replace:!0})}),(0,q.jsx)(f,{path:Z.settingsTags,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsSoundProfiles,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/settings/library/calcs`,element:(0,q.jsx)(`div`,{className:`p-6`,children:(0,q.jsx)(XCe,{})})}),(0,q.jsx)(f,{path:`/legacy`,element:(0,q.jsx)(rwe,{})}),(0,q.jsx)(f,{path:`/syntax`,element:(0,q.jsx)(gwe,{})}),(0,q.jsx)(f,{path:Z.plan,element:(0,q.jsx)(bwe,{})}),(0,q.jsx)(f,{path:Z.feeds,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.feed,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebooks,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebook,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebookTarget,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebookItem,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.subscribe,element:(0,q.jsx)(Twe,{})}),(0,q.jsx)(f,{path:Z.pages,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.page,element:r??(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/guide/:slug`,element:(0,q.jsx)(Rwe,{})}),(0,q.jsx)(f,{path:Z.load,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(Mwe,{})})}),(0,q.jsx)(f,{path:Z.loadJournal,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(C9,{})})}),(0,q.jsx)(f,{path:Z.loadJournalDate,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(C9,{})})}),(0,q.jsx)(f,{path:Z.playgroundRoot,element:(0,q.jsx)(Cwe,{})}),(0,q.jsx)(f,{path:Z.playground,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.playgrounds,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notes,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.note,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.journal,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.day,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.run,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(Owe,{})})}),(0,q.jsx)(f,{path:Z.tracker,element:(0,q.jsx)(ywe,{})}),(0,q.jsx)(f,{path:`/results/segments`,element:(0,q.jsx)(vwe,{})}),(0,q.jsx)(f,{path:Z.sessionDetail,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.sessions,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.sessionDate,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/review/:runtimeId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review/:sectionId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:Z.efforts,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.effort,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.equipment,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.equipmentSlug,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tags,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tagCategory,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tag,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.dashboards,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.dashboardView,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),t.map(({route:t})=>(0,q.jsx)(f,{path:t,element:(0,q.jsx)(x7,{searchHandlerRef:e})},t))]})}var w9=`G-PROD-ID`,T9=!1;function E9(){if(T9||typeof document>`u`)return;T9=!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=${w9}`,document.head.appendChild(e),window.gtag(`js`,new Date),window.gtag(`config`,w9,{send_page_view:!1})}function D9(e,t){typeof window>`u`||!$R.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:QR()})}$R.setForwarder(e=>{window.gtag?.(`event`,e.name,e.payload??{})}),$R.consent?E9():$R.subscribeConsent(e=>{e&&(E9(),D9())});function Bwe(){let e=Qe();return(0,K.useEffect)(()=>{let t=e.pathname;if(!t.startsWith(`/effort/`)&&!t.startsWith(`/playground/`)&&!t.startsWith(`/equipment/`)){let e=`Wod.Wiki`;t.startsWith(`/day/`)?e=`Wod.Wiki - Day`:t.startsWith(`/journal`)?e=`Wod.Wiki - Journal`:t.startsWith(`/notebooks`)||t.startsWith(`/notebook/`)?e=`Wod.Wiki - Notebooks`:t===`/notes`?e=`Wod.Wiki - Notes`:t.startsWith(`/note/`)?e=`Wod.Wiki - Note`:t.startsWith(`/pages`)||t.startsWith(`/page/`)?e=`Wod.Wiki - Pages`:t.startsWith(`/tags`)||t.startsWith(`/t/`)?e=`Wod.Wiki - Tags`:t===`/feeds`?e=`Wod.Wiki - Feeds`:t.startsWith(`/feed/`)?e=`Wod.Wiki - Feed`:t.startsWith(`/efforts`)?e=`Wod.Wiki - Efforts`:t.startsWith(`/equipment`)?e=`Wod.Wiki - Equipment`:t.startsWith(`/sessions`)||t.startsWith(`/session/`)?e=`Wod.Wiki - Sessions`:t.startsWith(`/dashboards`)||t.startsWith(`/dashboard/`)?e=`Wod.Wiki - Dashboards`:t.startsWith(`/playgrounds`)&&(e=`Wod.Wiki - Playgrounds`),document.title=e}let n=setTimeout(()=>{D9(document.title,e.pathname+e.search)},0);return()=>clearTimeout(n)},[e.pathname]),null}function Vwe(e={}){let{decodeZip:t=x9,intake:n=w$,toast:r=CQ}=e,i=dt(),a=Qe(),[o]=V(`zip`),[s]=V(`z`),[c]=V(`by`),[l]=V(`src`),u=(0,K.useRef)(null);(0,K.useEffect)(()=>{if(a.pathname!==`/load`&&!(a.pathname===`/`&&s))return;if(s){let e=`${s}:${c??``}`;if(u.current===e)return;u.current=e;let a=!1;return(async()=>{try{let e=await t(s);if(e===null)throw Error(`Invalid workout link`);if(a)return;let r=Mve(e,c??void 0);if(await n.ensureEntry(r,{reuseKey:`home`,title:`Home playground`}),a)return;Nve({content:r,by:c??void 0})}catch(e){console.error(`Failed to decode zip:`,e),a||r({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}a||i(`/`,{replace:!0})})(),()=>{a=!0}}if(!o)return;let e=!1,d=l&&l.startsWith(`/`)?l:void 0;return(async()=>{try{let r=await t(o);if(r===null)throw Error(`Invalid workout link`);if(e)return;let a=d?await n.createPage(r,{sourcePath:d}):await n.createPage(r);e||i(yH(a),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),e||(r({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),i(Z.home,{replace:!0}))}})(),()=>{e=!0}},[o,s,c,l,i,a.pathname,t,n,r])}var O9=null,Hwe=1,k9=new Set;function A9(){for(let e of k9)e()}function j9(e){return O9&&O9.resolve(!1),new Promise(t=>{let n=Hwe++;O9={id:n,request:e,resolve:e=>{O9?.id===n&&(O9=null,A9()),t(e)}},A9()})}async function M9(e,t){let n=t&&typeof t==`object`?t:void 0,r=n?.client?.requestUserInteraction??n?.requestUserInteraction;return typeof r==`function`?r(()=>j9(e)):j9(e)}var Uwe=()=>{let e=(0,K.useSyncExternalStore)(e=>(k9.add(e),()=>k9.delete(e)),()=>O9,()=>null);return e?(0,q.jsx)(`div`,{"data-agent-hidden":``,children:(0,q.jsxs)(ei,{open:!0,onOpenChange:t=>{t||e.resolve(!1)},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{"data-testid":`agent-confirm-dialog`,children:[(0,q.jsxs)(Do,{children:[(0,q.jsxs)(oa,{className:`flex items-center gap-2 text-destructive`,children:[(0,q.jsx)(oe,{className:`size-5 shrink-0`,"aria-hidden":`true`}),`Confirm Agent Action`]}),(0,q.jsxs)(Xi,{children:[`An AI agent requested a destructive operation (`,(0,q.jsx)(`strong`,{children:e.request.action}),`).`]})]}),(0,q.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/40 p-3 text-xs space-y-1`,children:[(0,q.jsx)(`div`,{className:`font-medium text-foreground`,children:e.request.summary}),(0,q.jsxs)(`div`,{className:`font-mono text-muted-foreground`,children:[`Target: `,(0,q.jsx)(`span`,{"data-testid":`agent-confirm-target`,children:e.request.targetId})]})]}),(0,q.jsxs)(Oo,{className:`gap-2 sm:gap-0`,children:[(0,q.jsx)(Sr,{"data-testid":`agent-confirm-cancel`,onClick:()=>e.resolve(!1),children:`Deny`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`destructive`,"data-testid":`agent-confirm-approve`,onClick:()=>e.resolve(!0),children:`Approve Action`})]})]})]})}):null};function Wwe(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var Gwe=()=>{let e=Qe(),t=RZ(),n=zZ(),r=tZ(),i=EX(),a=MX(),o=RW(),s=bX(),c=RX(),l=(0,K.useSyncExternalStore)(e0,$1,()=>null),u=r||t===`preparing`||n,d=(0,K.useMemo)(()=>{let r=i&&o&&o.pathname===e.pathname?o:null;return Wwe({schemaVersion:`1.0`,build:MJ,hydrated:!0,status:u?`loading`:`ready`,feedReadiness:t,importPending:n,route:{pathname:e.pathname,search:e.search,hash:e.hash},stream:i?{route:i.route,query:i.query,defaultQuery:i.defaultQuery,layout:i.layout,availableLayouts:i.availableLayouts,groupBy:i.groupBy??null,loading:i.loading,totalUnbatchedCount:r?r.entries.length:null,sampleEntries:r?r.entries.slice(0,25).map(e=>({id:e.id,title:e.title,date:e.date??null,notebookId:e.notebookId??null})):[]}:null,explorer:a?{draft:a.draft,submitted:a.submitted,weeks:a.weeks,loading:a.loading,saveReady:a.saveReady}:null,editor:s?{noteId:s.noteId??null,readonly:s.readonly,sourceRevision:s.sourceRevision??null,workoutBlockIds:s.getBlocks().map(e=>e.id)}:null,results:c?{resultId:c.resultId,activeTab:c.activeTab,mobileViewMode:c.mobileViewMode,sourceDrawerOpen:c.sourceDrawerOpen,addToDashboardOpen:c.addToDashboardOpen}:null,clock:l})},[u,t,n,e.pathname,e.search,e.hash,i,a,o,s,c,l]);return(0,q.jsx)(`script`,{id:`agent-view-state`,type:`application/json`,dangerouslySetInnerHTML:{__html:d}})},N9=class extends Error{code=`CONFIRMATION_REQUIRED`;targetId;action;constructor(e,t){super(t??`Destructive action '${e.action}' on '${e.targetId}' requires confirmation (${e.summary}).`),this.name=`AgentConfirmationRequiredError`,this.action=e.action,this.targetId=e.targetId}};function P9(e){return e}async function F9(e,t,n){if(n===void 0||n!==t.targetId){if(e.confirmDestructive){let n=e.confirmTimeoutMs??1500,r;if(await Promise.race([e.confirmDestructive(t).finally(()=>{r!==void 0&&clearTimeout(r)}),new Promise(e=>{r=setTimeout(()=>e(!1),n)})]))return;throw new N9(t,`User declined or did not confirm '${t.action}' on '${t.targetId}'.`)}throw new N9(t,`Destructive action '${t.action}' requires confirmId="${t.targetId}" (or --yes "${t.targetId}" on CLI).`)}}function I9(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Kwe(e){let t=e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);for(let e of t.split(/\r?\n/)){let t=e.match(/^#\s+(.+)$/);if(t?.[1]?.trim())return t[1].trim()}}function L9(e,t,n){let r=e.trim();if(!r)return n?`# ${n}\n`:``;let i=e.replace(/^(\s*`{3,})(?:wod|whiteboard)(?=(?::[\w-]+)?\s*$)/gim,`$1time`);if(zs(i,{registeredWidgets:Ns}).some(e=>e.scriptBlock)||/^---\r?\n/.test(i)||/^#\s+/m.test(i))return i.endsWith(`
|
|
1200
|
+
`));e(yH(n))},[e]),m=(0,K.useCallback)(t=>{if(/^https?:\/\//i.test(t)){window.open(t,`_blank`,`noopener,noreferrer`);return}e(t)},[e]);return(0,q.jsxs)(twe,{actionsSlot:(0,q.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,q.jsx)(fn,{className:`size-4 text-zinc-500`,"aria-hidden":`true`}),(0,q.jsx)(un,{checked:l,onCheckedChange:e=>n(e?`dark`:`light`),"aria-label":`Toggle dark mode`,children:(0,q.jsx)(Cn,{})}),(0,q.jsx)(zt,{className:`size-4 text-zinc-500`,"aria-hidden":`true`})]}),heroSlot:(0,q.jsx)(x5,{config:nwe,onAction:f}),children:[(0,q.jsxs)(`section`,{ref:r,id:`workout-widget-surface`,className:`mt-8 grid grid-cols-1 gap-4 xl:grid-cols-3`,children:[(0,q.jsx)(`div`,{className:`xl:col-span-2`,children:(0,q.jsx)(S5,{config:s,isDarkMode:l,onRun:p})}),(0,q.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,q.jsx)(C5,{config:e,onOpenDocs:m},e.title))})]}),(0,q.jsx)(j6,{})]})}function _9(e){let[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)({});(0,K.useEffect)(()=>{i(Y0()),n(!0);let e=e=>{e.key===`wodwiki.quests.v1`&&i(Y0())};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 iwe({activeIndex:e,onCommand:t,captions:n}){return(0,q.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`tour-captions`,children:n.map((n,r)=>(0,q.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,q.jsx)(awe,{cap:n,onCommand:t})},n.id))})}function awe({cap:e,onCommand:t}){return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`h3`,{className:`mb-3.5 xl:mb-5 text-[clamp(22px,2vw,32px)] font-extrabold leading-[1.12] tracking-[-0.03em]`,children:[(0,q.jsx)(`span`,{className:`mr-2 align-[0.2em] font-mono text-[0.5em] font-semibold tracking-[0.08em] text-muted-foreground`,children:e.num}),e.title]}),(0,q.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,q.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,q.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,q.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,q.jsx)(`span`,{children:e})]},t))}),e.foot&&(0,q.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`,children:e.foot}),e.extra&&(0,q.jsx)(`div`,{className:`mt-3`,children:e.extra}),e.commands&&e.commands.length>0&&t&&(0,q.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,q.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,q.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,q.jsx)(M,{to:e.href,onClick:()=>$R.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 owe({visible:e,children:t}){return(0,q.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 swe=(0,K.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,K.useRef)(null),f=(0,K.useRef)(null),[p,m]=(0,K.useState)(null),h=(0,K.useCallback)(e=>{f.current=e,m(e)},[]),{slice:g,subscribe:_,resync:v,runwayReached:y}=X4(d,!1,r,e),b=lwe(d);(0,K.useEffect)(()=>{o?.(b)},[b,o]),(0,K.useEffect)(()=>{s?.(y)},[y,s]);let[x,S]=(0,K.useState)(!1),C=cwe(d);(0,K.useEffect)(()=>{(C||y)&&S(!0)},[C,y]);let w=g.stage?.screen??`editor`,T=(0,K.useRef)(null);return(0,K.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,K.useImperativeHandle)(u,()=>({scrollToStage:e=>{let t=d.current,n=r.find(t=>t.id===e);!t||!n||jge(t,Math.min(n.range[0]+.02,n.range[1]-.005))},subscribe:_,resync:v}),[r,_,v]),(0,q.jsxs)(`section`,{id:`tour-section-${e}`,"data-testid":`tour-section-${e}`,children:[n,(0,q.jsx)(Y4,{trackRef:d,height:t,stages:r,activeIndex:g.index,segmentId:e,testId:`tour-runway`,pane:(0,q.jsx)(`div`,{ref:h,className:`absolute inset-0 flex flex-col justify-center`,children:(0,q.jsxs)(y6,{children:[(0,q.jsx)(Hve,{ringKey:`editor.window`,el:p}),(0,q.jsx)(r2,{title:__e[w],className:`relative h-full max-h-[760px]`,children:(0,q.jsx)(J4,{gateId:`${e}-pane`,segmentId:e,className:`relative h-full`,children:l&&(0,q.jsx)(owe,{visible:w===`editor`,children:(0,q.jsx)(M6,{doc:l.doc,onDocChange:l.onDocChange,onBlocksChange:l.onBlocksChange,onRun:l.onRun,theme:l.theme,withRingTargets:!0})})})}),(0,q.jsx)(Uve,{target:g.ring?.key?{key:g.ring.key}:null,accent:g.stage.accent??w3.editor,canvasRef:f})]})}),captions:(0,q.jsx)(iwe,{activeIndex:g.index,captions:i,onCommand:c})})]})});function cwe(e){let[t,n]=(0,K.useState)(!1);return(0,K.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 lwe(e){let[t,n]=(0,K.useState)(()=>typeof IntersectionObserver>`u`);return(0,K.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 uwe={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`},v9={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`]}},dwe=[{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 fwe({chapters:e=[],allQuests:t=[],theme:n,wodFiles:r={},onRun:i}){let a=(0,K.useMemo)(()=>{let t=(e??[]).filter(e=>e.id!==`home-tour`);return t.length>0?t:dwe},[e]),o=t2(`(prefers-reduced-motion: reduce)`),{markComplete:s}=Q0(`/`,t),{chapters:c}=_9(a),[l,u]=(0,K.useState)(()=>a[0]?.id??`basics`),[d,f]=(0,K.useState)(``),p=(0,K.useRef)([]),m=(0,K.useRef)(l);m.current=l;let h=(0,K.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,fY(uwe[e.id]??``,r)])),[a,r]);(0,K.useEffect)(()=>{p.current=[],f(h[l]??``)},[l,h]);let g=(0,K.useCallback)(e=>{p.current=e},[]),_=(0,K.useCallback)(()=>{let e=m.current;s(`${e}-run`),i?.(e,p.current[0]??null,d)},[d,s,i]),v=(0,K.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,K.useMemo)(()=>Object.fromEntries(c.map(e=>[e.chapter.id,e])),[c]),b=(0,K.useMemo)(()=>a.map((e,t)=>{let n=v9[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,q.jsx)(`span`,{"data-testid":`chapter-picker-progress-${e.id}`,className:$(`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:T3[e.id]??`/page/guide-start`,event:ez.chapterGuideClicked,data:{chapter:e.id},testId:`chapter-picker-guide-${e.id}`}]}}),[a,y]);return(0,q.jsxs)(`section`,{id:`tour-chapter-picker`,"data-testid":`tour-chapter-picker`,className:`flex flex-col`,children:[(0,q.jsx)(S3,{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,q.jsx)(pwe,{chapters:a,selectedId:l,onSelect:u,doc:d,onDocChange:f,theme:n,onBlocksChange:g,onRun:_,progressByChapter:y}):(0,q.jsx)(swe,{id:`learn`,heightVh:`600vh`,stages:v,captions:b,onActiveStageChange:u,editor:{doc:d,theme:n,onDocChange:f,onBlocksChange:g,onRun:_}})]})}function pwe({chapters:e,selectedId:t,onSelect:n,doc:r,onDocChange:i,theme:a,onBlocksChange:o,onRun:s,progressByChapter:c}){return(0,q.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,q.jsxs)(`div`,{className:`flex flex-col gap-10 lg:flex-row lg:items-start lg:gap-12 xl:gap-16`,children:[(0,q.jsx)(`div`,{className:`w-full lg:w-[58%] xl:w-[60%] lg:sticky lg:top-[110px] z-10 flex-none`,children:(0,q.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,q.jsx)(r2,{title:T3[t]?.split(`/`).pop()??`example.md`,subtitle:`Lesson: ${e.find(e=>e.id===t)?.title??t}`,className:`h-full`,children:(0,q.jsx)(M6,{doc:r,onDocChange:i,onBlocksChange:o,onRun:s,theme:a,withRingTargets:!1})})})}),(0,q.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=v3(e.badge),o=e.id===t,s=v9[e.id];return(0,q.jsxs)(`div`,{"data-testid":`chapter-picker-row-${e.id}`,className:$(`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,q.jsxs)(`div`,{children:[(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsxs)(`span`,{className:`font-mono text-xs font-bold uppercase tracking-wider text-primary`,children:[`Chapter 0`,r+1]}),a&&(0,q.jsx)(a,{className:`size-4 text-primary`})]}),(0,q.jsx)(`span`,{className:$(`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,q.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground sm:text-3xl`,children:e.title}),(0,q.jsx)(`p`,{className:`mt-3 text-sm sm:text-base leading-relaxed text-muted-foreground`,children:s?.summary??e.title}),s?.bullets&&(0,q.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,q.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,q.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,q.jsx)(`span`,{children:e})]},t))})]}),(0,q.jsxs)(`div`,{className:`mt-6 flex flex-wrap items-center gap-3 pt-4 border-t border-border/50`,children:[(0,q.jsxs)(`button`,{type:`button`,onClick:()=>n(e.id),"data-testid":`chapter-picker-select-${e.id}`,"aria-pressed":o,className:$(`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,q.jsx)(Er,{className:`size-3.5 fill-current`}),(0,q.jsx)(`span`,{children:o?`Loaded in editor`:`Load example`})]}),(0,q.jsxs)(M,{to:T3[e.id]??`/page/guide-start`,"data-testid":`chapter-picker-guide-${e.id}`,"aria-label":`Read guide for ${e.title}`,onClick:()=>$R.record(ez.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,q.jsx)(fe,{className:`size-3.5`}),(0,q.jsx)(`span`,{children:`Read guide →`})]})]})]},e.id)})})]})})}function mwe({chapters:e}){let t=()=>$R.record(ez.lessonStarted),n=()=>$R.record(ez.cheatsheetOpened),{chapters:r}=_9(e),i=r.filter(e=>e.chapter.id!==`home-tour`);return(0,q.jsxs)(`section`,{"data-testid":`tour-learn`,className:`mx-auto max-w-5xl px-6 py-16 border-b border-border/60`,children:[(0,q.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between`,children:[(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-bold tracking-tight`,children:`Learn the Language`}),(0,q.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,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,q.jsx)(M,{to:`/page/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,q.jsx)(M,{to:`/page/guide-start?h=reference`,onClick:n,className:`text-sm font-semibold text-primary underline-offset-2 hover:underline`,children:`Cheat sheet →`})]})]}),(0,q.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=T3[e.id]??`/page/guide-start`,a=v3(e.badge);return(0,q.jsxs)(M,{to:i,"data-testid":`learn-progress-chip-${e.id}`,className:$(`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,q.jsx)(a,{className:`size-3.5 text-muted-foreground`}),(0,q.jsx)(`span`,{className:`text-[12px] font-semibold text-foreground`,children:e.title}),(0,q.jsx)(`span`,{className:$(`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 hwe=mwe;function gwe(){let e=HP(),t=(0,K.useMemo)(()=>h6(e??{}),[e]),{theme:n}=So(),[r,i]=(0,K.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches);(0,K.useEffect)(()=>{if(n!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>i(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[n]);let a=(0,K.useMemo)(()=>n===`system`?r?`vs-dark`:`vs`:n===`dark`?`vs-dark`:`vs`,[n,r]),o=Oq(),s=m6.chapters,c=m6.quests,l=(0,K.useMemo)(()=>{let e={};for(let t of m6.quests)e[t.id]=t.label;for(let{page:t}of o)for(let n of t.quests)e[n.id]=n.label;return e},[o]),u=tz()?.track,{run:d,start:f,finalize:p,end:m}=K0(),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(0),[y,b]=(0,K.useState)(!1),x=(0,K.useCallback)(()=>{g(null),b(!1)},[]),S=(0,K.useCallback)(async(e,t,n)=>{if(t){u?.(ez.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(),CQ({title:`Could not start workout`,variant:`destructive`})}}},[x,f,u]),C=(0,K.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),CQ({title:`Session not saved`,variant:`destructive`}),e}},[x,m,p]);return(0,q.jsx)(y6,{children:(0,q.jsxs)(`div`,{"data-testid":`syntax-view`,children:[(0,q.jsx)(S3,{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,q.jsx)(fwe,{wodFiles:t,chapters:s,allQuests:c,theme:a,onRun:S}),(0,q.jsx)(hwe,{quests:c,chapters:s,questLabels:l}),(0,q.jsx)(D3,{}),(0,q.jsx)(w6,{}),h&&y&&d&&(0,q.jsx)(z2,{block:d.block,resultId:d.resultId,autoStart:!0,onClose:x,onCompleteWorkout:C},_)]})})}function _we(){let e=dt();return(0,q.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Not found navigation`,className:`flex items-center gap-5 px-6 py-3 border-b bg-background`,children:[(0,q.jsx)(`span`,{className:`text-sm font-semibold tracking-tight`,children:`WOD Wiki`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-home`,onClick:()=>e(`/`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Home`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-journal`,onClick:()=>e(`/journal`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Journal`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`notfound-nav-notebooks`,onClick:()=>e(`/notebooks`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`})]}),(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`flex-1 flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,q.jsx)(Ri,{className:`w-8 h-8 text-muted-foreground`})}),(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Page not found`}),(0,q.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`The page you are looking for does not exist or has been moved.`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`notfound-go-home`,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,q.jsx)(da,{className:`w-4 h-4`}),`Go home`]})]})]})}function vwe(){return(0,q.jsx)(at,{to:`/sessions?q=%3Asegment%7B%7D%20last%208w`,replace:!0})}function ywe(){let{runtimeId:e}=te();return(0,q.jsx)(at,{to:DH(e),replace:!0})}function y9(){let{runtimeId:e,noteId:t,resultId:n}=te(),r=n??e;return r?(0,q.jsx)(at,{to:AH(r),replace:!0}):t?(0,q.jsx)(at,{to:`/sessions?q=${encodeURIComponent(`:session{note:${t}}`)}`,replace:!0}):(0,q.jsx)(at,{to:`/sessions`,replace:!0})}function bwe(){let e=Qe().search,t=e&&e.startsWith(`?`)?`${e}&mode=plan`:`?mode=plan`;return(0,q.jsx)(at,{to:`/journal${t}`,replace:!0})}var b9=null;async function xwe(e,t,n){(!b9||b9.attempt!==e)&&(b9={attempt:e,promise:t(A$.content)});try{let t=await b9.promise;return!n()&&b9?.attempt===e&&(b9=null),t}catch(t){throw b9?.attempt===e&&(b9=null),t}}var Swe=()=>T$(A$.content);function Cwe({createPage:e=Swe}={}){let t=dt(),n=(0,K.useRef)(t);(0,K.useLayoutEffect)(()=>{n.current=t},[t]);let[r,i]=(0,K.useState)(!1),[a,o]=(0,K.useState)(0);return(0,K.useEffect)(()=>{let t=!1;return(async()=>{try{let r=await xwe(a,e,()=>t);t||n.current(yH(r),{replace:!0})}catch{t||i(!0)}})(),()=>{t=!0}},[a,e]),r?(0,q.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,q.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,q.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{i(!1),o(e=>e+1)},children:`Try again`})]}):(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function wwe(e){if(!e)return null;let t=e.trim();if(!t)return null;let n=_I(t);if(n&&n.id!==`core`)return n;let r=iI(t);return r?xI().find(e=>iI(e.url)===r)??null:null}function Twe(){let e=Qe(),t=dt(),n=(0,K.useMemo)(()=>new URLSearchParams(e.search),[e.search]),r=n.get(`source`)??n.get(`feed`),[i,a]=(0,K.useState)(()=>r??``),[o,s]=(0,K.useState)(()=>r),[c,l]=(0,K.useState)(null);(0,K.useEffect)(()=>{a(r??``),s(r)},[r]);let u=(0,K.useMemo)(()=>wwe(o),[o]),d=(0,K.useSyncExternalStore)(GI,()=>xI().map(e=>`${e.id}:${BI(e.id)?`1`:`0`}`).join(`,`)),f=(0,K.useMemo)(()=>xI().filter(e=>!BI(e.id)),[d]),p=(0,K.useCallback)(async e=>{if(c===null){l(e.id);try{if(await cV(e.id,{offlinePolicy:`index-only`})===`error`){CQ({title:`${e.label} sync failed`,description:`Check your connection and try again.`,variant:`destructive`});return}t(`${Z.notebooks}?q=:notebook{feed:${e.id}}`)}finally{l(null)}}},[c,t]);return(0,q.jsxs)(`div`,{className:`min-h-svh flex flex-col bg-background text-foreground overflow-x-hidden`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Subscribe navigation`,className:`flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3 sm:px-6`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,q.jsx)(sr,{className:`size-4 text-primary`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`WOD Wiki Feeds`})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4 text-xs`,children:[(0,q.jsx)(M,{to:Z.feeds,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Browse Feeds`}),(0,q.jsx)(M,{to:Z.notebooks,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`}),(0,q.jsx)(M,{to:Z.settingsSync,className:`no-underline hover:underline text-muted-foreground hover:text-foreground transition-colors`,children:`Sync Settings`})]})]}),(0,q.jsxs)(`main`,{"data-agent-status":c?`loading`:`ready`,"aria-busy":c!==null,"data-testid":Q.FEED_SUBSCRIPTION_INTAKE,className:`w-full max-w-2xl min-w-0 mx-auto flex-1 px-4 py-8 sm:px-6 space-y-6`,children:[(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`h1`,{className:`text-xl font-bold tracking-tight`,children:`Subscribe to a Feed`}),(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground text-pretty max-w-prose`,children:`Inspect any workout catalog URL before subscribing. Choose which notebooks to include and keep workouts lightweight until you open them.`})]}),(0,q.jsxs)(`section`,{className:`rounded-xl border border-border bg-card p-4 sm:p-5 space-y-3`,children:[(0,q.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Inspect a Feed URL`}),(0,q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=i.trim();t&&s(t)},className:`flex flex-col sm:flex-row gap-2`,children:[(0,q.jsx)(Eo,{type:`url`,value:i,onValueChange:a,placeholder:`https://example.com/seed/`,"aria-label":`Feed directory URL`,className:`w-full sm:w-auto sm:flex-1 min-w-0 h-10 text-sm`}),(0,q.jsx)(J,{type:`submit`,className:`h-10 shrink-0`,disabled:!i.trim()||c!==null,children:`Inspect Feed`})]})]}),o&&u?(0,q.jsx)(H3,{registeredFeed:u,testId:Q.REGISTERED_FEED_INTAKE_CARD,subscribeButtonTestId:Q.REGISTERED_FEED_SUBSCRIBE_BTN,previewHref:EH(u.id),cancelLabel:`Decline`,onCancel:()=>t(Z.feeds),onSubscribed:e=>t(`${Z.notebooks}?q=:notebook{feed:${e}}`)}):o?(0,q.jsx)(U3,{feedParam:o,showUrlInputWhenInvalid:!1,onDismiss:()=>t(Z.notebooks),onSubscribed:e=>t(`${Z.notebooks}?q=:notebook{feed:${e}}`)}):null,!o&&f.length>0&&(0,q.jsxs)(`section`,{className:`space-y-3`,children:[(0,q.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Available Community Feeds`}),(0,q.jsx)(`div`,{className:`divide-y divide-border rounded-xl border border-border bg-card`,children:f.map(e=>(0,q.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-4`,children:[(0,q.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5`,children:[(0,q.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,q.jsx)(M,{to:EH(e.id),className:`no-underline hover:underline text-sm font-semibold text-foreground`,children:e.label})}),e.description&&(0,q.jsx)(`p`,{className:`text-xs text-muted-foreground text-pretty max-w-prose`,children:e.description})]}),(0,q.jsxs)(`div`,{className:`flex items-center justify-end gap-2 shrink-0`,children:[(0,q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:c!==null,onClick:()=>{a(e.url),s(e.id)},children:`Inspect`}),(0,q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,"data-testid":`subscribe-catalog-${e.id}`,disabled:c!==null,onClick:()=>void p(e),children:c===e.id?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(ot,{className:`size-3.5 animate-spin`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Subscribing…`})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(Cr,{className:`size-3.5`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Subscribe`})]})})]})]},e.id))})]})]})]})}async function Ewe(e,t,n){let r=await X.getNote(e);if(!r||r.feedOrigin===`feed`||r.retention===`schedule-pinned`||r.retention===`session-pinned`||Array.isArray(r.notebookIds)&&r.notebookIds.length>0&&r.type!==`journal`&&r.type!==`playground`)return;let i=qN(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${JN(n)}${r.rawContent.slice(a.to)}`;await new DR().updateRecord(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function Dwe(e){if(!e)return{pending:void 0,adoptedRuntime:null};let t=Dz.get(e);if(t)return{pending:t,adoptedRuntime:null};let n=jz(e);return n?{pending:{block:n.block,noteId:n.noteId,captured:n.captured,origin:n.origin,returnTo:n.returnTo,scheduleItemId:n.scheduleItemId,sessionDate:n.sessionDate},adoptedRuntime:n.runtime}:{pending:void 0,adoptedRuntime:null}}function Owe(){let{runtimeId:e}=te();return(0,q.jsx)(kwe,{runtimeId:e},e??`missing`)}function kwe({runtimeId:e}){let[t]=be(),n=dt(),[r]=(0,K.useState)(()=>Dwe(e)),i=(0,K.useRef)(r.pending),a=t.get(`note`),o=t.get(`block`),[s,c]=(0,K.useState)(()=>!r.pending&&!!a),[l,u]=(0,K.useState)(void 0),d=(0,K.useRef)(r.pending?.captured??null),f=(0,K.useRef)(!1);(0,K.useEffect)(()=>{if(i.current||!a||!e){c(!1);return}let t=!1;return c(!0),X.getNote(a).then(e=>{if(t)return;if(!e){c(!1);return}let n=Object.values(e.blocks??{}).filter(e=>e.kind===`wod`),r=o?n.find(e=>e.id===o):n[0];if(!r){c(!1);return}let a=e.rawContent.slice(r.from,r.to),s=zs(a,{registeredWidgets:Ns})[0],l=s?.scriptBlock?.content??a,d=nu().read(l,r.sport).statements??[],f={block:{id:r.id,contentId:s?.scriptBlock?.contentId,dialect:r.dialect??`time`,sport:r.sport,startLine:0,endLine:Math.max(0,a.split(/\r?\n/).length-1),content:l,statements:d,state:`idle`,version:r.version,createdAt:e.createdAt,widgetIds:{}},noteId:e.id};i.current=f,u(f),c(!1)}).catch(()=>{t||c(!1)}),()=>{t=!0}},[a,o,e]);let p=(0,K.useCallback)(async()=>{let t=i.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(d.current=t.captured,t.captured.block):(d.current||=t.snapshot?await Yz(t.snapshot,t.block,e,t.origin,void 0,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}):await Xz(t.noteId,t.block,e,t.origin,{deferPersist:!0,...t.scheduleItemId?{scheduleItemId:t.scheduleItemId}:{},...t.sessionDate?{sessionDate:t.sessionDate}:{}}),d.current.block)},[e]);(0,K.useEffect)(()=>{e&&Dz.delete(e)},[e]);let m=r.pending??l,h=(0,K.useRef)(!1),g=(0,K.useCallback)((t,n)=>!n||!e||!m?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):(h.current=n.completed,_R.record({runBlock:m.block,blockId:m.block.id,noteId:m.noteId,resultId:e,...m.block.content?{blockContent:m.block.content}:{},...m.block.dialect?{blockDialect:m.block.dialect}:{},...m.block.sport?{blockSport:m.block.sport}:{},data:n,createdAt:n.endTime||Date.now(),...m.origin?{origin:m.origin}:{},...m.scheduleItemId?{scheduleItemId:m.scheduleItemId}:{},...m.sessionDate?{sessionDate:m.sessionDate}:{}}).then(async()=>{if(bU(),f.current=!0,Nz(e),n.completed)try{await Ewe(m.noteId,m.block.id,e)}catch{}})),[e,m]),_=(0,K.useCallback)(()=>{if(f.current=!0,e&&Nz(e),!m){n(`/`);return}if(h.current&&e){n(AH(e),{replace:!0});return}if(m.returnTo){n(m.returnTo,{replace:!0});return}n(BW(zW(m.noteId)),{replace:!0})},[e,m,n]),v=(0,K.useCallback)(t=>{let n=i.current;if(!e||!n||f.current){t.dispose();return}kz({runtimeId:e,block:n.block,noteId:n.noteId,captured:d.current??n.captured,origin:n.origin,returnTo:n.returnTo,scheduleItemId:n.scheduleItemId,sessionDate:n.sessionDate,runtime:t})},[e]),y=(0,K.useCallback)(t=>{if(!e)return;let n=Az(e);n&&n.runtime!==t&&n.runtime.dispose()},[e]);if(s)return(0,q.jsx)(`main`,{"data-agent-status":`loading`,"aria-busy":!0,role:`status`,className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Preparing workout timer…`});if(!m)return(0,q.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,q.jsxs)(`nav`,{"aria-label":`Workout runner navigation`,className:`flex items-center gap-5 px-6 py-3 border-b bg-background`,children:[(0,q.jsx)(`span`,{className:`text-sm font-semibold tracking-tight`,children:`WOD Wiki`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-home`,onClick:()=>n(`/`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Home`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-journal`,onClick:()=>n(`/journal`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Journal`}),(0,q.jsx)(`button`,{type:`button`,"data-testid":`run-notfound-nav-notebooks`,onClick:()=>n(`/notebooks`),className:`text-sm text-muted-foreground hover:text-foreground transition-colors`,children:`Notebooks`})]}),(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`flex-1 flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,q.jsx)(W0,{}),(0,q.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,q.jsx)(Ri,{className:`w-8 h-8 text-muted-foreground`})}),(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Workout session not found`}),(0,q.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`Runtime not found. Please start the workout from the editor.`})]}),(0,q.jsxs)(`button`,{type:`button`,"data-testid":`run-notfound-go-home`,onClick:()=>n(`/`),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,q.jsx)(da,{className:`w-4 h-4`}),`Go home`]})]})]});let b=m.captured?.note.rawContent??m.snapshot?.rawContent,x=m.scheduleItemId?`Scheduled${m.sessionDate?` · ${m.sessionDate}`:``}`:m.sessionDate?`Logged for ${m.sessionDate}`:`Ad-hoc · Today`;return(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":!1,className:`contents`,children:[(0,q.jsx)(`div`,{"data-testid":Q.RUNNER_CONTEXT_PILL,className:`pointer-events-none fixed left-1/2 top-2.5 z-50 -translate-x-1/2 rounded-full border border-border/70 bg-background/90 px-3 py-1 text-[11px] font-semibold text-foreground shadow-sm backdrop-blur-sm`,children:x}),(0,q.jsx)(z2,{block:m.block,noteContent:b,prepareRun:p,onClose:_,onCompleteWorkout:g,resultId:e,noteId:m.noteId,autoStart:!0,adoptRuntime:r.adoptedRuntime,parkOnUnmount:!0,onPark:v,onRuntimeReady:y})]})}var Awe=new DR;function jwe(){let e=dt(),[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)(null),a=(0,K.useRef)(null),o=async r=>{if(!(!r||t)){n(!0),i(null);try{let t=await lL(r,Awe);if(t.imported+(t.sessionsImported??0)===0){i(t.errors.length>0?t.errors.slice(0,2).join(`; `):`No portable notes or sessions were found in that bundle.`);return}CQ({title:`Imported ${t.imported} note(s), ${t.sessionsImported??0} session(s)`,description:t.errors.length>0?t.errors.slice(0,2).join(`; `):`Import complete.`}),e(Z.home)}catch(e){i(e instanceof Error?e.message:`That file is not a valid portable bundle (.zip).`)}finally{n(!1)}}};return(0,q.jsxs)(`main`,{"data-agent-status":`ready`,"aria-busy":t,"data-testid":`load-zip-intake`,className:`w-full max-w-xl min-w-0 mx-auto px-4 py-10 sm:px-6 flex flex-col gap-4 overflow-x-hidden`,children:[(0,q.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Workout Bundle`}),(0,q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`A portable bundle is the `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.zip`}),` (or`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.md`}),` / `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.jsonl`}),` /`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`.csv`}),`) export from Settings → Data, or a`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`wod export`}),` archive. Importing never runs the workout.`]}),(0,q.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border bg-card p-5 flex flex-col items-center gap-3 text-center`,children:[(0,q.jsx)(_n,{className:`size-6 text-muted-foreground`,"aria-hidden":`true`}),(0,q.jsx)(`input`,{ref:a,type:`file`,accept:`.zip,.md,.markdown,.jsonl,.csv`,"data-testid":`bundle-file-input`,className:`text-xs text-muted-foreground file:mr-3 file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-primary-foreground hover:file:opacity-90 max-w-full`,"aria-label":`Portable bundle file`,disabled:t,onChange:e=>{o(e.target.files?.[0]),e.target.value=``}}),r&&(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`bundle-import-error`,className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:[(0,q.jsx)($i,{className:`size-4 mt-0.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r})]})]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[(0,q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>e(HH(`data`)),children:`Storage settings`}),(0,q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>e(`/`),children:`Back to Home`})]})]})}function Mwe(){let[e]=V(`zip`),[t]=V(`z`),n=Qe(),[r]=(0,K.useState)(()=>{let e=new URLSearchParams(n.search||window.location.search);return!!(e.get(`zip`)||e.get(`z`))}),i=new URLSearchParams(n.search);return e||t||i.get(`zip`)||i.get(`z`)||r?(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,q.jsx)(`div`,{className:`flex-1 flex items-start justify-center`,children:(0,q.jsx)(jwe,{})})}async function x9(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 S9(e={}){let{decodeZip:t=x9,getTodayDateKey:n=mU,isDateInPast:r=hU,journalNotes:i=DU,toast:a=CQ}=e,o=dt(),s=Qe(),{date:c}=te(),[l]=V(`zip`),[u,d]=(0,K.useState)({state:`loading`});return(0,K.useEffect)(()=>{if(!(s.pathname===`/load/journal`||s.pathname.startsWith(`/load/journal/`)))return;if(!l){d({state:`missing-zip`});return}let e=!1,u=async()=>{try{d({state:`loading`});let i;try{i=await t(l)}catch(e){console.error(`Failed to decode zip:`,e),d({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{u()}}),a({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(e)return;let s;if(c){let e=gU(c);if(!e){d({state:`error`,error:`Invalid date format`}),a({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),o(Z.journal,{replace:!0});return}s=e.dateKey}else s=n();if(e)return;if(r(s)){d({state:`pending-confirmation`,content:i,dateKey:s,onConfirmBackdate:async()=>{e||await f(i,s)}});return}await f(i,s)}catch(t){console.error(`Unexpected error in journal zip processor:`,t),e||(d({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{u()}}),a({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},f=async(t,n)=>{if(!e)try{d({state:`creating`});let r=await i.create({journalDate:n,title:n,rawContent:t});e||(o(SH(r.id),{replace:!0}),d({state:`success`,content:t,dateKey:n}))}catch(r){console.error(`Failed to create journal entry:`,r),e||(d({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{f(t,n)}}),a({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return u(),()=>{e=!0}},[l,c,o,t,n,r,i,a]),u}var Nwe=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,K.useState)(!1),[c,u]=(0,K.useState)(!1),d=async()=>{u(!0);try{await t()}finally{u(!1)}},f=async e=>{u(!0),s(!1);try{await n(e)}finally{u(!1)}},p=e?Mw(e):`Date`,m=i||c;return(0,q.jsxs)(`div`,{className:$(`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,q.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:()=>void d(),disabled:m,className:$(`flex items-center gap-2 px-3 py-2 transition-colors hover:bg-accent hover:text-accent-foreground`,m&&`opacity-60 cursor-not-allowed`),children:[c?(0,q.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,q.jsx)(kt,{className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:`Import Today`})]}),(0,q.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,q.jsxs)(nt,{open:o,onOpenChange:s,children:[(0,q.jsxs)(l,{disabled:m,"aria-label":`Plan for future date`,title:`Select a date to plan for the future`,className:$(`flex h-auto rounded-none border-0 bg-transparent items-center gap-1.5 px-2.5 py-2 transition-colors hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,m&&`opacity-60 cursor-not-allowed`),children:[(0,q.jsx)(Re,{className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),e&&(0,q.jsx)(`span`,{className:`leading-none text-xs`,children:p})]}),(0,q.jsx)(Rr,{align:`end`,sideOffset:6,"aria-label":`Plan date`,className:`p-0 w-auto`,children:(0,q.jsx)(i6,{selectedDate:e||null,onDateSelect:e=>void f(e),entryDates:r})})]})]})},Pwe=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let i=jw(new Date(`${e}T00:00:00`));return(0,q.jsxs)(ei,{open:!0,onOpenChange:(e,t)=>{!e&&t.reason!==`action`&&!r&&n()},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{className:`max-w-sm`,children:[(0,q.jsxs)(Do,{children:[(0,q.jsx)(oa,{children:`Backdate Journal Entry`}),(0,q.jsxs)(Xi,{children:[`The date you selected (`,i,`) is in the past. This will create a journal entry for the selected date.`]})]}),(0,q.jsxs)(Oo,{children:[(0,q.jsx)(Sr,{disabled:r,onClick:n,children:`Cancel`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`solid`,disabled:r,action:()=>t(),children:r?`Importing…`:`Import`})]})]})]})},Fwe=new DR,Iwe={h1:({children:e})=>(0,q.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,q.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,q.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,q.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,q.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,q.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,q.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,q.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,q.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,q.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,q.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,q.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,q.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,q.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,q.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,q.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,q.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,q.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,q.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,q.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,q.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,q.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,q.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,q.jsx)(`hr`,{className:`my-6 border-border/50`})};function C9(){let e=dt(),t=S9(),[n,r]=(0,K.useState)(!1),[i,a]=(0,K.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,q.jsxs)(`main`,{"data-agent-status":o===`loading`?`loading`:`ready`,"aria-busy":o===`loading`,className:`flex flex-col flex-1 min-h-0 bg-background`,children:[(0,q.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,q.jsx)(`button`,{type:`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,q.jsx)(je,{className:`h-5 w-5`})}),(0,q.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,q.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,q.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,q.jsx)(J,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`||o===`missing-zip`?null:(0,q.jsx)(Nwe,{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:!1})]}),(0,q.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`missing-zip`&&(0,q.jsx)(Lwe,{}),o===`loading`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,q.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,q.jsx)($i,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,q.jsx)(J,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,q.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,q.jsxs)(`div`,{className:`text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,q.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,q.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,q.jsxs)(`div`,{className:`text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,q.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,q.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,q.jsx)(si,{remarkPlugins:[Fn],components:Iwe,children:s})}):null]}),n&&c&&(0,q.jsx)(Pwe,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function Lwe(){let e=dt(),[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)(null),a=async r=>{if(!(!r||t)){n(!0),i(null);try{let t=await lL(r,Fwe);CQ({title:`Imported ${t.imported} note(s)`,description:t.errors.length>0?t.errors.slice(0,2).join(`; `):`Open the entry from your journal.`}),e(Z.journal)}catch(e){i(e instanceof Error?e.message:`That file is not a valid portable bundle (.zip).`)}finally{n(!1)}}};return(0,q.jsxs)(`div`,{className:`flex flex-col items-center justify-center gap-4 max-w-md min-w-0 mx-auto text-center`,children:[(0,q.jsx)(`h2`,{className:`text-lg font-semibold text-foreground`,children:`This import link is missing its bundle`}),(0,q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`The journal import link carries a compressed bundle in its`,` `,(0,q.jsx)(`code`,{className:`font-mono`,children:`?zip=`}),` parameter. Re-open the original link, or import a portable bundle file directly — entries land in your journal.`]}),(0,q.jsx)(`input`,{type:`file`,accept:`.zip,.md,.markdown,.jsonl,.csv`,"data-testid":`journal-zip-upload`,"aria-label":`Journal bundle file`,disabled:t,className:`text-xs text-muted-foreground file:mr-3 file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-primary-foreground hover:file:opacity-90 max-w-full`,onChange:e=>{a(e.target.files?.[0]),e.target.value=``}}),r&&(0,q.jsxs)(`div`,{role:`alert`,"data-testid":`journal-zip-error`,className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:[(0,q.jsx)($i,{className:`size-4 mt-0.5 shrink-0`,"aria-hidden":`true`}),(0,q.jsx)(`span`,{children:r})]}),(0,q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>e(Z.journal),children:`Back to Journal`})]})}function Rwe(){let{slug:e}=te(),t=Qe(),n=e?.startsWith(`guide-`)?e:`guide-${e??`start`}`;return(0,q.jsx)(at,{to:`/page/${encodeURIComponent(n)}${t.search}${t.hash}`,replace:!0})}function zwe({searchHandlerRef:e,canvasRouteList:t=[],rootUnavailable:n,pageSettlingFallback:r}){return(0,q.jsxs)(lee,{children:[(0,q.jsx)(f,{path:Z.home,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`*`,element:n??(0,q.jsx)(_we,{})}),(0,q.jsx)(f,{path:`/proto/calc-authoring`,element:(0,q.jsx)(iCe,{})}),(0,q.jsx)(f,{path:`/proto/query-block-composer`,element:(0,q.jsx)(mCe,{})}),(0,q.jsx)(f,{path:`/settings`,element:(0,q.jsx)(at,{to:`/settings/appearance`,replace:!0})}),(0,q.jsx)(f,{path:`/settings/appearance`,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsProfile,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:vH.settingsData,element:(0,q.jsx)(at,{to:Z.settingsStorage,replace:!0})}),(0,q.jsx)(f,{path:vH.settingsDatabase,element:(0,q.jsx)(at,{to:Z.settingsStorage,replace:!0})}),(0,q.jsx)(f,{path:Z.settingsStorage,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsSync,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/settings/system`,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:vH.settingsQueries,element:(0,q.jsx)(at,{to:Z.journal,replace:!0})}),(0,q.jsx)(f,{path:Z.settingsTags,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.settingsSoundProfiles,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/settings/library/calcs`,element:(0,q.jsx)(`div`,{className:`p-6`,children:(0,q.jsx)(XCe,{})})}),(0,q.jsx)(f,{path:`/legacy`,element:(0,q.jsx)(rwe,{})}),(0,q.jsx)(f,{path:`/syntax`,element:(0,q.jsx)(gwe,{})}),(0,q.jsx)(f,{path:Z.plan,element:(0,q.jsx)(bwe,{})}),(0,q.jsx)(f,{path:Z.feeds,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.feed,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebooks,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebook,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebookTarget,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notebookItem,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.subscribe,element:(0,q.jsx)(Twe,{})}),(0,q.jsx)(f,{path:Z.pages,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.page,element:r??(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/guide/:slug`,element:(0,q.jsx)(Rwe,{})}),(0,q.jsx)(f,{path:Z.load,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(Mwe,{})})}),(0,q.jsx)(f,{path:Z.loadJournal,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(C9,{})})}),(0,q.jsx)(f,{path:Z.loadJournalDate,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(C9,{})})}),(0,q.jsx)(f,{path:Z.playgroundRoot,element:(0,q.jsx)(Cwe,{})}),(0,q.jsx)(f,{path:Z.playground,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.playgrounds,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.notes,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.note,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.journal,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.day,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.run,element:(0,q.jsx)(K.Suspense,{fallback:(0,q.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-muted-foreground`,children:`Loading…`}),children:(0,q.jsx)(Owe,{})})}),(0,q.jsx)(f,{path:Z.tracker,element:(0,q.jsx)(ywe,{})}),(0,q.jsx)(f,{path:`/results/segments`,element:(0,q.jsx)(vwe,{})}),(0,q.jsx)(f,{path:Z.sessionDetail,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.sessions,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.sessionDate,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:`/review/:runtimeId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review/:sectionId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,q.jsx)(y9,{})}),(0,q.jsx)(f,{path:Z.efforts,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.effort,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.equipment,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.equipmentSlug,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tags,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tagCategory,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.tag,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.dashboards,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),(0,q.jsx)(f,{path:Z.dashboardView,element:(0,q.jsx)(x7,{searchHandlerRef:e})}),t.map(({route:t})=>(0,q.jsx)(f,{path:t,element:(0,q.jsx)(x7,{searchHandlerRef:e})},t))]})}var w9=`G-PROD-ID`,T9=!1;function E9(){if(T9||typeof document>`u`)return;T9=!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=${w9}`,document.head.appendChild(e),window.gtag(`js`,new Date),window.gtag(`config`,w9,{send_page_view:!1})}function D9(e,t){typeof window>`u`||!$R.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:QR()})}$R.setForwarder(e=>{window.gtag?.(`event`,e.name,e.payload??{})}),$R.consent?E9():$R.subscribeConsent(e=>{e&&(E9(),D9())});function Bwe(){let e=Qe();return(0,K.useEffect)(()=>{let t=e.pathname;if(!t.startsWith(`/effort/`)&&!t.startsWith(`/playground/`)&&!t.startsWith(`/equipment/`)){let e=`Wod.Wiki`;t.startsWith(`/day/`)?e=`Wod.Wiki - Day`:t.startsWith(`/journal`)?e=`Wod.Wiki - Journal`:t.startsWith(`/notebooks`)||t.startsWith(`/notebook/`)?e=`Wod.Wiki - Notebooks`:t===`/notes`?e=`Wod.Wiki - Notes`:t.startsWith(`/note/`)?e=`Wod.Wiki - Note`:t.startsWith(`/pages`)||t.startsWith(`/page/`)?e=`Wod.Wiki - Pages`:t.startsWith(`/tags`)||t.startsWith(`/t/`)?e=`Wod.Wiki - Tags`:t===`/feeds`?e=`Wod.Wiki - Feeds`:t.startsWith(`/feed/`)?e=`Wod.Wiki - Feed`:t.startsWith(`/efforts`)?e=`Wod.Wiki - Efforts`:t.startsWith(`/equipment`)?e=`Wod.Wiki - Equipment`:t.startsWith(`/sessions`)||t.startsWith(`/session/`)?e=`Wod.Wiki - Sessions`:t.startsWith(`/dashboards`)||t.startsWith(`/dashboard/`)?e=`Wod.Wiki - Dashboards`:t.startsWith(`/playgrounds`)&&(e=`Wod.Wiki - Playgrounds`),document.title=e}let n=setTimeout(()=>{D9(document.title,e.pathname+e.search)},0);return()=>clearTimeout(n)},[e.pathname]),null}function Vwe(e={}){let{decodeZip:t=x9,intake:n=w$,toast:r=CQ}=e,i=dt(),a=Qe(),[o]=V(`zip`),[s]=V(`z`),[c]=V(`by`),[l]=V(`src`),u=(0,K.useRef)(null);(0,K.useEffect)(()=>{if(a.pathname!==`/load`&&!(a.pathname===`/`&&s))return;if(s){let e=`${s}:${c??``}`;if(u.current===e)return;u.current=e;let a=!1;return(async()=>{try{let e=await t(s);if(e===null)throw Error(`Invalid workout link`);if(a)return;let r=Mve(e,c??void 0);if(await n.ensureEntry(r,{reuseKey:`home`,title:`Home playground`}),a)return;Nve({content:r,by:c??void 0})}catch(e){console.error(`Failed to decode zip:`,e),a||r({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}a||i(`/`,{replace:!0})})(),()=>{a=!0}}if(!o)return;let e=!1,d=l&&l.startsWith(`/`)?l:void 0;return(async()=>{try{let r=await t(o);if(r===null)throw Error(`Invalid workout link`);if(e)return;let a=d?await n.createPage(r,{sourcePath:d}):await n.createPage(r);e||i(yH(a),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),e||(r({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),i(Z.home,{replace:!0}))}})(),()=>{e=!0}},[o,s,c,l,i,a.pathname,t,n,r])}var O9=null,Hwe=1,k9=new Set;function A9(){for(let e of k9)e()}function j9(e){return O9&&O9.resolve(!1),new Promise(t=>{let n=Hwe++;O9={id:n,request:e,resolve:e=>{O9?.id===n&&(O9=null,A9()),t(e)}},A9()})}async function M9(e,t){let n=t&&typeof t==`object`?t:void 0,r=n?.client?.requestUserInteraction??n?.requestUserInteraction;return typeof r==`function`?r(()=>j9(e)):j9(e)}var Uwe=()=>{let e=(0,K.useSyncExternalStore)(e=>(k9.add(e),()=>k9.delete(e)),()=>O9,()=>null);return e?(0,q.jsx)(`div`,{"data-agent-hidden":``,children:(0,q.jsxs)(ei,{open:!0,onOpenChange:t=>{t||e.resolve(!1)},children:[(0,q.jsx)(Tr,{}),(0,q.jsxs)(Mn,{"data-testid":`agent-confirm-dialog`,children:[(0,q.jsxs)(Do,{children:[(0,q.jsxs)(oa,{className:`flex items-center gap-2 text-destructive`,children:[(0,q.jsx)(oe,{className:`size-5 shrink-0`,"aria-hidden":`true`}),`Confirm Agent Action`]}),(0,q.jsxs)(Xi,{children:[`An AI agent requested a destructive operation (`,(0,q.jsx)(`strong`,{children:e.request.action}),`).`]})]}),(0,q.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/40 p-3 text-xs space-y-1`,children:[(0,q.jsx)(`div`,{className:`font-medium text-foreground`,children:e.request.summary}),(0,q.jsxs)(`div`,{className:`font-mono text-muted-foreground`,children:[`Target: `,(0,q.jsx)(`span`,{"data-testid":`agent-confirm-target`,children:e.request.targetId})]})]}),(0,q.jsxs)(Oo,{className:`gap-2 sm:gap-0`,children:[(0,q.jsx)(Sr,{"data-testid":`agent-confirm-cancel`,onClick:()=>e.resolve(!1),children:`Deny`}),(0,q.jsx)(Sr,{value:`confirm`,"data-variant":`destructive`,"data-testid":`agent-confirm-approve`,onClick:()=>e.resolve(!0),children:`Approve Action`})]})]})]})}):null};function Wwe(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var Gwe=()=>{let e=Qe(),t=RZ(),n=zZ(),r=tZ(),i=EX(),a=MX(),o=RW(),s=bX(),c=RX(),l=(0,K.useSyncExternalStore)(e0,$1,()=>null),u=r||t===`preparing`||n,d=(0,K.useMemo)(()=>{let r=i&&o&&o.pathname===e.pathname?o:null;return Wwe({schemaVersion:`1.0`,build:MJ,hydrated:!0,status:u?`loading`:`ready`,feedReadiness:t,importPending:n,route:{pathname:e.pathname,search:e.search,hash:e.hash},stream:i?{route:i.route,query:i.query,defaultQuery:i.defaultQuery,layout:i.layout,availableLayouts:i.availableLayouts,groupBy:i.groupBy??null,loading:i.loading,totalUnbatchedCount:r?r.entries.length:null,sampleEntries:r?r.entries.slice(0,25).map(e=>({id:e.id,title:e.title,date:e.date??null,notebookId:e.notebookId??null})):[]}:null,explorer:a?{draft:a.draft,submitted:a.submitted,weeks:a.weeks,loading:a.loading,saveReady:a.saveReady}:null,editor:s?{noteId:s.noteId??null,readonly:s.readonly,sourceRevision:s.sourceRevision??null,workoutBlockIds:s.getBlocks().map(e=>e.id)}:null,results:c?{resultId:c.resultId,activeTab:c.activeTab,mobileViewMode:c.mobileViewMode,sourceDrawerOpen:c.sourceDrawerOpen,addToDashboardOpen:c.addToDashboardOpen}:null,clock:l})},[u,t,n,e.pathname,e.search,e.hash,i,a,o,s,c,l]);return(0,q.jsx)(`script`,{id:`agent-view-state`,type:`application/json`,dangerouslySetInnerHTML:{__html:d}})},N9=class extends Error{code=`CONFIRMATION_REQUIRED`;targetId;action;constructor(e,t){super(t??`Destructive action '${e.action}' on '${e.targetId}' requires confirmation (${e.summary}).`),this.name=`AgentConfirmationRequiredError`,this.action=e.action,this.targetId=e.targetId}};function P9(e){return e}async function F9(e,t,n){if(n===void 0||n!==t.targetId){if(e.confirmDestructive){let n=e.confirmTimeoutMs??1500,r;if(await Promise.race([e.confirmDestructive(t).finally(()=>{r!==void 0&&clearTimeout(r)}),new Promise(e=>{r=setTimeout(()=>e(!1),n)})]))return;throw new N9(t,`User declined or did not confirm '${t.action}' on '${t.targetId}'.`)}throw new N9(t,`Destructive action '${t.action}' requires confirmId="${t.targetId}" (or --yes "${t.targetId}" on CLI).`)}}function I9(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Kwe(e){let t=e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);for(let e of t.split(/\r?\n/)){let t=e.match(/^#\s+(.+)$/);if(t?.[1]?.trim())return t[1].trim()}}function L9(e,t,n){let r=e.trim();if(!r)return n?`# ${n}\n`:``;let i=e.replace(/^(\s*`{3,})(?:wod|whiteboard)(?=(?::[\w-]+)?\s*$)/gim,`$1time`);if(zs(i,{registeredWidgets:Ns}).some(e=>e.scriptBlock)||/^---\r?\n/.test(i)||/^#\s+/m.test(i))return i.endsWith(`
|
|
1201
1201
|
`)?i:`${i}\n`;let a=3;for(let e of i.matchAll(/`+/g))a=Math.max(a,e[0].length+1);let o="`".repeat(a);return`${n?`# ${n}\n\n`:``}${o}time${t?`:${t}`:``}\n${r}\n${o}\n`}function R9(e,t=Date.now()){if(!e||e.trim().toLowerCase()===`today`){let e=new Date(t);return`${e.getUTCFullYear()}-${String(e.getUTCMonth()+1).padStart(2,`0`)}-${String(e.getUTCDate()).padStart(2,`0`)}`}let n=e.trim();if(!/^\d{4}-\d{2}-\d{2}$/.test(n))throw Error(`Invalid date '${e}'; expected YYYY-MM-DD or 'today'.`);return n}function qwe(e){return new Sb(vS(e))}async function z9(e,t,n,r){let i=new Set(r.map(e=>e.id));for(let r of n)i.has(r.id)||await e.readwrite(t).delete(r.id);let a=new Map(n.map(e=>[e.id,e]));for(let n of r)Vx(a.get(n.id),n)||(t===`block_index`&&`blockVersion`in n&&await e.readwrite(`block_index`).put(n),t===`block_efforts`&&`effortSlug`in n&&await e.readwrite(`block_efforts`).put(n),t===`block_equipment`&&`equipmentSlug`in n&&await e.readwrite(`block_equipment`).put(n))}async function B9(e,t){let n=t.now??Date.now(),r=Ub(t.rawContent),i=t.noteId??r?.noteId??I9(),a=t.tags??Yb(t.rawContent);return e.transaction([`notes`,`block_revisions`,`note_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`tags`,`note_tags`,`page`,`page_notes`,`schedule_items`,`sessions`,`notebook_links`],`readwrite`,async e=>{let o=await e.readonly(`notes`).get(i);if(o){let e=Wy(o),t=Uy(o);if(!(o.seedOrigin!==`seed`&&o.feedOrigin!==`feed`&&Os(o,e,t)))throw Error(`Note '${i}' is read-only (seed/feed). Clone it first with wod_note_clone before editing.`)}if(t.expectedSourceRevision!==void 0&&(o?.sourceRevision??0)!==t.expectedSourceRevision)throw Error(`CONFLICT: Stale sourceRevision on note '${i}': expected ${t.expectedSourceRevision}, actual ${o?.sourceRevision??0}.`);let s=o&&o.rawContent===t.rawContent?o.sourceRevision:(o?.sourceRevision??0)+1,c=await e.readonly(`block_revisions`).getAllFromIndex(`by-note`,i),l=new Map;for(let e of c)(l.get(e.blockId)?.version??0)<e.version&&l.set(e.blockId,e);let u=0,d=Vs(t.rawContent,{sourceRevision:s,blocks:o?.blocks,registeredWidgets:Ns,createId:()=>{for(;;){let e=`blk-${i.slice(0,8)}-${u++}`;if(!l.has(e))return e}}});Hs(t.rawContent,d,s,{registeredWidgets:Ns});let f=[];for(let e of Object.values(d)){let r=l.get(e.id),a=t.rawContent.slice(e.from,e.to),o=r&&r.rawContent===a&&r.kind===e.kind&&r.dialect===e.dialect&&r.sport===e.sport;e.version=o?r.version:(r?.version??0)+1,o||f.push({noteId:i,blockId:e.id,version:e.version,kind:e.kind,rawContent:a,savedAt:n,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}if(o?.rawContent===t.rawContent&&!Vx(o.blocks,d)){s+=1;for(let e of Object.values(d))e.sourceRevision=s}let p=t.title??r?.title??Kwe(t.rawContent)??o?.title??`Untitled Workout`,m=t.notebookId?Cs(t.notebookId):o?.notebookId,h=m?Array.from(new Set([...o?.notebookIds??[],m])):o?[...o.notebookIds??[]]:[],g=a.map(e=>e.label),_=t.type??o?.type??(t.journalDate?`journal`:`note`);if(o&&(o.rawContent!==t.rawContent||o.title!==p||o.type!==_||!Vx(o.blocks,d)||!Vx(o.tags??[],g))&&await GC(e,i)&&(await KC(e,o,n),s<=o.sourceRevision)){s=o.sourceRevision+1;for(let e of Object.values(d))e.sourceRevision=s}let v=t.journalDate?Date.parse(`${R9(t.journalDate,n)}T12:00:00Z`):o?.date??n,y={...o??{},id:i,title:p,rawContent:t.rawContent,sourceRevision:s,blocks:d,type:_,date:v,createdAt:o?.createdAt??n,notebookIds:h,...m&&m!==`notebook/journal`?{notebookId:m}:{},tags:g,seedOrigin:`user`},b=await e.readonly(`efforts`).getAll(),x=new Map;for(let e of Xd)x.set(e.slug,e);for(let e of b)x.set(e.slug,e);let S=nf({efforts:[...x.values()],equipment:await e.readonly(`equipment`).getAll()}),C=await e.readonly(`block_index`).getAllFromIndex(`by-note`,i),w=await e.readonly(`block_efforts`).getAllFromIndex(`by-note`,i),T=await e.readonly(`block_equipment`).getAllFromIndex(`by-note`,i),E=new Map(C.map(e=>[e.id,e])),D=[],O=[],k=[],A=new Set,j=new Set;for(let[e,r]of Object.values(d).sort((e,t)=>e.from-t.from).entries()){let a=`${i}:${r.id}`,o=E.get(a),c=t.rawContent.slice(r.from,r.to),l=zs(c,{registeredWidgets:Ns})[0]?.displayContent??c,u=r.kind===`wod`?os(l):void 0;if(D.push({...o??{},id:a,noteId:i,blockId:r.id,blockVersion:r.version,dataType:r.kind,sourceRevision:s,from:r.from,to:r.to,position:e,rawContent:c,noteTitle:y.title,createdAt:o?.createdAt??n,...u?{blockContentId:u}:{},...y.notebookId?{notebookId:y.notebookId}:{}}),r.kind===`wod`){let e=eu(l,{...r.sport?{sport:r.sport}:{},references:S}),t=rf(e.statements),a=new Set(t.efforts);if(a.size===0)for(let t of e.statements){let e=t.metrics?.getMetric?.(Y.Effort),n=(typeof e?.value==`string`?e.value:``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``);n&&![`rest`,`amrap`,`emom`,`tabata`,`for-time`].includes(n)&&a.add(n)}for(let e of a){A.add(e);let t=`${i}:${r.id}:${e}`,a=w.find(e=>e.id===t);O.push({...a??{},id:t,noteId:i,blockId:r.id,...u?{blockContentId:u}:{},effortSlug:e,createdAt:a?.createdAt??n})}for(let e of t.equipment){j.add(e);let t=`${i}:${r.id}:${e}`,a=T.find(e=>e.id===t);k.push({...a??{},id:t,noteId:i,blockId:r.id,...u?{blockContentId:u}:{},equipmentSlug:e,createdAt:a?.createdAt??n})}}}Vx(o,y)||await e.readwrite(`notes`).put(y),f.length>0&&await e.readwrite(`block_revisions`).putMany(f),await z9(e,`block_index`,C,D),await z9(e,`block_efforts`,w,O),await z9(e,`block_equipment`,T,k);let M=await e.readonly(`note_tags`).getAllFromIndex(`by-note`,i),N=new Map;for(let t of a){let r=t.label.trim();if(!r)continue;let a=(await e.readonly(`tags`).getAllFromIndex(`by-label`,r))[0],o=a?{...a,...!a.type&&t.type?{type:t.type}:{}}:{id:I9(),label:r,...t.type?{type:t.type}:{},createdAt:n};Vx(a,o)||await e.readwrite(`tags`).put(o);let s=M.find(e=>e.tagId===o.id)?.id??`${i}:${o.id}`;N.set(s,{id:s,noteId:i,tagId:o.id})}for(let t of M)N.has(t.id)||await e.readwrite(`note_tags`).delete(t.id);for(let t of N.values())await e.readwrite(`note_tags`).put(t);let P=h.map(e=>({id:IS(Cs(e),`note`,i),notebookId:Cs(e),targetKind:`note`,targetId:i,noteId:i,createdAt:n}));P.length>0&&await e.readwrite(`notebook_links`).putMany(P);let F;if(t.journalDate){let r=R9(t.journalDate,n),a;try{a=await e.readonly(`page`).getAllFromIndex(`by-date`,r)}catch{a=(await e.readonly(`page`).getAll()).filter(e=>e.date===r)}let o=a[0];o||(o={id:I9(),date:r,title:r,createdAt:n},await e.readwrite(`page`).put(o));let s=await e.readonly(`page_notes`).getAllFromIndex(`by-page`,o.id);if(!s.some(e=>e.noteId===i)){let t=s.reduce((e,t)=>typeof t.position==`number`&&t.position>e?t.position:e,-1);await e.readwrite(`page_notes`).put({id:I9(),pageId:o.id,noteId:i,position:t+1,createdAt:n})}try{let t=await e.readonly(`schedule_items`).getAllFromIndex(`by-date`,r),a=t.find(e=>e.noteId===i);if(a)F=a.id;else{let a=t.reduce((e,t)=>typeof t.position==`number`&&t.position>e?t.position:e,-1),s=I9();await e.readwrite(`schedule_items`).put({id:s,date:r,noteId:i,pageId:o.id,...y.notebookId?{sourceNotebookId:y.notebookId}:{},fallbackTitle:y.title,position:a+1,status:`planned`,createdAt:n,updatedAt:n}),F=s}}catch{}}return{note:y,created:!o,blockCount:D.length,effortSlugs:[...A],equipmentSlugs:[...j],tagLabels:a.map(e=>e.label),...F?{scheduleItemId:F}:{}}})}async function Jwe(e,t){return e.transaction([`notes`,`attachments`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`notebook_links`,`meta`],`readwrite`,async e=>{let n=await e.readonly(`notes`).get(t);if(!n)return!1;await e.readwrite(`notes`).delete(t);for(let n of await e.readonly(`attachments`).getAllFromIndex(`by-note`,t))await e.readwrite(`attachments`).delete(n.id);for(let n of await e.readonly(`note_tags`).getAllFromIndex(`by-note`,t))await e.readwrite(`note_tags`).delete(n.id);for(let n of await e.readonly(`block_index`).getAllFromIndex(`by-note`,t))await e.readwrite(`block_index`).delete(n.id);for(let n of await e.readonly(`block_efforts`).getAllFromIndex(`by-note`,t))await e.readwrite(`block_efforts`).delete(n.id);for(let n of await e.readonly(`block_equipment`).getAllFromIndex(`by-note`,t))await e.readwrite(`block_equipment`).delete(n.id);for(let n of await e.readonly(`page_notes`).getAllFromIndex(`by-note`,t))await e.readwrite(`page_notes`).delete(n.id);try{for(let n of await e.readonly(`schedule_items`).getAllFromIndex(`by-note`,t))await e.readwrite(`schedule_items`).delete(n.id)}catch{}try{for(let n of await e.readonly(`notebook_links`).getAllFromIndex(`by-note`,t))await e.readwrite(`notebook_links`).delete(n.id)}catch{}return(n.seedOrigin===`seed`||n.seedChunkId!==void 0||n.sourcePath!==void 0)&&await e.readwrite(`meta`).put({key:Jx(t),value:Date.now()}),!0})}async function Ywe(e,t){return e.transaction([`sessions`,`events`,`notebook_links`],`readwrite`,async e=>{if(!await e.readonly(`sessions`).get(t))return!1;await e.readwrite(`sessions`).delete(t);let n=await e.readonly(`events`).getAll();for(let r of n)r.resultId===t&&await e.readwrite(`events`).delete(r.id);try{let n=await e.readonly(`notebook_links`).getAll();for(let r of n)r.targetKind===`session`&&r.targetId===t&&await e.readwrite(`notebook_links`).delete(r.id)}catch{}return!0})}function V9(e,t=``){return`${t.replace(/\/+$/,``)}/note/${encodeURIComponent(e.id)}`}var Xwe=P9({name:`wod_catalog_lookup`,title:`Lookup Efforts, Equipment & Tags`,description:"Search or inspect the Effort movement registry, Equipment catalog, Tags, and Tag Categories with Notebook-scoped override precedence (`notebook/defaults` -> Feed/Notebook -> `notebook/custom`).",tier:0,domain:`catalog`,annotations:{title:`Lookup Catalog`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({kind:Qt([`effort`,`equipment`,`tag`,`tag-type`]).describe(`Catalog family to search or inspect.`),search:G().optional().describe(`Case-insensitive slug, label, or alias filter.`),slug:G().optional().describe(`Exact canonical slug/name to look up.`),notebookId:G().optional().describe(`Optional Notebook scope for property inheritance resolution.`),limit:se().int().min(1).max(250).optional().describe(`Max entries to return (default 50).`)}),cliEquivalent:`wod catalog <efforts|equipment|tags> --json`,async execute(e,t){let n=await dS(t.storage,{...e.notebookId?{notebookId:e.notebookId}:{},mode:`custom-runtime`}),r=e.limit??50,i=e.search?.trim().toLowerCase(),a=e.slug?.trim().toLowerCase();if(e.kind===`effort`){let e=new Map;for(let t of Xd)e.set(t.slug,t);for(let t of n.efforts)e.set(t.slug,t);let t=[...e.values()].filter(e=>a?e.slug.toLowerCase()===a:!i||e.slug.toLowerCase().includes(i)||e.label.toLowerCase().includes(i)||(e.aliases??[]).some(e=>e.toLowerCase().includes(i)));return{kind:`effort`,totalCount:t.length,items:t.slice(0,r).map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[],met:e.baseAttributes?.met,scope:n.originByKey.get(`effort:${e.slug}`)??`notebook/defaults`,...a?{markdown:Xb(e)}:{}}))}}if(e.kind===`equipment`){let e=n.equipment.filter(e=>a?e.slug.toLowerCase()===a:!i||e.slug.toLowerCase().includes(i)||e.label.toLowerCase().includes(i)||(e.aliases??[]).some(e=>e.toLowerCase().includes(i)));return{kind:`equipment`,totalCount:e.length,items:e.slice(0,r).map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[],scope:n.originByKey.get(`equipment:${e.slug}`)??`notebook/defaults`,...a?{markdown:Zb(e)}:{}}))}}if(e.kind===`tag`){let e=n.tags.filter(e=>a?e.label.toLowerCase()===a:!i||e.label.toLowerCase().includes(i)||(e.type??``).toLowerCase().includes(i));return{kind:`tag`,totalCount:e.length,items:e.slice(0,r).map(e=>({id:e.id,label:e.label,type:e.type??`general`,contributions:e.contributions??[],scope:n.originByKey.get(`tag:${e.label}`)??`notebook/defaults`}))}}let o=n.tagTypes.filter(e=>a?e.name.toLowerCase()===a:!i||e.name.toLowerCase().includes(i)||e.label.toLowerCase().includes(i));return{kind:`tag-type`,totalCount:o.length,items:o.slice(0,r)}}}),Zwe=yi({kind:Qt([`effort`,`equipment`,`tag`,`tag-type`]).describe(`Property definition family to create or override.`),slug:G().min(1).describe(`Canonical kebab-case slug (e.g. "kettlebell-swing", "barbell").`),label:G().optional().describe(`Human-readable display label.`),targetNotebookId:G().optional().describe(`Target Notebook scope: defaults to "notebook/custom" (personal runtime) or a writable user Notebook.`),markdown:G().optional().describe(`Full Property Note Markdown with YAML frontmatter. If omitted, synthesized from structured fields below.`),met:se().positive().optional().describe(`MET metabolic equivalent (for kind="effort", default 5.0).`),aliases:me(G()).optional().describe(`Optional movement/equipment aliases.`),category:G().optional().describe(`Tag category when kind="tag" (e.g. "equipment", "quality", "format").`),color:G().optional().describe(`Hex color when kind="tag-type" (e.g. "#10b981").`)});function Qwe(e){if(e.markdown?.trim())return e.markdown;let t=e.slug.trim().toLowerCase(),n=e.label?.trim()||t,r=e.aliases&&e.aliases.length>0?`\naliases:\n${e.aliases.map(e=>` - ${JSON.stringify(e)}`).join(`
|
|
1202
|
-
`)}`:``;if(e.kind===`effort`){let i=e.met??5;return`---\nid: effort-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}${r}\nbaseAttributes:\n met: ${i}\n---\n\n# ${n}\n`}if(e.kind===`equipment`)return`---\ntype: equipment\nid: equipment-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}${r}\n---\n\n# ${n}\n`;if(e.kind===`tag`){let r=e.category??`general`;return`---\ntype: tag\nid: tag-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}\ncategory: ${r}\n---\n\n# ${n}\n`}let i=e.color??`#6366f1`;return`---\ntype: tag-type\nid: type-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}\ncolor: ${JSON.stringify(i)}\n---\n\n# ${n}\n`}var $we=[Xwe,P9({name:`wod_catalog_upsert`,title:`Save Effort, Equipment, or Tag Property Note`,description:"Create or update a Scoped Property Override (`effort`, `equipment`, `tag`, or `tag-type`) in `notebook/custom` or a shared user Notebook.",tier:1,domain:`catalog`,annotations:{title:`Save Catalog Property`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Zwe,cliEquivalent:`wod catalog save <kind> <file|-> --json`,async execute(e,t){let n=Qwe(e),r=await lS(t.storage,{targetNotebookId:e.targetNotebookId??`notebook/custom`,kind:e.kind,slug:e.slug,rawContent:n,title:e.label,category:e.category});return await t.onMutated?.([`notes`,`block_revisions`,`property_overrides`,`efforts`,`equipment`,`tags`,`tag_types`]),{id:r.id,kind:r.kind,slug:r.slug,label:r.label,notebookId:r.notebookId,ownerNoteId:r.ownerNoteId}}})],eTe=[P9({name:`wod_feed_manage`,title:`Manage Feeds & Portability`,description:"Inspect installed Seed/Feed sources (`list`), check unpublished public Notebook changes (`status`), compile and publish public Notebooks (`publish`), import portable Markdown + JSONL/CSV files (`import-bundle`), or subscribe/unsubscribe/delete a Feed source.",tier:1,domain:`feed`,annotations:{title:`Manage Feeds`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({action:Qt([`list`,`status`,`publish`,`import-bundle`,`subscribe`,`unsubscribe`,`delete`]).describe(`Feed or portability operation to run.`),sourceId:G().min(1).optional().describe(`Target Feed source ID when action is "subscribe", "unsubscribe", or "delete".`),notebookIds:me(G().min(1)).optional().describe(`Optional subset of Notebook IDs when action="subscribe".`),url:G().min(1).optional().describe(`Optional Feed manifest URL when subscribing to a custom source.`),confirmId:G().optional().describe(`Confirmation token (must match sourceId) for non-interactive unsubscribe/delete calls.`),notebookSlug:G().optional().describe(`Optional Notebook slug filter when publishing.`),name:G().optional().describe(`Optional Feed display name when publishing or subscribing.`),description:G().optional().describe(`Optional Feed description when publishing.`),files:me(yi({path:G().min(1),content:G()})).optional().describe('Portable `.md` / `.jsonl` / `.csv` files when action="import-bundle".')}),cliEquivalent:`wod feed <list|status|publish|subscribe|unsubscribe|delete> --json`,async execute(e,t){if(e.action===`list`){let e=await t.storage.readonly(`meta`).getAll(),n=await mC(t.storage),r=[];for(let t of e){let e=t;if(typeof e.key==`string`&&e.key.startsWith(`seed:`)&&e.key!==bx(`user`)){let t=e.key.slice(5),i=n[t];r.push({sourceId:t,seedVersion:e.seedVersion,builtAt:e.builtAt,importedAt:e.importedAt,chunkCount:Object.keys(e.chunks??{}).length,subscribed:i?.subscribed??!0,offlinePolicy:i?.offlinePolicy??(t===`core`?`offline-full`:`index-only`),autoSync:i?.autoSync??t===`core`})}}return{action:`list`,installedCount:r.length,feeds:r,subscriptions:n}}if(e.action===`subscribe`){if(!e.sourceId)throw Error('Provide `sourceId` when action="subscribe".');let n=t.feedLifecycle?.subscribe?await t.feedLifecycle.subscribe(e.sourceId,{notebookIds:e.notebookIds,url:e.url,name:e.name}):await hC(t.storage,e.sourceId,{notebookIds:e.notebookIds,url:e.url,name:e.name});return await t.onMutated?.([`meta`,`notes`]),{action:`subscribe`,...n}}if(e.action===`unsubscribe`){if(!e.sourceId)throw Error('Provide `sourceId` when action="unsubscribe".');if(e.sourceId===`core`)throw Error(`Core feed cannot be unsubscribed.`);await F9(t,{action:`wod_feed_manage:unsubscribe`,targetId:e.sourceId,summary:`Unsubscribe from feed '${e.sourceId}' and purge its imported notes`},e.confirmId);let n=t.feedLifecycle?.unsubscribe?await t.feedLifecycle.unsubscribe(e.sourceId):await gC(t.storage,e.sourceId);return await t.onMutated?.([`meta`,`notes`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`property_overrides`]),{action:`unsubscribe`,...n}}if(e.action===`delete`){if(!e.sourceId)throw Error('Provide `sourceId` when action="delete".');if(e.sourceId===`core`)throw Error(`Core feed cannot be deleted.`);await F9(t,{action:`wod_feed_manage:delete`,targetId:e.sourceId,summary:`Delete feed source '${e.sourceId}' and purge all of its imported notes`},e.confirmId);let n=t.feedLifecycle?.delete?await t.feedLifecycle.delete(e.sourceId):await _C(t.storage,e.sourceId);return await t.onMutated?.([`meta`,`notes`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`property_overrides`]),{action:`delete`,...n}}if(e.action===`status`)return{action:`status`,...await FS(t.storage,t.feedTree)};if(e.action===`publish`){let n=t.feedTree??new DS,r=await PS(t.storage,n,{layout:`feed`,notebookSlug:e.notebookSlug,name:e.name,description:e.description});return await t.onMutated?.([`meta`,`property_overrides`]),{action:`publish`,notebooks:r.notebooks,totalNotes:r.totalNotes,totalPublicSessions:r.totalPublicSessions,manifestVersion:r.manifest.version,manifestSha256:r.manifestSha256}}if(!e.files||e.files.length===0)throw Error('Provide non-empty `files` array when action="import-bundle".');let n=await zoe(t.storage,e.files,{defaultNotebookId:e.notebookSlug});return await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`tags`,`note_tags`,`sessions`,`events`]),{action:`import-bundle`,...n}}}),P9({name:`wod_export_bundle`,title:`Export Portable Markdown & Telemetry Bundle`,description:"Export user Notes and attached Session telemetry directly as structured `{ path, content }` strings (Markdown + JSONL/CSV) without triggering synthetic browser file downloads.",tier:0,domain:`feed`,annotations:{title:`Export Portable Bundle`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteIds:me(G()).optional().describe(`Optional Note IDs to export (defaults to all user-owned Notes).`),telemetryFormat:Qt([`jsonl`,`csv`,`both`]).optional().describe(`Format for companion Session/Event telemetry files (default "jsonl").`)}),cliEquivalent:`wod export note <id> -o -`,async execute(e,t){let n=await Roe(t.storage,{noteIds:e.noteIds,telemetryFormat:e.telemetryFormat??`jsonl`});return{fileCount:n.length,files:n}}}),P9({name:`wod_reset_storage`,title:`Wipe Storage Data`,description:`Wipe user Notes, Sessions, Events, and Notebook data from the active storage backend (Tier 2 destructive — requires explicit user confirmation).`,tier:2,domain:`system`,annotations:{title:`Wipe Storage Data`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({confirmToken:G().optional().describe(`For non-interactive MCP/CLI calls, pass confirmToken="WIPE_STORAGE" to confirm wiping user storage.`)}),cliEquivalent:`wod reset --yes WIPE_STORAGE --json`,async execute(e,t){return await F9(t,{action:`wod_reset_storage`,targetId:`WIPE_STORAGE`,summary:`Wipe all user Notes, Sessions, and telemetry from WOD Wiki storage`},e.confirmToken),await t.storage.wipe(),await t.onMutated?.([`notes`,`sessions`,`events`,`page`,`page_notes`,`notebook_links`]),{wiped:!0}}})],tTe=[P9({name:`wod_journal_day`,title:`Get Journal Day`,description:"Fetch all scheduled/authored workout Notes and recorded Sessions for a specific Journal calendar day (`YYYY-MM-DD` or `today`).",tier:0,domain:`journal`,annotations:{title:`Get Journal Day`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({date:G().optional().describe(`Calendar date in YYYY-MM-DD format, or "today" (defaults to "today").`)}),cliEquivalent:`wod journal [today|YYYY-MM-DD] --json`,async execute(e,t){let n=R9(e.date),r=await aw(t.storage,n),i=Date.parse(`${n}T00:00:00Z`),a=Date.parse(`${n}T23:59:59.999Z`),o;try{o=await t.storage.readonly(`page`).getAllFromIndex(`by-date`,n)}catch{o=(await t.storage.readonly(`page`).getAll()).filter(e=>e.date===n)}let s=o[0],c=[];if(s){let e=cs(await t.storage.readonly(`page_notes`).getAllFromIndex(`by-page`,s.id));for(let t of e)c.includes(t.noteId)||c.push(t.noteId)}let l=await t.storage.readonly(`notes`).getAll(),u=new Map(l.map(e=>[e.id,e])),d=[],f=new Set;for(let{item:e,note:t}of r.planned){let n=t??u.get(e.noteId);n&&!f.has(n.id)&&(d.push(n),f.add(n.id))}for(let e of c){let t=u.get(e);t&&!f.has(t.id)&&(d.push(t),f.add(t.id))}for(let e of l){if(f.has(e.id)||e.seedOrigin===`seed`||e.feedOrigin===`feed`||e.id.startsWith(`notebook/`)&&e.notebookId===e.id)continue;let t=e.date??e.createdAt;t>=i&&t<=a&&(d.push(e),f.add(e.id))}let p=new Map;for(let e of r.planned)for(let t of e.pairedSessions)p.set(t.id,t);for(let e of r.adhocSessions)p.set(e.session.id,e.session);let m=Array.from(p.values()).sort((e,t)=>e.startTime-t.startTime);for(let e of m){if(f.has(e.noteId))continue;let t=u.get(e.noteId);t&&(d.push(t),f.add(t.id))}return{date:n,url:`${(t.baseUrl??``).replace(/\/+$/,``)}/day/${n}`,pageId:s?.id??null,plannedCount:r.planned.length,planned:r.planned.map(({item:e,note:t,pairedSessions:n})=>({scheduleItemId:e.id,noteId:e.noteId,noteTitle:t?.title??e.noteId,status:n.length>0?`completed`:e.status,...e.slot?{slot:e.slot}:{},...e.notes?{notes:e.notes}:{},pairedSessionIds:n.map(e=>e.id)})),adhocSessionCount:r.adhocSessions.length,adhocSessions:r.adhocSessions.map(({session:e,note:t})=>({id:e.id,noteId:e.noteId,noteTitle:t?.title??e.noteId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,...e.noteSourceRevision?{noteSourceRevision:e.noteSourceRevision}:{}})),noteCount:d.length,notes:d.map(e=>({id:e.id,title:e.title,sourceRevision:e.sourceRevision,rawContent:e.rawContent,tags:e.tags??[],wodBlockIds:Object.values(e.blocks??{}).filter(e=>e.kind===`wod`).map(e=>e.id),url:V9(e,t.baseUrl)})),sessionCount:m.length,sessions:m.map(e=>({id:e.id,noteId:e.noteId,blockId:e.blockId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,...e.scheduleItemId?{scheduleItemId:e.scheduleItemId}:{},...e.sessionDate?{sessionDate:e.sessionDate}:{},...e.noteSourceRevision?{noteSourceRevision:e.noteSourceRevision}:{}}))}}}),P9({name:`wod_journal_add`,title:`Add Workout to Journal Day`,description:"Create a lightweight workout Note (unfiled unless `notebookId` is given) and schedule it onto the specified calendar day via a `ScheduleItem`.",tier:1,domain:`journal`,annotations:{title:`Add Workout to Journal Day`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({date:G().optional().describe(`Target Journal date in YYYY-MM-DD format or "today" (defaults to "today").`),title:G().optional().describe(`Workout title (defaults to # H1 heading or date).`),content:G().min(1).describe(`Markdown workout note or bare Whiteboard Script to schedule onto the Journal day.`),sport:G().optional().describe(`Optional sport fence tag when passing bare Whiteboard Script.`),notebookId:G().optional().describe(`Optional user Notebook ID to assign this Note into (omit to keep unfiled on Journal).`)}),cliEquivalent:`wod journal add <file|-> --date YYYY-MM-DD --json`,async execute(e,t){let n=R9(e.date),r=e.title??`Workout ${n}`,i=L9(e.content,e.sport,e.title),a=await B9(t.storage,{title:r,rawContent:i,journalDate:n,notebookId:e.notebookId,type:`journal`});await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`notebook_links`,`schedule_items`]);let o=(t.baseUrl??``).replace(/\/+$/,``);return{date:n,noteId:a.note.id,...a.scheduleItemId?{scheduleItemId:a.scheduleItemId}:{},journalUrl:`${o}/day/${n}`,note:{id:a.note.id,title:a.note.title,sourceRevision:a.note.sourceRevision,blockCount:a.blockCount,effortSlugs:a.effortSlugs,url:V9(a.note,t.baseUrl)}}}})],H9=new Set(ks.map(e=>e.slug)),nTe=[P9({name:`wod_notebook_list`,title:`List Notebooks`,description:`List built-in, user-created, and feed-subscribed Notebooks along with member Note counts and publication status.`,tier:0,domain:`notebook`,annotations:{title:`List Notebooks`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({origin:Qt([`all`,`default`,`user`,`feed`]).optional().describe(`Filter notebooks by origin (default "all").`)}),cliEquivalent:`wod notebook list --json`,async execute(e,t){let[n,r]=await Promise.all([t.storage.readonly(`notes`).getAll(),t.storage.readonly(`notebook_links`).getAll().catch(()=>[])]),i=Ms(n,r,Hy),a=new Map;for(let e of ks)a.set(e.notebookId,{notebookId:e.notebookId,slug:e.slug,name:e.name,description:e.description,icon:e.icon,origin:`default`,writable:!bs(e.notebookId),public:!1,noteCount:i.get(e.notebookId)??0});for(let e of n){if(!As(e))continue;let t=Ss(e.id),n=qb(e.rawContent),r=typeof n.description==`string`?n.description.replace(/^"|"$/g,``):``,o=typeof n.icon==`string`?n.icon.replace(/^"|"$/g,``):`📓`,s=e.feedOrigin===`feed`||e.seedOrigin===`seed`,c=a.get(e.id);a.set(e.id,{notebookId:e.id,slug:t,name:e.title||c?.name||t,description:r||c?.description||``,icon:o||c?.icon||`📓`,origin:c?.origin??(s?`feed`:`user`),writable:!bs(e.id)&&!s,public:e.public===!0,noteCount:i.get(Cs(e.id))??0})}let o=e.origin??`all`,s=(t.baseUrl??``).replace(/\/+$/,``),c=[...a.values()].filter(e=>o===`all`||e.origin===o).map(e=>({id:e.notebookId,...e,url:`${s}/notebook/${encodeURIComponent(e.slug)}`}));return{totalCount:c.length,notebooks:c}}}),P9({name:`wod_notebook_save`,title:`Create, Update, or Promote Notebook`,description:"Create or update a user-owned Notebook, promote/detach a Note across Notebooks (`notebook/journal` permanence preserved), or toggle Notebook publication visibility.",tier:1,domain:`notebook`,annotations:{title:`Save or Promote Notebook`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({action:Qt([`create`,`update`,`promote`,`detach`,`set-public`]).describe(`Operation to perform on a user Notebook.`),notebookId:G().optional().describe(`Target Notebook slug or ID (required for update, promote, detach, set-public).`),name:G().optional().describe(`Display name when creating or renaming a Notebook.`),description:G().optional().describe(`Notebook description.`),icon:G().optional().describe(`Notebook icon/emoji.`),noteId:G().optional().describe(`Note ID to promote into or detach from the Notebook.`),sessionIds:me(G()).optional().describe("Optional Session IDs on `noteId` to promote alongside the Note."),public:Gt().optional().describe(`Visibility flag when action="set-public" or promoting sessions.`)}),cliEquivalent:`wod notebook <create|update|promote> --json`,async execute(e,t){if(e.action===`create`){let n=e.name?.trim()||e.notebookId?.trim();if(!n)throw Error('`name` is required when action="create".');let r=await VS(t.storage,n);if(e.description!==void 0||e.icon!==void 0){let i=`---\ndescription: ${JSON.stringify(e.description??``)}\nicon: ${JSON.stringify(e.icon??`📓`)}\n---\n\n# ${n}\n`,a=await B9(t.storage,{noteId:r,title:n,rawContent:i});await t.storage.readwrite(`notes`).put({...a.note,notebookId:r})}return e.public!==void 0&&await JS(t.storage,r,e.public),await t.onMutated?.([`notes`,`block_revisions`,`notebook_links`]),{action:`create`,notebookId:r,slug:Ss(r),name:n}}if(!e.notebookId)throw Error(`'notebookId' is required for action="${e.action}".`);let n=Cs(e.notebookId),r=Ss(n);if(e.action===`update`){if(H9.has(r))throw Error(`Built-in Notebook '${n}' cannot be modified.`);let i=await t.storage.readonly(`notes`).get(n);if(!i)throw Error(`Notebook not found: ${n}`);let a=qb(i.rawContent),o=e.name??i.title??r,s=e.description??(typeof a.description==`string`?a.description.replace(/^"|"$/g,``):``),c=e.icon??(typeof a.icon==`string`?a.icon.replace(/^"|"$/g,``):`📓`),l=`---\ndescription: ${JSON.stringify(s)}\nicon: ${JSON.stringify(c)}\n---\n\n# ${o}\n`,u=await B9(t.storage,{noteId:n,title:o,rawContent:l});return await t.storage.readwrite(`notes`).put({...u.note,notebookId:n,...i.public===void 0?{}:{public:i.public}}),await t.onMutated?.([`notes`,`block_revisions`]),{action:`update`,notebookId:n,slug:r,name:o}}if(e.action===`promote`){if(!e.noteId)throw Error('`noteId` is required when action="promote".');let r=await HS(t.storage,{noteId:e.noteId,notebookIds:[n],sessionIds:e.sessionIds,shareSessionsPublicly:e.public});return await t.onMutated?.([`notes`,`sessions`,`notebook_links`]),{action:`promote`,noteId:e.noteId,notebookIds:r.notebookIds,promotedSessionIds:r.promotedSessionIds}}if(e.action===`detach`){if(!e.noteId)throw Error('`noteId` is required when action="detach".');let r=await WS(t.storage,e.noteId,n);return await t.onMutated?.([`notes`,`notebook_links`]),{action:`detach`,noteId:e.noteId,notebookIds:r}}if(xs(n))throw Error(`Notebook '${n}' is private/system and cannot be published.`);let i=await JS(t.storage,n,e.public??!0);return await t.onMutated?.([`notes`]),{action:`set-public`,notebookId:n,public:i.public===!0}}}),P9({name:`wod_notebook_delete`,title:`Delete User Notebook`,description:"Delete a user-created Notebook landing note and detach member links while keeping all member Notes safely in `notebook/journal` (Tier 2 destructive).",tier:2,domain:`notebook`,annotations:{title:`Delete User Notebook`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({notebookId:G().min(1).describe(`User Notebook ID or slug to delete (member Notes stay safe in notebook/journal).`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact notebookId or slug to confirm deletion.`)}),cliEquivalent:`wod notebook delete <slug> --yes <slug> --json`,async execute(e,t){let n=Cs(e.notebookId),r=Ss(n);if(H9.has(r))throw Error(`Built-in Notebook '${n}' cannot be deleted.`);let i=e.confirmId===n||e.confirmId===r?n:void 0;await F9(t,{action:`wod_notebook_delete`,targetId:n,summary:`Delete user Notebook "${r}" (${n}); member Notes remain in notebook/journal`},i);let a=await yC(t.storage,n);return await t.onMutated?.([`notes`,`notebook_links`]),a}})];function rTe(e){return e.id.startsWith(`notebook/`)&&e.notebookId===e.id}var iTe=[P9({name:`wod_note_list`,title:`List Notes`,description:`List workout and reference Notes with optional filtering by Notebook, search query, tag, and origin.`,tier:0,domain:`note`,annotations:{title:`List Notes`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({notebookId:G().optional().describe(`Filter by notebook ID or slug (e.g. "journal", "custom", "guides", "notebook/strength").`),search:G().optional().describe(`Case-insensitive substring filter over title and Markdown content.`),tag:G().optional().describe(`Filter to Notes carrying this tag label.`),origin:Qt([`all`,`user`,`feed`,`seed`]).optional().describe(`Filter by Note origin ("user", "feed", "seed", or "all"; defaults to "all").`),includeSeed:Gt().optional().describe(`Include read-only Seed/Feed notes (default true; pass false for user-authored notes only).`),orphanedOnly:Gt().optional().describe("When true, return only user Notes not belonging to any Notebook (equivalent to `:note{!notebook:*}`)."),limit:se().int().min(1).max(200).optional().describe(`Max notes to return (default 50).`)}),cliEquivalent:`wod note list --json`,async execute(e,t){let n=e.notebookId?Cs(e.notebookId):void 0,r=e.includeSeed??!0,i=e.origin??`all`,a=e.orphanedOnly===!0,o=e.search?.trim().toLowerCase(),s=e.tag?.trim().toLowerCase(),c=e.limit??50,{allNotes:l,linkedNoteIdsForNb:u,noteIdsWithLinks:d}=await t.storage.transaction([`notes`,`notebook_links`],`readonly`,async e=>{let t=await e.readonly(`notes`).getAll(),r,i=new Set;try{if(n){let t=await e.readonly(`notebook_links`).getAllFromIndex(`by-notebook`,n);r=new Set(t.filter(e=>e.targetKind===`note`).map(e=>e.noteId))}if(a){let t=await e.readonly(`notebook_links`).getAll();for(let e of t)e.targetKind===`note`&&i.add(e.noteId)}}catch{r=new Set}return{allNotes:t,linkedNoteIdsForNb:r,noteIdsWithLinks:i}}),f=l.filter(e=>{if(rTe(e))return!1;let t=e.seedOrigin===`seed`||e.feedOrigin===`feed`;return!(i===`user`&&t||i===`feed`&&e.feedOrigin!==`feed`||i===`seed`&&e.seedOrigin!==`seed`||!r&&t||a&&(t||d.has(e.id)||Hy(e).length>0)||n&&!(u?.has(e.id)||e.notebookId===n||(e.notebookIds??[]).includes(n)||Hy(e).includes(n))||s&&!(e.tags??[]).some(e=>e.toLowerCase()===s)||o&&!e.title.toLowerCase().includes(o)&&!e.rawContent.toLowerCase().includes(o))}).sort((e,t)=>(t.date??t.createdAt)-(e.date??e.createdAt));return{totalCount:f.length,notes:f.slice(0,c).map(e=>{let n=Wy(e),r=Uy(e);return{id:e.id,title:e.title,sourceRevision:e.sourceRevision,date:e.date,createdAt:e.createdAt,editable:Os(e,n,r),notebooks:Hy(e),tags:e.tags??[],wodBlockCount:Object.values(e.blocks??{}).filter(e=>e.kind===`wod`).length,url:V9(e,t.baseUrl)}})}}}),P9({name:`wod_note_get`,title:`Get Note Details`,description:"Read a full Note by ID including authored Markdown, `sourceRevision`, parsed workout blocks, attached Session count, upstream provenance, and publication visibility.",tier:0,domain:`note`,annotations:{title:`Get Note Details`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`Unique Note ID (UUID or seed route ID).`)}),cliEquivalent:`wod note get <noteId> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.noteId);if(!n)throw Error(`Note not found: ${e.noteId}`);let r=Os(n,Wy(n),Uy(n)),[i,a,o,s,c,l]=await Promise.all([GS(t.storage,n.id),LC(t.storage,n),qS(t.storage,n.id),t.storage.readonly(`sessions`).getAllFromIndex(`by-note`,n.id).catch(async()=>(await t.storage.readonly(`sessions`).getAll()).filter(e=>e.noteId===n.id)),ew(t.storage,n.id).catch(()=>[]),JC(t.storage,n.id).catch(()=>[])]),u=zs(n.rawContent,{registeredWidgets:Ns}),d=Object.values(n.blocks??{}).sort((e,t)=>e.from-t.from).map(e=>{let t=u.find(t=>t.from===e.from&&t.to===e.to);return{id:e.id,kind:e.kind,version:e.version,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{},content:t?.scriptBlock?.content??n.rawContent.slice(e.from,e.to)}});return{id:n.id,title:n.title,rawContent:n.rawContent,portableMarkdown:Gb(n),sourceRevision:n.sourceRevision,editable:r,date:n.date,createdAt:n.createdAt,tags:n.tags??[],notebooks:i.map(e=>({id:e,slug:Ss(e)})),scheduleCount:c.length,scheduleItems:c,revisionCount:l.length,blocks:d,sessionCount:s.length,recentSessions:s.sort((e,t)=>t.startTime-e.startTime).slice(0,10).map(e=>({id:e.id,blockId:e.blockId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,public:e.public===!0})),...a?{provenance:a}:{},visibility:o,url:V9(n,t.baseUrl)}}}),P9({name:`wod_note_upsert`,title:`Create or Update Note`,description:"Create a new workout/reference Note or update an existing editable Note with full block-revision pinning, effort/equipment indexing, and optimistic concurrency (`expectedSourceRevision`).",tier:1,domain:`note`,annotations:{title:`Create or Update Note`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Existing Note ID to update, or omit to create a new Note.`),title:G().optional().describe(`Note title (defaults to # H1 heading in content).`),content:G().min(1).describe(`Full Markdown document or Whiteboard Script body.`),sport:G().optional().describe(`Optional sport fence tag when passing bare Whiteboard Script.`),expectedSourceRevision:se().int().min(0).optional().describe(`Optimistic concurrency guard: pass the current sourceRevision from wod_note_get when updating.`),notebookId:G().optional().describe(`Optional user Notebook ID/slug to assign this Note into (omit for unfiled/existing memberships).`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" to place the Note on that Journal calendar day.`)}),cliEquivalent:`wod note save <file|-> --json`,async execute(e,t){let n=L9(e.content,e.sport,e.title),r=await B9(t.storage,{noteId:e.noteId,title:e.title,rawContent:n,expectedSourceRevision:e.expectedSourceRevision,notebookId:e.notebookId,journalDate:e.journalDate});return await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`tags`,`note_tags`,`page`,`page_notes`,`notebook_links`]),{id:r.note.id,noteId:r.note.id,title:r.note.title,created:r.created,sourceRevision:r.note.sourceRevision,blockCount:r.blockCount,effortSlugs:r.effortSlugs,equipmentSlugs:r.equipmentSlugs,tags:r.tagLabels,url:V9(r.note,t.baseUrl)}}}),P9({name:`wod_note_clone`,title:`Clone Note with Provenance`,description:"Clone any Note (especially read-only Seed or Feed workouts) into a writable user Notebook or Journal day while recording structured upstream `NoteProvenance`.",tier:1,domain:`note`,annotations:{title:`Clone Note`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({sourceNoteId:G().min(1).describe(`Source Note ID (including read-only Seed/Feed Notes) to clone.`),targetNotebookId:G().optional().describe(`Target writable user Notebook ID/slug (defaults to "notebook/journal").`),title:G().optional().describe(`Optional title override for the cloned Note.`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" to pin the clone onto a Journal day.`)}),cliEquivalent:`wod note clone <sourceNoteId> --notebook <slug> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.sourceNoteId);if(!n)throw Error(`Source Note not found: ${e.sourceNoteId}`);let r=Cs(e.targetNotebookId??`notebook/journal`);if(bs(r))throw Error(`Target Notebook '${r}' is read-only.`);let i=Date.now(),a=I9(),o=Hy(n)[0],s=RC(n,o,i),c={...(await B9(t.storage,{noteId:a,title:e.title??n.title,rawContent:n.rawContent,notebookId:r,journalDate:e.journalDate,tags:(n.tags??[]).map(e=>({label:e})),now:i})).note,sourceId:n.id,provenance:s};return await t.storage.readwrite(`notes`).put(c),r!==`notebook/journal`&&await HS(t.storage,{noteId:a,notebookIds:[r]}),await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`notebook_links`,`page`,`page_notes`]),{id:c.id,noteId:c.id,title:c.title,sourceRevision:c.sourceRevision,targetNotebookId:r,provenance:s,url:V9(c,t.baseUrl)}}}),P9({name:`wod_note_delete`,title:`Delete Note`,description:`Permanently delete a Note and detach its projections, tag links, and calendar placements (Tier 2 destructive — requires user confirmation or matching confirmId).`,tier:2,domain:`note`,annotations:{title:`Delete Note`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`ID of the Note to delete.`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact noteId to confirm deletion.`)}),cliEquivalent:`wod note delete <noteId> --yes <noteId> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.noteId);if(!n)return{deleted:!1,noteId:e.noteId,reason:`not_found`};await F9(t,{action:`wod_note_delete`,targetId:e.noteId,summary:`Delete Note "${n.title||e.noteId}" (${e.noteId})`},e.confirmId);let r=await Jwe(t.storage,e.noteId);return r&&await t.onMutated?.([`notes`,`block_index`,`block_efforts`,`block_equipment`,`note_tags`,`page_notes`,`notebook_links`,`meta`]),{deleted:r,noteId:e.noteId,title:n.title}}})],aTe=[P9({name:`wod_schedule_list`,title:`List Scheduled Workouts`,description:"List M:N ScheduleItem instances by date range (`from`/`to`) or for a specific Note ID.",tier:0,domain:`journal`,annotations:{title:`List Scheduled Workouts`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({from:G().optional().describe(`Start date in YYYY-MM-DD format (inclusive, or "today").`),to:G().optional().describe(`End date in YYYY-MM-DD format (inclusive, or "today").`),noteId:G().optional().describe(`Optional Note ID to list scheduled dates for one workout.`)}),cliEquivalent:`wod schedule list --json`,async execute(e,t){let n;if(e.noteId){if(n=await ew(t.storage,e.noteId),e.from){let t=R9(e.from);n=n.filter(e=>e.date>=t)}if(e.to){let t=R9(e.to);n=n.filter(e=>e.date<=t)}}else if(e.from||e.to){let r=R9(e.from??e.to),i=R9(e.to??e.from);n=await $C(t.storage,r,i)}else n=(await t.storage.readonly(`schedule_items`).getAll()).sort((e,t)=>e.date.localeCompare(t.date)||(e.position??0)-(t.position??0));let r=[...new Set(n.map(e=>e.noteId))],i=await t.storage.readonly(`notes`).getMany(r),a=new Map;return i.forEach((e,t)=>{e&&a.set(r[t],e.title)}),{totalCount:n.length,items:n.map(e=>({...e,noteTitle:a.get(e.noteId)??e.noteId}))}}}),P9({name:`wod_schedule_add`,title:`Schedule Workout onto Day`,description:`Link an existing Note onto a Journal calendar date via a ScheduleItem (M:N link-first scheduling without cloning user Notes or forcing notebook/journal).`,tier:1,domain:`journal`,annotations:{title:`Schedule Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`Canonical Note ID to schedule onto a calendar day.`),date:G().optional().describe(`Calendar date YYYY-MM-DD or "today" (defaults to "today").`),slot:G().optional().describe(`Optional slot badge such as "AM", "PM", or "Warmup".`),position:se().int().optional().describe(`Optional ordering index within the day.`),notes:G().optional().describe(`Optional scaling or session intent notes for this scheduled instance.`)}),cliEquivalent:`wod schedule add <noteId> --date YYYY-MM-DD --json`,async execute(e,t){let n=R9(e.date),r=await YC(t.storage,{noteId:e.noteId,date:n,...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}});return await t.onMutated?.([`schedule_items`,`notes`]),{item:r}}}),P9({name:`wod_schedule_batch`,title:`Batch Schedule Workouts`,description:`Schedule one or more existing Notes across target calendar dates atomically via ScheduleItem links.`,tier:1,domain:`journal`,annotations:{title:`Batch Schedule Workouts`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({items:me(yi({noteId:G().min(1),date:G().describe(`Calendar date YYYY-MM-DD or "today".`),slot:G().optional(),position:se().int().optional(),notes:G().optional()})).min(1).describe(`List of Note + date pairs to schedule atomically.`)}),cliEquivalent:`wod schedule batch --json`,async execute(e,t){let n=await XC(t.storage,e.items.map(e=>({noteId:e.noteId,date:R9(e.date),...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}})));return await t.onMutated?.([`schedule_items`,`notes`]),{scheduledCount:n.length,items:n}}}),P9({name:`wod_schedule_update`,title:`Update Scheduled Workout`,description:"Reschedule, reorder, or update status (`planned`, `completed`, `moved`, `skipped`) on a ScheduleItem.",tier:1,domain:`journal`,annotations:{title:`Update Scheduled Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({scheduleItemId:G().min(1).describe(`ScheduleItem ID to update.`),date:G().optional().describe(`New calendar date YYYY-MM-DD or "today".`),status:Qt([`planned`,`completed`,`moved`,`skipped`]).optional().describe(`Updated schedule status.`),slot:G().optional().describe(`Updated slot label.`),position:se().int().optional().describe(`Updated intra-day ordering index.`),notes:G().optional().describe(`Updated intent or scaling notes.`)}),cliEquivalent:`wod schedule update <scheduleItemId> --json`,async execute(e,t){let n=await ZC(t.storage,e.scheduleItemId,{...e.date===void 0?{}:{date:R9(e.date)},...e.status===void 0?{}:{status:e.status},...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}});return await t.onMutated?.([`schedule_items`]),{item:n}}}),P9({name:`wod_schedule_remove`,title:`Unschedule Workout Instance`,description:`Remove a single ScheduleItem from a calendar day while leaving the canonical Note and recorded Sessions intact.`,tier:1,domain:`journal`,annotations:{title:`Unschedule Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({scheduleItemId:G().min(1).describe(`ScheduleItem ID to remove from the calendar.`)}),cliEquivalent:`wod schedule remove <scheduleItemId> --json`,async execute(e,t){return await QC(t.storage,e.scheduleItemId),await t.onMutated?.([`schedule_items`]),{removed:!0,scheduleItemId:e.scheduleItemId}}})];function U9(e,t=[]){for(let n of e.metrics??[])(n.value===`?`||n.origin===`collectible`)&&t.push({...e.id===void 0?{}:{id:e.id},text:e.raw??``,metricType:n.type});for(let n of e.children??[])U9(n,t);return t}var oTe=[P9({name:`wod_parse_script`,title:`Parse Whiteboard Script`,description:"Validate Whiteboard Script syntax, inspect parsed statements, typed metrics, unresolved choices, and collectible `?` placeholders. Defaults to dry-run (`save: false`); pass `save: true` to persist as a Note.",tier:0,domain:`script`,annotations:{title:`Parse Whiteboard Script`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({source:G().min(1).describe("Whiteboard Script body OR full Markdown document containing ```time / ```wod blocks."),sport:G().optional().describe(`Optional sport fence dialect override (e.g. "crossfit", "climbing", "running").`),save:Gt().optional().describe(`Default false (dry-run syntax & metric inspection). Set true to persist as a Note.`),noteId:G().optional().describe(`Optional target Note ID when save=true.`),title:G().optional().describe(`Optional Note title when save=true.`),notebookId:G().optional().describe(`Optional user Notebook slug/ID when save=true.`)}),cliEquivalent:`wod parse - --no-save --json`,async execute(e,t){let n=await dS(t.storage,{...e.notebookId?{notebookId:e.notebookId}:{}}).catch(()=>void 0),r=zs(e.source,{registeredWidgets:Ns}).filter(e=>e.scriptBlock),i=nu({...n?{references:n.referenceIndex,tags:n.tagIndex}:{}}),a=(r.length>0?r.map((t,n)=>({index:n,sport:e.sport??t.scriptBlock?.sport,dialect:t.scriptBlock?.dialect??`time`,body:t.scriptBlock.content})):[{index:0,sport:e.sport,dialect:`time`,body:e.source}]).map(e=>{let t=i.read(e.body,e.sport),n=wae(t),r=Rm(t.statements).map(e=>({statementIndex:e.statementIndex,statementId:e.statementId,choice:e.choice})),a=U9(n);return{index:e.index,dialect:e.dialect,...e.sport?{sport:e.sport}:{},valid:(t.errors?.length??0)===0,errors:t.errors??[],statementCount:t.statements.length,tree:n,unresolvedChoices:r,collectibles:a}}),o=a.every(e=>e.valid),s;if(e.save&&o){let n=L9(e.source,e.sport,e.title),r=await B9(t.storage,{noteId:e.noteId,title:e.title,rawContent:n,notebookId:e.notebookId});await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`]),s={noteId:r.note.id,title:r.note.title,sourceRevision:r.note.sourceRevision,created:r.created}}return{valid:o,blockCount:a.length,blocks:a,...s?{savedNote:s}:{}}}})];function sTe(e,t){if(!t||Object.keys(t).length===0)return e;let n=Object.entries(t),r=e;for(let[e,t]of n){let n=String(t);if(e===`?`||e==="default")r=r.replace(/\?/g,n);else{let t=RegExp(`\\?\\s*${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}\\b`,`gi`);r=t.test(r)?r.replace(t,`${n} ${e}`):r.replace(/\?/,n)}}return r}var cTe=P9({name:`wod_session_run_headless`,title:`Run Workout Session Headlessly`,description:"Execute a workout block through the headless JIT compiler and runtime state machine, recording a pinned `Session` and derived `EventRecord`s in storage. Automatically clones read-only Seed/Feed Notes into `notebook/journal`.",tier:1,domain:`session`,annotations:{title:`Run Workout Headlessly`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Existing Note ID to execute (read-only Seed/Feed Notes pin one immutable copy on first run).`),blockId:G().optional().describe("Optional workout block ID on `noteId` (defaults to first wod block)."),source:G().optional().describe("Inline Whiteboard Script or Markdown to persist & run when `noteId` is not supplied."),title:G().optional().describe("Optional Note title when running inline `source`."),sport:G().optional().describe(`Optional sport dialect override.`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" attributed Session calendar date.`),scheduleItemId:G().optional().describe(`Optional ScheduleItem ID that triggered this workout run.`),collectibles:Ne(G(),yn([G(),se()])).optional().describe('Optional values for collectible `?` metrics (e.g. `{ "lb": 185, "reps": 12 }`).'),stepAdvanceMs:se().int().min(100).max(36e5).optional().describe(`Simulated clock advance per step in milliseconds (default 10000).`),maxSteps:se().int().min(1).max(5e3).optional().describe(`Safety cap on execution steps (default 500).`),public:Gt().optional().describe(`Mark the recorded Session public for Feed publication.`)}),cliEquivalent:`wod run <file|--note id> --json`,async execute(e,t){let n=e.noteId;if(!n){if(!e.source?.trim())throw Error("Provide either `noteId` or inline `source` to execute a workout session.");let r=L9(e.source,e.sport,e.title);n=(await B9(t.storage,{title:e.title,rawContent:r,journalDate:e.journalDate,type:`journal`})).note.id}let r=Date.now(),i=await FC(t.storage,{noteId:n,blockId:e.blockId,journalDate:e.journalDate,...e.scheduleItemId?{scheduleItemId:e.scheduleItemId}:{},startedAt:r}),a=sTe(zs(i.revision.rawContent,{registeredWidgets:Ns}).find(e=>e.scriptBlock)?.scriptBlock?.content??i.revision.rawContent,e.collectibles),o=await dS(t.storage,{note:i.note}).catch(()=>void 0),s=e.sport??i.revision.sport,c=nu({...o?{references:o.referenceIndex,tags:o.tagIndex}:{}}).read(a,s);if(c.errors&&c.errors.length>0)throw Error(`Whiteboard Script syntax error: ${c.errors.map(e=>e.message).join(`; `)}`);let l=Dne(new Date(r)),u=new Df,d=new em,f=Tne(new Date(r)),p=new vf(c,rh(),{stack:u,clock:l,eventBus:d},{},f),{engine:m,analyticsContext:h}=Im({id:i.session.blockId,content:a,statements:c.statements,sport:s,version:i.session.blockVersion,startLine:0,endLine:0,dialect:i.revision.dialect??`time`,state:`idle`,createdAt:r});p.analyticsContext=h,p.setAnalyticsEngine(m);let g=[];p.subscribeToOutput(e=>{g.push(e)}),p.do(new nm),u.current?.key.toString().startsWith(`waiting-to-start`)&&p.handle(new th(void 0,{nowMs:()=>l.currentDate.getTime(),now:()=>l.currentDate}));let _=e.stepAdvanceMs??1e4,v=e.maxSteps??500,y=0;for(;u.count>0&&y<v;)l.advance(_),p.handle(new th(void 0,{nowMs:()=>l.currentDate.getTime(),now:()=>l.currentDate})),y+=1;let b=u.count===0,x=l.currentDate.getTime();p.dispose();let S=g.map(Fh),C={noteId:i.session.noteId,resultId:i.session.id,blockId:i.session.blockId,blockVersion:i.session.blockVersion,...i.session.blockContentId?{blockContentId:i.session.blockContentId}:{},...i.session.pageId?{pageId:i.session.pageId}:{},origin:i.session.origin,workoutTimestamp:x},w=jy(S,C),T=My(S,C),E=[...w,...T],D={...i.session,sessionDate:i.session.sessionDate??BC(r),status:b?`completed`:`in-progress`,endTime:x,duration:Math.max(0,x-r),completed:b,...e.public===void 0?{}:{public:e.public}};return await t.storage.transaction([`sessions`,`events`,`notebook_links`,`schedule_items`],`readwrite`,async e=>{await e.readwrite(`sessions`).put(D);let t=(D.notebookIds??[]).map(e=>({id:IS(Cs(e),`session`,D.id),notebookId:Cs(e),targetKind:`session`,targetId:D.id,noteId:D.noteId,createdAt:D.createdAt}));if(t.length>0&&await e.readwrite(`notebook_links`).putMany(t),D.scheduleItemId)try{let t=e.readwrite(`schedule_items`),n=await t.get(D.scheduleItemId);n&&n.status!==`completed`&&await t.put({...n,status:`completed`,updatedAt:x})}catch{}E.length>0&&await e.readwrite(`events`).putMany(E)}),e.public!==void 0&&await YS(t.storage,D.id,e.public),await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`sessions`,`events`,`page`,`page_notes`,`notebook_links`]),{sessionId:D.id,noteId:D.noteId,blockId:D.blockId,blockVersion:D.blockVersion,clonedFromReadOnly:i.clonedFromReadOnly,pinnedExternalWorkout:i.pinnedExternalWorkout,...i.upstreamNoteId?{upstreamNoteId:i.upstreamNoteId}:{},completed:b,stepsExecuted:y,durationMs:D.duration,eventCount:w.length,summaryCount:T.length}}}),lTe=P9({name:`wod_session_list`,title:`List Recorded Sessions`,description:`List recorded workout Sessions ordered newest-first, optionally filtered by Note ID.`,tier:0,domain:`session`,annotations:{title:`List Sessions`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Filter Sessions by owning Note ID.`),completedOnly:Gt().optional().describe(`Filter to completed Sessions only.`),limit:se().int().min(1).max(200).optional().describe(`Max Sessions to return (default 50).`)}),cliEquivalent:`wod session list --json`,async execute(e,t){let n=e.limit??50,r;if(e.noteId)try{r=await t.storage.readonly(`sessions`).getAllFromIndex(`by-note`,e.noteId)}catch{r=(await t.storage.readonly(`sessions`).getAll()).filter(t=>t.noteId===e.noteId)}else r=await t.storage.readonly(`sessions`).getAll();e.completedOnly&&(r=r.filter(e=>e.completed)),r.sort((e,t)=>t.startTime-e.startTime);let i=[...new Set(r.slice(0,n).map(e=>e.noteId))],a=await t.storage.readonly(`notes`).getMany(i),o=new Map;return a.forEach((e,t)=>{e&&o.set(i[t],e.title)}),{totalCount:r.length,sessions:r.slice(0,n).map(e=>({id:e.id,noteId:e.noteId,noteTitle:o.get(e.noteId)??e.noteId,blockId:e.blockId,blockVersion:e.blockVersion,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,endTime:e.endTime,public:e.public===!0}))}}}),uTe=P9({name:`wod_session_get`,title:`Get Session Telemetry`,description:"Read a recorded workout Session along with its pinned `BlockRevision` and derived event/summary telemetry rows.",tier:0,domain:`session`,annotations:{title:`Get Session Telemetry`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to inspect.`)}),cliEquivalent:`wod session get <sessionId> --json`,async execute(e,t){let n=await t.storage.readonly(`sessions`).get(e.sessionId);if(!n)throw Error(`Session not found: ${e.sessionId}`);let[r,i,a]=await Promise.all([t.storage.readonly(`notes`).get(n.noteId),t.storage.readonly(`block_revisions`).get([n.noteId,n.blockId,n.blockVersion]),t.storage.readonly(`events`).getAll()]),o=a.filter(e=>e.resultId===n.id).sort((e,t)=>e.timestamp-t.timestamp);return{session:n,noteTitle:r?.title,pinnedRevision:i??null,eventCount:o.filter(e=>e.grain===`event`).length,summaryCount:o.filter(e=>e.grain===`summary`).length,events:o}}}),dTe=P9({name:`wod_session_delete`,title:`Delete Recorded Session`,description:`Permanently delete a recorded workout Session and its telemetry events (Tier 2 destructive — requires confirmation).`,tier:2,domain:`session`,annotations:{title:`Delete Session`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to delete.`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact sessionId to confirm deletion.`)}),cliEquivalent:`wod session delete <sessionId> --yes <sessionId> --json`,async execute(e,t){let n=await t.storage.readonly(`sessions`).get(e.sessionId);if(!n)return{deleted:!1,sessionId:e.sessionId,reason:`not_found`};await F9(t,{action:`wod_session_delete`,targetId:e.sessionId,summary:`Delete workout Session ${e.sessionId} on Note ${n.noteId}`},e.confirmId);let r=await Ywe(t.storage,e.sessionId);return r&&await t.onMutated?.([`sessions`,`events`,`notebook_links`]),{deleted:r,sessionId:e.sessionId}}}),fTe=[cTe,lTe,uTe,P9({name:`wod_session_attribute`,title:`Attribute Session to Day or Plan`,description:`Associate a recorded workout Session with a specific Journal civil date and/or pair or unlink it with a planned ScheduleItem.`,tier:1,domain:`session`,annotations:{title:`Attribute Session`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to attribute to a calendar date or ScheduleItem.`),sessionDate:G().optional().describe(`Attributed Journal date (YYYY-MM-DD).`),scheduleItemId:G().nullable().optional().describe(`ScheduleItem ID to link this Session with, or null to unlink into an ad-hoc Session.`)}),cliEquivalent:`wod session attribute <sessionId> --json`,async execute(e,t){let n=await nw(t.storage,{sessionId:e.sessionId,...e.sessionDate===void 0?{}:{sessionDate:e.sessionDate},...e.scheduleItemId===void 0?{}:{scheduleItemId:e.scheduleItemId}});return await t.onMutated?.([`sessions`,`schedule_items`]),{session:n}}}),dTe],pTe=P9({name:`wod_validate_wql`,title:`Validate & Inspect WQL Query`,description:"Parse a WQL string without executing it. Returns syntax validity, query family (find, aggregate, pipeline), normalized WQL string, and the allowed filter keys and `by {}` grouping dimensions for that plane.",tier:0,domain:`wql`,annotations:{title:`Validate WQL Query`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({query:G().describe(`WQL query string to validate and inspect (e.g. ":note{notebook:journal} last 7d" or "sum:volume by {effort}").`),targetHint:G().optional().describe(`Optional target plane to list valid filter keys & grouping dimensions for (note, session, effort, equipment, tag, feed, block, event).`)}),cliEquivalent:`wod query "<wql>" --format json`,async execute(e){let t=Xg(e.query),n=!t.error,r=Lg(t)?`pipeline`:Fg(t)?`find`:`aggregate`,i=e.targetHint??(Fg(t)?t.target:Ig(t)?`event`:`note`),a=r===`find`?`find`:`aggregate`;return{valid:n,...t.error?{error:t.error}:{},family:r,target:i,normalized:n?Qg(e.query):e.query,allowedTargets:[...qh],allowedAggregators:[...Rh],allowedRollupPeriods:[...ig],validFilterKeys:[...vg(i,a)],validGroupingDimensions:[...yg(i,a)]}}}),mTe=[P9({name:`wod_query_wql`,title:`Execute WQL Query`,description:"Run any WQL find (`:note`, `:session`, `:effort`, `:equipment`, `:tag`, `:feed`, `:block`), aggregate (`sum:volume`, `max:weight`, `count:sessions`), or pipeline query against the active WOD Wiki storage.",tier:0,domain:`wql`,annotations:{title:`Execute WQL Query`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({query:G().min(1).describe(`WQL query expression (e.g. ":note{notebook:journal}", ":session last 30d", "sum:volume by {week}").`),preferredUnit:G().optional().describe(`Optional display unit conversion preference (e.g. "lb", "kg", "m", "mi").`),limit:se().int().min(1).max(500).optional().describe(`Maximum rows/items to return in the response payload (default 100).`)}),cliEquivalent:`wod query '<wql>' --format json`,async execute(e,t){let n=Xg(e.query);if(n.error)throw Error(`WQL Syntax Error in "${e.query}": ${n.error}. Call wod_validate_wql to inspect valid targets and filter keys.`);let r=qwe(t.storage),i=e.limit??100;if(Lg(n)){let t=await r.runPipeline(e.query,{preferredUnit:e.preferredUnit});return{kind:`pipeline-result`,query:e.query,result:t}}if(Fg(n)){let t=await r.runFind(n);return Array.isArray(t.runs)?{kind:`rows-result`,target:n.target,query:e.query,totalRuns:t.runs.length,totalCount:t.runs.length,runs:t.runs.slice(0,i),truncated:t.runs.length>i}:Array.isArray(t.efforts)?{kind:`find-result`,target:n.target,query:e.query,totalCount:t.efforts.length,items:t.efforts.slice(0,i),truncated:t.efforts.length>i}:t.table?{kind:`find-result`,target:n.target,query:e.query,columns:t.table.columns,totalCount:t.table.rows.length,items:t.table.rows.slice(0,i),truncated:t.table.rows.length>i}:n.target===`block`?{kind:`find-result`,target:n.target,query:e.query,totalCount:t.blocks.length,items:t.blocks.slice(0,i),truncated:t.blocks.length>i}:{kind:`find-result`,target:n.target,query:e.query,totalCount:t.notes.length,items:t.notes.slice(0,i),truncated:t.notes.length>i}}let a=await r.runQuery(e.query,{preferredUnit:e.preferredUnit});return{kind:`query-result`,query:e.query,result:a}}}),pTe],W9=[...oTe,...mTe,...iTe,...tTe,...aTe,...nTe,...fTe,...$we,...eTe];new Map(W9.map(e=>[e.name,e]));async function G9(){if(typeof window>`u`||typeof window.requestAnimationFrame!=`function`){await new Promise(e=>setTimeout(e,0));return}await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e())})})}async function K9(e=2e3){let t=Date.now()+e;for(await new Promise(e=>setTimeout(e,200));$X()&&Date.now()<t;)await new Promise(e=>setTimeout(e,25));await G9()}var hTe=yi({includeSampleEntries:Gt().optional().describe(`Include up to 50 unbatched stream entries when on a stream route (default true).`)}),gTe=yi({path:G().min(1).describe(`Internal app path (with optional ?query and #hash) to navigate to, e.g. "/journal", "/day/2026-11-11", "/note/<id>", "/notebooks", "/dashboards".`),replace:Gt().optional().describe(`Replace current history entry instead of pushing.`)}),_Te=yi({action:Qt([`status`,`disconnect`]).describe(`Inspect active Chromecast/receiver session status or disconnect an active session.`)}),vTe=yi({query:G().optional().describe(`WQL query string to apply to the mounted stream view (e.g. ":note{tags:benchmark}").`),layout:Qt([`cards`,`rows`,`feed`,`agenda`,`planner`]).optional().describe(`Switch stream layout mode and sync ?layout= in URL.`),groupBy:G().nullable().optional().describe(`Grouping dimension (e.g. "date", "week", "notebook") or null to clear.`),month:G().regex(/^\d{4}-\d{2}$/,`Expected YYYY-MM calendar month`).optional().describe(`Calendar month anchor in YYYY-MM format (syncs ?month= on calendar/journal views).`),overlayMode:Qt([`all`,`planned`,`logged`]).optional().describe("Calendar schedule/session overlay filter (`all`, `planned`, or `logged`)."),resetToDefault:Gt().optional().describe(`Undo custom stream filter and restore the route default WQL query.`)}),yTe=yi({operation:Qt([`read`,`replace`,`append`,`undo`]).describe(`Read live editor buffer, replace document content, append Markdown/workout block, or undo last edit.`),content:G().optional().describe(`Markdown or Whiteboard Script content for replace / append operations.`),save:Gt().optional().describe(`Flush and persist the draft to storage immediately after applying the edit (default false).`)}),bTe=yi({blockId:G().optional().describe("Optional workout block ID in the active Note editor (defaults to first ```time block)."),autoStart:Gt().optional().describe(`Automatically start the timer after mounting the workout clock (default true).`)}),xTe=yi({command:Qt([`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`,`status`]).describe(`Live workout clock command to dispatch (or "status" to read current ClockSnapshot).`),fieldId:G().optional().describe(`Target fieldId for entry-save, entry-skip, or choice-select.`),value:se().optional().describe(`Numeric value for entry-save or reps-set.`),occurrenceId:G().optional().describe(`Rep occurrenceId for reps-adjust, reps-set, or reps-select.`),delta:yn([on(1),on(-1)]).optional().describe(`+1 or -1 delta for reps-adjust.`),index:se().int().min(0).optional().describe(`Zero-based alternative index for choice-select.`)}),STe=yi({action:Qt([`get`,`set`]).describe(`Read current Playground UI preferences ("get") or update preferences ("set").`),theme:Qt([`light`,`dark`,`system`]).optional().describe("Color theme preference (`light`, `dark`, or `system`)."),audioEnabled:Gt().optional().describe(`Enable or mute workout timer audio cues.`),debugMode:Gt().optional().describe(`Enable or disable global runtime debug mode.`),analyticsUnit:Qt([`kg`,`lb`]).optional().describe("Preferred display unit for analytics charts (`kg` or `lb`)."),leftDrawerOpen:Gt().optional().describe(`Open or close the primary navigation drawer on mobile/tablet.`),rightDrawerOpen:Gt().optional().describe(`Open or close the secondary L3 context drawer on mobile/tablet.`)}),CTe=yi({query:G().optional().describe('WQL aggregate or find query string to set on the Metric Explorer (`/dashboards`), e.g. "sum:totalVolume{} by {week}".'),submit:Gt().optional().describe("Execute/submit the query immediately (default true when `query` is provided)."),weeks:yn([on(4),on(8),on(16)]).optional().describe("Analytics lookback range in weeks (`4`, `8`, or `16`)."),openSaveDialog:Gt().optional().describe(`Open the "Save to dashboard" dialog for the active query.`),openQuerySettings:Gt().optional().describe("Open the surface query settings dialog on `/dashboards`.")}),wTe=yi({action:Qt([`get_state`,`open_popover`,`close_popover`,`open_drawer`,`close_drawer`,`toggle_drawer`]).describe(`Inspect cursor line tokens & lint fixes, open/close the anchored Option A popover, or toggle the Option B right inspector drawer.`),mode:Qt([`token`,`add`,`block`,`wiki`,`prose-tag`,`query`,`markdown`]).optional().describe(`Optional inspector view mode when opening the popover or drawer.`),tokenIndex:se().int().min(0).optional().describe(`Zero-based index of the token on the current cursor line to target.`)}),TTe=yi({activeTab:Qt([`splits`,`movement`,`compare`,`raw`]).optional().describe(`Switch the active results workbook tab.`),mobileViewMode:Qt([`grid`,`cards`]).optional().describe("Switch the mobile results presentation mode (`grid` or `cards`)."),sourceDrawerOpen:Gt().optional().describe(`Open or close the Pinned Workout Source & History drawer.`),openAddToDashboard:Gt().optional().describe(`Open the 2-step Add to Dashboard promotion sheet for the session.`),closeModals:Gt().optional().describe(`Close any open source drawer or dashboard dialog on the results workbench.`)}),ETe=yi({action:Qt([`status`,`open`,`close`]).describe(`Read active Entity Peek Drawer state ("status"), open a preview for a target entity ("open"), or dismiss it ("close").`),kind:Qt([`effort`,`equipment`,`tag`,`unrecognized`,`note`,`notebook`,`day`]).optional().describe(`Target entity kind when action="open".`),slug:G().optional().describe(`Canonical slug when kind is "effort", "equipment", or "notebook".`),label:G().optional().describe(`Tag label (required when kind="tag") or optional display label for effort/equipment.`),tagType:G().optional().describe(`Optional tag category/type when kind="tag" (e.g. "domain", "format", "general").`),term:G().optional().describe(`Unrecognized term to quick-define when kind="unrecognized".`),noteId:G().optional().describe(`Target Note ID when kind="note".`),title:G().optional().describe(`Optional display title hint when kind is "note" or "notebook".`),date:G().regex(/^\d{4}-\d{2}-\d{2}$/,`Expected YYYY-MM-DD civil date`).optional().describe(`Civil date (YYYY-MM-DD) when kind="day".`)});function DTe(e){switch(e.kind){case`effort`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="effort".`);return{kind:`effort`,slug:e.slug.trim(),...e.label?.trim()?{label:e.label.trim()}:{}};case`equipment`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="equipment".`);return{kind:`equipment`,slug:e.slug.trim(),...e.label?.trim()?{label:e.label.trim()}:{}};case`tag`:if(!e.label?.trim())throw Error(`'label' is required when kind="tag".`);return{kind:`tag`,label:e.label.trim().replace(/^#/,``),...e.tagType?.trim()?{tagType:e.tagType.trim()}:{}};case`unrecognized`:if(!e.term?.trim())throw Error(`'term' is required when kind="unrecognized".`);return{kind:`unrecognized`,term:e.term.trim()};case`note`:if(!e.noteId?.trim())throw Error(`'noteId' is required when kind="note".`);return{kind:`note`,noteId:e.noteId.trim(),...e.title?.trim()?{title:e.title.trim()}:{}};case`notebook`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="notebook".`);return{kind:`notebook`,slug:e.slug.trim(),...e.title?.trim()?{title:e.title.trim()}:{}};case`day`:if(!e.date?.trim())throw Error(`'date' is required when kind="day".`);return{kind:`day`,date:e.date.trim()};default:throw Error(`'kind' is required when action="open".`)}}function OTe(){(0,K.useEffect)(()=>u7({name:`ui_peek_entity`,title:`Inspect, Open, or Close Entity Peek Drawer`,description:`Inspect, open, or close the 340px right-edge Entity Peek Drawer on the live UI.`,tier:1,scope:`editor-ui`}),[]),Or({name:`ui_peek_entity`,title:`Inspect, Open, or Close Entity Peek Drawer`,description:"Read active Entity Peek Drawer state (`status`), open a non-destructive 340px right-edge preview for an effort, equipment, tag, unrecognized term, note, notebook, or day (`open`), or dismiss the drawer (`close`). Mutually exclusive with the Whiteboard Token Inspector drawer.",inputSchema:ETe,annotations:{title:`Inspect or Control Entity Peek Drawer`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=qX(),r=vX();if(e.action===`status`){let r=n?.getTarget()??null,i={ok:!0,open:r!==null,target:r};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}if(e.action===`close`){n?n.closePeek():r?.closePeek&&r.closePeek(),await G9();let i=qX()?.getTarget()??null,a={ok:!0,open:i!==null,target:i};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),a}let i=DTe(e);if(n)try{n.openPeek(i)}catch(e){if(r?.peekEntity)r.peekEntity(i);else throw e}else if(r?.peekEntity)r.peekEntity(i);else throw Error(`No Entity Peek surface is currently mounted.`);await G9();let a=qX()?.getTarget()??i,o={ok:!0,open:a!==null,target:a};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}})}var kTe=()=>(OTe(),null),ATe=()=>((0,K.useEffect)(()=>{let e=u7({name:`ui_editor_draft`,title:`Read, Edit, or Undo Live Note Editor Buffer`,description:`Inspect or modify the live CodeMirror 6 Note buffer.`,tier:1,scope:`editor-ui`}),t=u7({name:`ui_start_live_workout`,title:`Start Live Interactive Workout Timer`,description:`Start the live interactive workout clock from the active Note editor.`,tier:1,scope:`editor-ui`}),n=u7({name:`ui_editor_inspector`,title:`Inspect or Control Whiteboard Token Inspector & Drawer`,description:`Inspect cursor-line tokens or control the Option A popover and Option B drawer.`,tier:1,scope:`editor-ui`});return()=>{e(),t(),n()}},[]),Or({name:`ui_editor_draft`,title:`Read, Edit, or Undo Live Note Editor Buffer`,description:"Inspect or modify the live CodeMirror 6 Note buffer (`read`, `replace`, `append`, `undo`) with full undo support and optional immediate save (`save: true`).",inputSchema:yTe,annotations:{title:`Edit Live Note Draft`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);if(e.operation===`read`){let e=n.getValue();return{operation:`read`,noteId:n.noteId??null,readonly:n.readonly,sourceRevision:n.sourceRevision??null,content:e,workoutBlockIds:n.getBlocks().map(e=>e.id)}}if(e.operation===`undo`){let e=n.undoEdit();return await G9(),{operation:`undo`,undone:e,content:n.getValue()}}if(!e.content)throw Error(`'content' is required when operation="${e.operation}".`);let r=n.getValue(),i=e.operation===`replace`?L9(e.content):`${r.trimEnd()}\n\n${L9(e.content)}`;await n.applyEdit(i,e.save===!0),await G9();let a=vX()??n,o={operation:e.operation,saved:e.save===!0,noteId:a.noteId??null,sourceRevision:a.sourceRevision??null,workoutBlockIds:a.getBlocks().map(e=>e.id),length:a.getValue().length};return d7({toolName:`ui_editor_draft`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify({operation:e.operation,save:e.save}).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_editor_draft`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify({operation:e.operation}).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),Or({name:`ui_start_live_workout`,title:`Start Live Interactive Workout Timer`,description:"Launch the live interactive workout clock on screen from a workout block in the active Note editor so the human athlete and agent can co-drive the session via `ui_clock_control`.",inputSchema:bTe,annotations:{title:`Start Live Workout Timer`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);let r=await n.startLiveWorkout(e.blockId,e.autoStart??!0);if(!r.started)throw Error(r.error??`Failed to start workout timer.`);let i=Date.now()+1500;for(;!$1()&&Date.now()<i;)await new Promise(e=>setTimeout(e,25));await G9();let a={started:!0,blockId:r.blockId??null,clock:$1()};return d7({toolName:`ui_start_live_workout`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),a}catch(n){throw d7({toolName:`ui_start_live_workout`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),Or({name:`ui_editor_inspector`,title:`Inspect or Control Whiteboard Token Inspector & Drawer`,description:"Read parsed cursor-line tokens and inline lint fixes, open or close the Option A anchored token inspector popover (`Alt+.`), or toggle the Option B right inspector drawer (`Ctrl+Alt+I` / `Cmd+Alt+I`).",inputSchema:wTe,annotations:{title:`Inspect or Control Token Inspector`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);if(e.action===`open_popover`)n.openTokenInspector?.({mode:e.mode,tokenIndex:e.tokenIndex});else if(e.action===`close_popover`)n.closeTokenInspector?.();else if(e.action===`open_drawer`)n.setInspectorDrawer?.(!0),(e.mode||e.tokenIndex!==void 0)&&n.openTokenInspector?.({mode:e.mode,tokenIndex:e.tokenIndex});else if(e.action===`close_drawer`)n.setInspectorDrawer?.(!1);else if(e.action===`toggle_drawer`){let e=n.getInspectorState?.()?.drawerOpen??!1;n.setInspectorDrawer?.(!e)}await G9();let r={ok:!0,inspector:n.getInspectorState?.()??null};return d7({toolName:`ui_editor_inspector`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),r}catch(n){throw d7({toolName:`ui_editor_inspector`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),jTe=()=>((0,K.useEffect)(()=>u7({name:`ui_set_explorer_query`,title:`Set or Run Analytics Explorer WQL Query`,description:`Update or run WQL queries, week windows, or dialogs on the Metric Explorer (/dashboards).`,tier:1,scope:`explorer-ui`}),[]),Or({name:`ui_set_explorer_query`,title:`Set or Run Analytics Explorer WQL Query`,description:"Set or execute an aggregate or find WQL query on the Metric Explorer (`/dashboards`), change the week window (`4`, `8`, `16`), or open the Save-to-Dashboard / Query Settings dialogs.",inputSchema:CTe,annotations:{title:`Set Analytics Explorer Query`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=AX();if(!n)throw Error(`Metric Explorer (/dashboards) is not currently mounted.`);e.weeks!==void 0&&n.setWeeks(e.weeks),e.query===void 0?e.submit===!0&&n.submit():(n.setDraft(e.query),e.submit!==!1&&n.submit(e.query)),e.openSaveDialog&&n.openSaveDialog(),e.openQuerySettings&&n.openQuerySettings(),await K9();let r=AX()??n,i={draft:r.draft,submitted:r.submitted,weeks:r.weeks,saveReady:r.saveReady,loading:r.loading};return d7({toolName:`ui_set_explorer_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}catch(n){throw d7({toolName:`ui_set_explorer_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),MTe=()=>((0,K.useEffect)(()=>u7({name:`ui_clock_control`,title:`Control Live Workout Clock`,description:`Dispatch live clock commands to the active workout timer.`,tier:1,scope:`clock-ui`}),[]),Or({name:`ui_clock_control`,title:`Control Live Workout Clock`,description:"Inspect or dispatch commands (`next`, `playback`, `ready-start`, `entry-save`, `entry-skip`, `reps-adjust`, `reps-set`, `choice-select`, `stop-request`, `stop-confirm`, `dismiss`) to the active on-screen workout clock.",inputSchema:xTe,annotations:{title:`Control Live Workout Clock`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e,t){let n=performance.now();try{let r=$1();if(!r)throw Error(`No live workout clock is currently mounted.`);if(e.command===`status`)return{accepted:!0,snapshot:r};if(e.command===`stop-confirm`){if(!await M9({action:`ui_clock_control:stop-confirm`,targetId:r.runId,summary:`Stop and end the active live workout timer early`},t))throw Error(`User declined early termination of the active workout timer.`);r.stopRequested||(t0(r.runId,{kind:`stop-request`}),await G9())}let i;switch(e.command){case`entry-save`:{let t=e.fieldId??r.entry?.fieldId;if(!t||typeof e.value!=`number`)throw Error("`entry-save` requires `value` (number) and an active or explicit `fieldId`.");i={kind:`entry-save`,fieldId:t,value:e.value};break}case`entry-skip`:{let t=e.fieldId??r.entry?.fieldId;if(!t)throw Error("`entry-skip` requires `fieldId`.");i={kind:`entry-skip`,fieldId:t};break}case`reps-adjust`:{let t=e.occurrenceId??r.selectedOccurrenceId??r.reps[0]?.occurrenceId;if(!t||e.delta!==1&&e.delta!==-1)throw Error("`reps-adjust` requires `occurrenceId` and `delta` (+1 or -1).");i={kind:`reps-adjust`,occurrenceId:t,delta:e.delta};break}case`reps-set`:{let t=e.occurrenceId??r.selectedOccurrenceId??r.reps[0]?.occurrenceId;if(!t||typeof e.value!=`number`)throw Error("`reps-set` requires `occurrenceId` and integer `value`.");i={kind:`reps-set`,occurrenceId:t,value:e.value};break}case`reps-select`:if(!e.occurrenceId)throw Error("`reps-select` requires `occurrenceId`.");i={kind:`reps-select`,occurrenceId:e.occurrenceId};break;case`choice-select`:{let t=e.fieldId??r.entry?.fieldId;if(!t||typeof e.index!=`number`)throw Error("`choice-select` requires `fieldId` and `index`.");i={kind:`choice-select`,fieldId:t,index:e.index};break}default:i={kind:e.command}}let a=t0(($1()??r).runId,i);await G9();let o={accepted:a,command:e.command,snapshot:$1()};return d7({toolName:`ui_clock_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(t){throw d7({toolName:`ui_clock_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:t instanceof Error?t.message:String(t)}),t}}}),null),q9=()=>((0,K.useEffect)(()=>u7({name:`ui_results_control`,title:`Control Session Results Workbench`,description:"Switch tabs, toggle mobile grid/cards layout, open/close Source & History drawer, or open the Add-to-Dashboard sheet on `/results/:sessionId`.",tier:1,scope:`results-ui`}),[]),Or({name:`ui_results_control`,title:`Control Session Results Workbench`,description:"Control the mounted `/results/:sessionId` workbench (`activeTab`: splits|movement|compare|raw, `mobileViewMode`: grid|cards, `sourceDrawerOpen`, `openAddToDashboard`, `closeModals`).",inputSchema:TTe,annotations:{title:`Control Session Results Workbench`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=IX();if(!n)throw Error(`No session results workbench is currently mounted.`);e.closeModals&&n.closeModals(),e.activeTab!==void 0&&n.setTab(e.activeTab),e.mobileViewMode!==void 0&&n.setMobileViewMode(e.mobileViewMode),e.sourceDrawerOpen!==void 0&&n.openSourceDrawer(e.sourceDrawerOpen),e.openAddToDashboard&&n.openAddToDashboard(),await G9();let r=IX()??n,i={resultId:r.resultId,activeTab:r.activeTab,mobileViewMode:r.mobileViewMode,sourceDrawerOpen:r.sourceDrawerOpen,addToDashboardOpen:r.addToDashboardOpen};return d7({toolName:`ui_results_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}catch(n){throw d7({toolName:`ui_results_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),NTe=()=>((0,K.useEffect)(()=>u7({name:`ui_set_stream_query`,title:`Set Live Stream WQL Query or Layout`,description:`Update live WQL query, layout, grouping, calendar month, or overlay filter on the mounted stream view.`,tier:1,scope:`stream-ui`}),[]),Or({name:`ui_set_stream_query`,title:`Set Live Stream WQL Query or Layout`,description:"Update the live WQL query, layout (`cards`, `rows`, `feed`, `agenda`, `planner`), grouping, calendar `month` (`YYYY-MM`), or calendar `overlayMode` (`all`, `planned`, `logged`) on the currently mounted stream view, or pass `resetToDefault: true` to restore the route default query.",inputSchema:vTe,annotations:{title:`Set Live Stream Query`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=wX();if(!n)throw Error(`No stream view is currently mounted.`);e.resetToDefault?n.setQuery(n.defaultQuery):e.query!==void 0&&n.setQuery(e.query),e.layout!==void 0&&n.setLayout(e.layout),e.groupBy!==void 0&&n.setGroupBy(e.groupBy===null?void 0:e.groupBy),e.month!==void 0&&n.setMonth?.(e.month),e.overlayMode!==void 0&&n.setOverlayMode?.(e.overlayMode),await K9();let r=wX()??n,i=document.getElementById(`agent-view-state`)?.textContent,a=i?JSON.parse(i):null,o={route:r.route,query:r.query,layout:r.layout,groupBy:r.groupBy??null,month:r.month??null,overlayMode:r.overlayMode??null,totalUnbatchedCount:a?.stream?.totalUnbatchedCount??null};return d7({toolName:`ui_set_stream_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_set_stream_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),PTe=pee({allow:(e,t)=>!e.confirm||M9({action:`ui.${e.action}`,targetId:String(e.ref),summary:e.confirm},t)}),J9=Symbol(`wodWrappedExecuteTool`);function Y9(e){return typeof e!=`object`||!e?!1:`name`in e&&typeof e.name==`string`&&`origin`in e&&typeof e.origin==`string`&&`window`in e&&typeof e.window==`object`}function FTe(e){return typeof e==`object`&&!!e&&`name`in e}function ITe(e){let t=e.arguments??e.input??e.params??e.args;if(typeof t==`string`)try{return JSON.parse(t)}catch{return{}}return t??{}}function X9(e,t){let n=t??{};if(e===`ui_navigate`&&typeof n.path!=`string`&&typeof n.href==`string`){let e=n.href.trim();if(/^https?:\/\//i.test(e))try{let t=new URL(e);e=`${t.pathname}${t.search}${t.hash}`||`/`}catch{}return{...n,path:e}}return n}async function Z9(e,t,n){if(typeof t==`string`){let n=(await e()).find(e=>Y9(e)&&e.name===t);if(n)return n}if(Y9(n))return n;throw Error(typeof t==`string`?`executeTool: no registered tool named "${t}"`:`executeTool: expected a registered tool descriptor or a { name, arguments } envelope`)}function Q9(e){if(typeof e!=`object`||!e)return;let t=e,n=t.executeTool;if(typeof n!=`function`)return;let r;if(n[J9])r=n;else{let e=async()=>typeof t.getTools==`function`?t.getTools():typeof t.listTools==`function`?t.listTools():[],i=async(...r)=>{let[i,a]=r;if(r.length>=2&&Y9(i))return n.call(t,i,X9(i.name,a),r[2]);if(typeof i==`string`){let o=await Z9(e,i,void 0);return n.call(t,o,X9(i,a??{}),r[2])}if(FTe(i)){let r=X9(i.name,ITe(i)),a=await Z9(e,i.name,i);return n.call(t,a,r)}return n.apply(t,r)};i[J9]=!0,Object.defineProperty(t,"executeTool",{configurable:!0,writable:!0,value:i}),r=i}if(typeof t.callTool!=`function`||!t.callTool[J9]){let e=async(...e)=>r.apply(t,e);e[J9]=!0,Object.defineProperty(t,"callTool",{configurable:!0,writable:!0,value:e})}}var LTe=({spec:e})=>((0,K.useEffect)(()=>u7({name:e.name,title:e.title,description:e.description,tier:e.tier,scope:`domain`}),[e]),Or({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,annotations:e.annotations,async execute(t,n){let r=performance.now(),i={storage:X.storage,baseUrl:typeof window<`u`?window.location.origin:``,feedLifecycle:{subscribe:async(e,t)=>{if(t?.notebookIds?.length){VI(e,!0);for(let n of t.notebookIds)UI(e,n,!0);await JF()}let n=t?.notebookIds?.length?await sV(e,{notebookIds:t.notebookIds,preserveSubscriptionState:!0}):await cV(e,{offlinePolicy:e===`core`?`offline-full`:`index-only`});return{sourceId:e,subscribed:!0,notebookIds:t?.notebookIds??null,synced:n!==`error`}},unsubscribe:async e=>{let{deleted:t}=await dV(e);return{sourceId:e,unsubscribed:!0,deletedNotes:t}},delete:async e=>{let{deleted:t}=await fV(e);return{sourceId:e,deleted:!0,deletedNotes:t}}},confirmDestructive:e=>M9(e,n),onMutated:async()=>{BP(),await Xq().catch(()=>{})}};try{let n=await e.execute(t,i);return await G9(),d7({toolName:e.name,timestamp:Date.now(),durationMs:Math.round(performance.now()-r),ok:!0,argsPreview:JSON.stringify(t??{}).slice(0,120)}),n}catch(n){throw d7({toolName:e.name,timestamp:Date.now(),durationMs:Math.round(performance.now()-r),ok:!1,argsPreview:JSON.stringify(t??{}).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),RTe=()=>{let e=dt(),t=Qe(),n=RZ(),r=zZ(),i=tZ(),a=EX(),o=MX(),s=RW(),c=bX(),l=YX(),u=RX(),d=(0,K.useSyncExternalStore)(e0,$1,()=>null),{theme:f,setTheme:p}=So(),m=kB(),{isDebugMode:h,toggleDebugMode:g}=Ew(),{unit:_,setUnit:v}=fk(typeof window<`u`?window.localStorage:void 0),{navState:y,dispatch:b}=NV();return(0,K.useEffect)(()=>{if(typeof navigator<`u`&&typeof document<`u`){let e=document,t=navigator;if(e.modelContext&&!t.modelContext)try{Object.defineProperty(navigator,"modelContext",{configurable:!0,enumerable:!0,get:()=>e.modelContext})}catch{}let n=e.modelContext,r=t.modelContext;Q9(n),r!==n&&Q9(r);let i=navigator;if((r||n)&&!i.modelContextTesting)try{Object.defineProperty(navigator,"modelContextTesting",{configurable:!0,enumerable:!0,value:{listTools:async()=>{let e=i.modelContext;return e&&typeof e.listTools==`function`?e.listTools():e&&typeof e.getTools==`function`?e.getTools():[]},executeTool:async(...e)=>{let t=i.modelContext;if(!t||typeof t.executeTool!=`function`)throw Error(`navigator.modelContext.executeTool is unavailable`);return t.executeTool(...e)},callTool:async(...e)=>{let t=i.modelContext;if(t&&typeof t.callTool==`function`)return t.callTool(...e);if(t&&typeof t.executeTool==`function`)return t.executeTool(...e);throw Error(`navigator.modelContext.callTool is unavailable`)}}})}catch{}let a=Si(PTe,{allow:()=>!0});return()=>{a()}}},[]),(0,K.useEffect)(()=>{let e=u7({name:`ui_get_view_context`,title:`Get Active UI View Context`,description:`Read current browser route, readiness, stream results, editor, and clock.`,tier:0,scope:`global-ui`}),t=u7({name:`ui_navigate`,title:`Navigate Playground Route`,description:`Navigate the SPA router to any internal WOD Wiki path.`,tier:1,scope:`global-ui`}),n=u7({name:`ui_cast_control`,title:`Inspect or Disconnect Cast Session`,description:`Inspect or disconnect Chromecast / receiver display session.`,tier:1,scope:`global-ui`}),r=u7({name:`ui_preferences`,title:`Get or Set Playground UI Preferences`,description:`Read or update theme, audio cues, debug mode, analytics units, and mobile drawers.`,tier:1,scope:`global-ui`}),i=Ii.map(e=>u7({name:e.name,title:`UI-SDK ${e.name[0].toUpperCase()}${e.name.slice(1)}`,description:e.description,tier:+(e.name===`act`),scope:`global-ui`}));return()=>{e(),t(),n(),r();for(let e of i)e()}},[]),Or({name:`ui_get_view_context`,title:`Get Active UI View Context`,description:`Read the current browser route, hydration/loading state, unbatched stream results, active editor metadata, and live workout clock snapshot.`,inputSchema:hTe,annotations:{title:`Get Active UI View Context`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let l=performance.now(),u=e.includeSampleEntries!==!1,p=a&&s&&s.pathname===t.pathname?s:null,g={hydrated:document.body.dataset.appHydrated===`true`,status:i||n===`preparing`||r?`loading`:`ready`,feedReadiness:n,importPending:r,route:{pathname:t.pathname,search:t.search,hash:t.hash,href:window.location.href},stream:a?{route:a.route,query:a.query,defaultQuery:a.defaultQuery,layout:a.layout,availableLayouts:a.availableLayouts,groupBy:a.groupBy??null,loading:a.loading,totalUnbatchedCount:p?p.entries.length:null,...u&&p?{entries:p.entries.slice(0,50).map(e=>({id:e.id,title:e.title,date:e.date??null,notebookId:e.notebookId??null}))}:{}}:null,editor:c?{noteId:c.noteId??null,readonly:c.readonly,sourceRevision:c.sourceRevision??null,workoutBlockIds:c.getBlocks().map(e=>e.id)}:null,explorer:o?{draft:o.draft,submitted:o.submitted,weeks:o.weeks,loading:o.loading,saveReady:o.saveReady}:null,preferences:{theme:f,audioEnabled:m?.isEnabled??!1,debugMode:h,analyticsUnit:_,leftDrawerOpen:y.leftDrawerOpen,rightDrawerOpen:y.rightDrawerOpen},clock:d};return d7({toolName:`ui_get_view_context`,timestamp:Date.now(),durationMs:Math.round(performance.now()-l),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),g}}),Or({name:`ui_navigate`,title:`Navigate Playground Route`,description:"Navigate the React Router SPA to any WOD Wiki route (`/journal`, `/day/:date`, `/note/:id`, `/notebooks`, `/dashboards`, `/run/:id?note=:noteId`) and wait for UI commit.",inputSchema:gTe,annotations:{title:`Navigate Route`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(t){let n=performance.now(),r=t.path.startsWith(`/`)?t.path:`/${t.path}`;e(r,{replace:t.replace===!0}),await G9();let i={navigatedTo:r,href:window.location.href};return d7({toolName:`ui_navigate`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!0,argsPreview:JSON.stringify(t).slice(0,120)}),i}}),Or({name:`ui_cast_control`,title:`Inspect or Disconnect Cast Session`,description:`Check active Chromecast / receiver display session state or cleanly disconnect an active Cast session.`,inputSchema:_Te,annotations:{title:`Cast Session Control`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now(),n=V1(),r=U1.getActiveHandle();e.action===`disconnect`&&r&&(U1.dispose(!0),yB(null),await G9());let i={action:e.action,backendState:n.state,connected:!!U1.getActiveHandle()};return d7({toolName:`ui_cast_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}}),Or({name:`ui_preferences`,title:`Get or Set Playground UI Preferences`,description:"Read or update global Playground UI preferences (`theme`, `audioEnabled`, `debugMode`, `analyticsUnit`, and mobile navigation drawers).",inputSchema:STe,annotations:{title:`Playground UI Preferences`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now(),n=f,r=m?.isEnabled??!1,i=h,a=_,o=y.leftDrawerOpen,s=y.rightDrawerOpen;e.action===`set`&&(e.theme!==void 0&&e.theme!==f&&(p(e.theme),n=e.theme),e.audioEnabled!==void 0&&m&&e.audioEnabled!==m.isEnabled&&(m.toggleAudio(),r=e.audioEnabled),e.debugMode!==void 0&&e.debugMode!==h&&(g(),i=e.debugMode),e.analyticsUnit!==void 0&&e.analyticsUnit!==_&&(v(e.analyticsUnit),a=e.analyticsUnit),e.leftDrawerOpen!==void 0&&(b({type:`SET_LEFT_DRAWER`,open:e.leftDrawerOpen}),o=e.leftDrawerOpen),e.rightDrawerOpen!==void 0&&(b({type:`SET_RIGHT_DRAWER`,open:e.rightDrawerOpen}),s=e.rightDrawerOpen),await G9());let c={theme:n,audioEnabled:r,debugMode:i,analyticsUnit:a,leftDrawerOpen:o,rightDrawerOpen:s};return d7({toolName:`ui_preferences`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),c}}),(0,q.jsxs)(q.Fragment,{children:[W9.map(e=>(0,q.jsx)(LTe,{spec:e},e.name)),a&&(0,q.jsx)(NTe,{stream:a}),o&&(0,q.jsx)(jTe,{explorer:o}),c&&(0,q.jsx)(ATe,{editor:c}),(l||c)&&(0,q.jsx)(kTe,{}),u&&(0,q.jsx)(q9,{results:u}),d&&(0,q.jsx)(MTe,{clock:d})]})};function zTe(){let{pathname:e,hash:t}=Qe(),{scrollToSection:n}=NV();return(0,K.useLayoutEffect)(()=>{if(SK(e),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 BTe(){return Vwe(),S9(),(0,K.useEffect)(()=>{qP.current().catch(console.error),Ule(),HZ(),wz().catch(()=>{}),V5().catch(()=>{})},[]),null}function $9({settling:e}){let t=BZ();if(e){let e=rZ(t);return(0,q.jsxs)(`div`,{role:`status`,className:`flex min-h-dvh flex-col items-center justify-center gap-2 text-muted-foreground`,children:[(0,q.jsx)(`span`,{children:t?nZ(t):`Loading library…`}),e&&(0,q.jsx)(`span`,{className:`text-xs`,"data-testid":`boot-progress-detail`,children:e})]})}return(0,q.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The feed corpus has not supplied this page. Re-running the feed import usually restores it.`}),(0,q.jsx)(J,{variant:`outline`,size:`sm`,"data-testid":`root-refeed`,onClick:()=>{iV().then(()=>BP())},children:`Re-import library`})]})}function VTe(){let e=(0,K.useRef)(()=>{}),t=Oq(),n=RZ(),r=(0,K.useMemo)(()=>ZK(()=>e.current(),t),[t]);return(0,q.jsx)(Xee,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,q.jsx)(Tw,{children:(0,q.jsx)(xV,{children:(0,q.jsx)(TV,{children:(0,q.jsx)(EB,{children:(0,q.jsx)(R,{children:(0,q.jsxs)(Rt,{children:[(0,q.jsx)(BTe,{}),(0,q.jsx)(ite,{}),(0,q.jsxs)(RV,{tree:r,children:[(0,q.jsx)(zTe,{}),(0,q.jsx)(RTe,{}),(0,q.jsx)(Uwe,{}),(0,q.jsx)(Gwe,{}),(0,q.jsx)(zwe,{searchHandlerRef:e,canvasRouteList:t,rootUnavailable:t.length===0?(0,q.jsx)($9,{settling:n===`preparing`||VB()&&n!==`error`}):void 0,pageSettlingFallback:t.length===0&&(n===`preparing`||VB()&&n!==`error`)?(0,q.jsx)($9,{settling:!0}):void 0}),(0,q.jsx)(Bwe,{})]})]})})})})})})})}function HTe({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e);return KP(),(0,q.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`The API data store could not be opened.`}),(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,q.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.`,!1]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,q.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`}),!1]}),!1]})}function UTe(){let e=(0,K.useSyncExternalStore)(jE,AE),t=e.phase===`updating`;return(0,q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var WTe=(0,bo.createRoot)(document.getElementById(`root`));function GTe(){let[e,t]=(0,K.useState)(!1),[n,r]=(0,K.useState)(null),[i,a]=(0,K.useState)(0),o=(0,K.useSyncExternalStore)(jE,AE);return(0,K.useEffect)(()=>{let e=!1,n;return ZP().then(()=>ZF(X.storage)).then(()=>FR?BR():void 0).then(()=>jI.ensureNotebooks().catch(e=>dR(`NotebookService`,`ensureNotebooks failed`,e))).then(()=>{e||(n=eF(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),(0,K.useEffect)(()=>{if(!e){delete document.body.dataset.appHydrated;return}return document.body.dataset.appHydrated=`true`,()=>{delete document.body.dataset.appHydrated}},[e]),n?(0,q.jsx)(HTe,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,q.jsx)(UTe,{}):e?(0,q.jsx)(VTe,{}):(0,q.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Opening local library…`})}WTe.render((0,q.jsx)(K.StrictMode,{children:(0,q.jsx)(GTe,{})}));
|
|
1203
|
-
//# sourceMappingURL=main-
|
|
1202
|
+
`)}`:``;if(e.kind===`effort`){let i=e.met??5;return`---\nid: effort-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}${r}\nbaseAttributes:\n met: ${i}\n---\n\n# ${n}\n`}if(e.kind===`equipment`)return`---\ntype: equipment\nid: equipment-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}${r}\n---\n\n# ${n}\n`;if(e.kind===`tag`){let r=e.category??`general`;return`---\ntype: tag\nid: tag-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}\ncategory: ${r}\n---\n\n# ${n}\n`}let i=e.color??`#6366f1`;return`---\ntype: tag-type\nid: type-${t}\nslug: ${t}\nlabel: ${JSON.stringify(n)}\ncolor: ${JSON.stringify(i)}\n---\n\n# ${n}\n`}var $we=[Xwe,P9({name:`wod_catalog_upsert`,title:`Save Effort, Equipment, or Tag Property Note`,description:"Create or update a Scoped Property Override (`effort`, `equipment`, `tag`, or `tag-type`) in `notebook/custom` or a shared user Notebook.",tier:1,domain:`catalog`,annotations:{title:`Save Catalog Property`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Zwe,cliEquivalent:`wod catalog save <kind> <file|-> --json`,async execute(e,t){let n=Qwe(e),r=await lS(t.storage,{targetNotebookId:e.targetNotebookId??`notebook/custom`,kind:e.kind,slug:e.slug,rawContent:n,title:e.label,category:e.category});return await t.onMutated?.([`notes`,`block_revisions`,`property_overrides`,`efforts`,`equipment`,`tags`,`tag_types`]),{id:r.id,kind:r.kind,slug:r.slug,label:r.label,notebookId:r.notebookId,ownerNoteId:r.ownerNoteId}}})],eTe=[P9({name:`wod_feed_manage`,title:`Manage Feeds & Portability`,description:"Inspect installed Seed/Feed sources (`list`), check unpublished public Notebook changes (`status`), compile and publish public Notebooks (`publish`), import portable Markdown + JSONL/CSV files (`import-bundle`), or subscribe/unsubscribe/delete a Feed source.",tier:1,domain:`feed`,annotations:{title:`Manage Feeds`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({action:Qt([`list`,`status`,`publish`,`import-bundle`,`subscribe`,`unsubscribe`,`delete`]).describe(`Feed or portability operation to run.`),sourceId:G().min(1).optional().describe(`Target Feed source ID when action is "subscribe", "unsubscribe", or "delete".`),notebookIds:me(G().min(1)).optional().describe(`Optional subset of Notebook IDs when action="subscribe".`),url:G().min(1).optional().describe(`Optional Feed manifest URL when subscribing to a custom source.`),confirmId:G().optional().describe(`Confirmation token (must match sourceId) for non-interactive unsubscribe/delete calls.`),notebookSlug:G().optional().describe(`Optional Notebook slug filter when publishing.`),name:G().optional().describe(`Optional Feed display name when publishing or subscribing.`),description:G().optional().describe(`Optional Feed description when publishing.`),files:me(yi({path:G().min(1),content:G()})).optional().describe('Portable `.md` / `.jsonl` / `.csv` files when action="import-bundle".')}),cliEquivalent:`wod feed <list|status|publish|subscribe|unsubscribe|delete> --json`,async execute(e,t){if(e.action===`list`){let e=await t.storage.readonly(`meta`).getAll(),n=await mC(t.storage),r=[];for(let t of e){let e=t;if(typeof e.key==`string`&&e.key.startsWith(`seed:`)&&e.key!==bx(`user`)){let t=e.key.slice(5),i=n[t];r.push({sourceId:t,seedVersion:e.seedVersion,builtAt:e.builtAt,importedAt:e.importedAt,chunkCount:Object.keys(e.chunks??{}).length,subscribed:i?.subscribed??!0,offlinePolicy:i?.offlinePolicy??(t===`core`?`offline-full`:`index-only`),autoSync:i?.autoSync??t===`core`})}}return{action:`list`,installedCount:r.length,feeds:r,subscriptions:n}}if(e.action===`subscribe`){if(!e.sourceId)throw Error('Provide `sourceId` when action="subscribe".');let n=t.feedLifecycle?.subscribe?await t.feedLifecycle.subscribe(e.sourceId,{notebookIds:e.notebookIds,url:e.url,name:e.name}):await hC(t.storage,e.sourceId,{notebookIds:e.notebookIds,url:e.url,name:e.name});return await t.onMutated?.([`meta`,`notes`]),{action:`subscribe`,...n}}if(e.action===`unsubscribe`){if(!e.sourceId)throw Error('Provide `sourceId` when action="unsubscribe".');if(e.sourceId===`core`)throw Error(`Core feed cannot be unsubscribed.`);await F9(t,{action:`wod_feed_manage:unsubscribe`,targetId:e.sourceId,summary:`Unsubscribe from feed '${e.sourceId}' and purge its imported notes`},e.confirmId);let n=t.feedLifecycle?.unsubscribe?await t.feedLifecycle.unsubscribe(e.sourceId):await gC(t.storage,e.sourceId);return await t.onMutated?.([`meta`,`notes`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`property_overrides`]),{action:`unsubscribe`,...n}}if(e.action===`delete`){if(!e.sourceId)throw Error('Provide `sourceId` when action="delete".');if(e.sourceId===`core`)throw Error(`Core feed cannot be deleted.`);await F9(t,{action:`wod_feed_manage:delete`,targetId:e.sourceId,summary:`Delete feed source '${e.sourceId}' and purge all of its imported notes`},e.confirmId);let n=t.feedLifecycle?.delete?await t.feedLifecycle.delete(e.sourceId):await _C(t.storage,e.sourceId);return await t.onMutated?.([`meta`,`notes`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`property_overrides`]),{action:`delete`,...n}}if(e.action===`status`)return{action:`status`,...await FS(t.storage,t.feedTree)};if(e.action===`publish`){let n=t.feedTree??new DS,r=await PS(t.storage,n,{layout:`feed`,notebookSlug:e.notebookSlug,name:e.name,description:e.description});return await t.onMutated?.([`meta`,`property_overrides`]),{action:`publish`,notebooks:r.notebooks,totalNotes:r.totalNotes,totalPublicSessions:r.totalPublicSessions,manifestVersion:r.manifest.version,manifestSha256:r.manifestSha256}}if(!e.files||e.files.length===0)throw Error('Provide non-empty `files` array when action="import-bundle".');let n=await zoe(t.storage,e.files,{defaultNotebookId:e.notebookSlug});return await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`tags`,`note_tags`,`sessions`,`events`]),{action:`import-bundle`,...n}}}),P9({name:`wod_export_bundle`,title:`Export Portable Markdown & Telemetry Bundle`,description:"Export user Notes and attached Session telemetry directly as structured `{ path, content }` strings (Markdown + JSONL/CSV) without triggering synthetic browser file downloads.",tier:0,domain:`feed`,annotations:{title:`Export Portable Bundle`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteIds:me(G()).optional().describe(`Optional Note IDs to export (defaults to all user-owned Notes).`),telemetryFormat:Qt([`jsonl`,`csv`,`both`]).optional().describe(`Format for companion Session/Event telemetry files (default "jsonl").`)}),cliEquivalent:`wod export note <id> -o -`,async execute(e,t){let n=await Roe(t.storage,{noteIds:e.noteIds,telemetryFormat:e.telemetryFormat??`jsonl`});return{fileCount:n.length,files:n}}}),P9({name:`wod_reset_storage`,title:`Wipe Storage Data`,description:`Wipe user Notes, Sessions, Events, and Notebook data from the active storage backend (Tier 2 destructive — requires explicit user confirmation).`,tier:2,domain:`system`,annotations:{title:`Wipe Storage Data`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({confirmToken:G().optional().describe(`For non-interactive MCP/CLI calls, pass confirmToken="WIPE_STORAGE" to confirm wiping user storage.`)}),cliEquivalent:`wod reset --yes WIPE_STORAGE --json`,async execute(e,t){return await F9(t,{action:`wod_reset_storage`,targetId:`WIPE_STORAGE`,summary:`Wipe all user Notes, Sessions, and telemetry from WOD Wiki storage`},e.confirmToken),await t.storage.wipe(),await t.onMutated?.([`notes`,`sessions`,`events`,`page`,`page_notes`,`notebook_links`]),{wiped:!0}}})],tTe=[P9({name:`wod_journal_day`,title:`Get Journal Day`,description:"Fetch all scheduled/authored workout Notes and recorded Sessions for a specific Journal calendar day (`YYYY-MM-DD` or `today`).",tier:0,domain:`journal`,annotations:{title:`Get Journal Day`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({date:G().optional().describe(`Calendar date in YYYY-MM-DD format, or "today" (defaults to "today").`)}),cliEquivalent:`wod journal [today|YYYY-MM-DD] --json`,async execute(e,t){let n=R9(e.date),r=await aw(t.storage,n),i=Date.parse(`${n}T00:00:00Z`),a=Date.parse(`${n}T23:59:59.999Z`),o;try{o=await t.storage.readonly(`page`).getAllFromIndex(`by-date`,n)}catch{o=(await t.storage.readonly(`page`).getAll()).filter(e=>e.date===n)}let s=o[0],c=[];if(s){let e=cs(await t.storage.readonly(`page_notes`).getAllFromIndex(`by-page`,s.id));for(let t of e)c.includes(t.noteId)||c.push(t.noteId)}let l=await t.storage.readonly(`notes`).getAll(),u=new Map(l.map(e=>[e.id,e])),d=[],f=new Set;for(let{item:e,note:t}of r.planned){let n=t??u.get(e.noteId);n&&!f.has(n.id)&&(d.push(n),f.add(n.id))}for(let e of c){let t=u.get(e);t&&!f.has(t.id)&&(d.push(t),f.add(t.id))}for(let e of l){if(f.has(e.id)||e.seedOrigin===`seed`||e.feedOrigin===`feed`||e.id.startsWith(`notebook/`)&&e.notebookId===e.id)continue;let t=e.date??e.createdAt;t>=i&&t<=a&&(d.push(e),f.add(e.id))}let p=new Map;for(let e of r.planned)for(let t of e.pairedSessions)p.set(t.id,t);for(let e of r.adhocSessions)p.set(e.session.id,e.session);let m=Array.from(p.values()).sort((e,t)=>e.startTime-t.startTime);for(let e of m){if(f.has(e.noteId))continue;let t=u.get(e.noteId);t&&(d.push(t),f.add(t.id))}return{date:n,url:`${(t.baseUrl??``).replace(/\/+$/,``)}/day/${n}`,pageId:s?.id??null,plannedCount:r.planned.length,planned:r.planned.map(({item:e,note:t,pairedSessions:n})=>({scheduleItemId:e.id,noteId:e.noteId,noteTitle:t?.title??e.noteId,status:n.length>0?`completed`:e.status,...e.slot?{slot:e.slot}:{},...e.notes?{notes:e.notes}:{},pairedSessionIds:n.map(e=>e.id)})),adhocSessionCount:r.adhocSessions.length,adhocSessions:r.adhocSessions.map(({session:e,note:t})=>({id:e.id,noteId:e.noteId,noteTitle:t?.title??e.noteId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,...e.noteSourceRevision?{noteSourceRevision:e.noteSourceRevision}:{}})),noteCount:d.length,notes:d.map(e=>({id:e.id,title:e.title,sourceRevision:e.sourceRevision,rawContent:e.rawContent,tags:e.tags??[],wodBlockIds:Object.values(e.blocks??{}).filter(e=>e.kind===`wod`).map(e=>e.id),url:V9(e,t.baseUrl)})),sessionCount:m.length,sessions:m.map(e=>({id:e.id,noteId:e.noteId,blockId:e.blockId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,...e.scheduleItemId?{scheduleItemId:e.scheduleItemId}:{},...e.sessionDate?{sessionDate:e.sessionDate}:{},...e.noteSourceRevision?{noteSourceRevision:e.noteSourceRevision}:{}}))}}}),P9({name:`wod_journal_add`,title:`Add Workout to Journal Day`,description:"Create a lightweight workout Note (unfiled unless `notebookId` is given) and schedule it onto the specified calendar day via a `ScheduleItem`.",tier:1,domain:`journal`,annotations:{title:`Add Workout to Journal Day`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({date:G().optional().describe(`Target Journal date in YYYY-MM-DD format or "today" (defaults to "today").`),title:G().optional().describe(`Workout title (defaults to # H1 heading or date).`),content:G().min(1).describe(`Markdown workout note or bare Whiteboard Script to schedule onto the Journal day.`),sport:G().optional().describe(`Optional sport fence tag when passing bare Whiteboard Script.`),notebookId:G().optional().describe(`Optional user Notebook ID to assign this Note into (omit to keep unfiled on Journal).`)}),cliEquivalent:`wod journal add <file|-> --date YYYY-MM-DD --json`,async execute(e,t){let n=R9(e.date),r=e.title??`Workout ${n}`,i=L9(e.content,e.sport,e.title),a=await B9(t.storage,{title:r,rawContent:i,journalDate:n,notebookId:e.notebookId,type:`journal`});await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`notebook_links`,`schedule_items`]);let o=(t.baseUrl??``).replace(/\/+$/,``);return{date:n,noteId:a.note.id,...a.scheduleItemId?{scheduleItemId:a.scheduleItemId}:{},journalUrl:`${o}/day/${n}`,note:{id:a.note.id,title:a.note.title,sourceRevision:a.note.sourceRevision,blockCount:a.blockCount,effortSlugs:a.effortSlugs,url:V9(a.note,t.baseUrl)}}}})],H9=new Set(ks.map(e=>e.slug)),nTe=[P9({name:`wod_notebook_list`,title:`List Notebooks`,description:`List built-in, user-created, and feed-subscribed Notebooks along with member Note counts and publication status.`,tier:0,domain:`notebook`,annotations:{title:`List Notebooks`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({origin:Qt([`all`,`default`,`user`,`feed`]).optional().describe(`Filter notebooks by origin (default "all").`)}),cliEquivalent:`wod notebook list --json`,async execute(e,t){let[n,r]=await Promise.all([t.storage.readonly(`notes`).getAll(),t.storage.readonly(`notebook_links`).getAll().catch(()=>[])]),i=Ms(n,r,Hy),a=new Map;for(let e of ks)a.set(e.notebookId,{notebookId:e.notebookId,slug:e.slug,name:e.name,description:e.description,icon:e.icon,origin:`default`,writable:!bs(e.notebookId),public:!1,noteCount:i.get(e.notebookId)??0});for(let e of n){if(!As(e))continue;let t=Ss(e.id),n=qb(e.rawContent),r=typeof n.description==`string`?n.description.replace(/^"|"$/g,``):``,o=typeof n.icon==`string`?n.icon.replace(/^"|"$/g,``):`📓`,s=e.feedOrigin===`feed`||e.seedOrigin===`seed`,c=a.get(e.id);a.set(e.id,{notebookId:e.id,slug:t,name:e.title||c?.name||t,description:r||c?.description||``,icon:o||c?.icon||`📓`,origin:c?.origin??(s?`feed`:`user`),writable:!bs(e.id)&&!s,public:e.public===!0,noteCount:i.get(Cs(e.id))??0})}let o=e.origin??`all`,s=(t.baseUrl??``).replace(/\/+$/,``),c=[...a.values()].filter(e=>o===`all`||e.origin===o).map(e=>({id:e.notebookId,...e,url:`${s}/notebook/${encodeURIComponent(e.slug)}`}));return{totalCount:c.length,notebooks:c}}}),P9({name:`wod_notebook_save`,title:`Create, Update, or Promote Notebook`,description:"Create or update a user-owned Notebook, promote/detach a Note across Notebooks (`notebook/journal` permanence preserved), or toggle Notebook publication visibility.",tier:1,domain:`notebook`,annotations:{title:`Save or Promote Notebook`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({action:Qt([`create`,`update`,`promote`,`detach`,`set-public`]).describe(`Operation to perform on a user Notebook.`),notebookId:G().optional().describe(`Target Notebook slug or ID (required for update, promote, detach, set-public).`),name:G().optional().describe(`Display name when creating or renaming a Notebook.`),description:G().optional().describe(`Notebook description.`),icon:G().optional().describe(`Notebook icon/emoji.`),noteId:G().optional().describe(`Note ID to promote into or detach from the Notebook.`),sessionIds:me(G()).optional().describe("Optional Session IDs on `noteId` to promote alongside the Note."),public:Gt().optional().describe(`Visibility flag when action="set-public" or promoting sessions.`)}),cliEquivalent:`wod notebook <create|update|promote> --json`,async execute(e,t){if(e.action===`create`){let n=e.name?.trim()||e.notebookId?.trim();if(!n)throw Error('`name` is required when action="create".');let r=await VS(t.storage,n);if(e.description!==void 0||e.icon!==void 0){let i=`---\ndescription: ${JSON.stringify(e.description??``)}\nicon: ${JSON.stringify(e.icon??`📓`)}\n---\n\n# ${n}\n`,a=await B9(t.storage,{noteId:r,title:n,rawContent:i});await t.storage.readwrite(`notes`).put({...a.note,notebookId:r})}return e.public!==void 0&&await JS(t.storage,r,e.public),await t.onMutated?.([`notes`,`block_revisions`,`notebook_links`]),{action:`create`,notebookId:r,slug:Ss(r),name:n}}if(!e.notebookId)throw Error(`'notebookId' is required for action="${e.action}".`);let n=Cs(e.notebookId),r=Ss(n);if(e.action===`update`){if(H9.has(r))throw Error(`Built-in Notebook '${n}' cannot be modified.`);let i=await t.storage.readonly(`notes`).get(n);if(!i)throw Error(`Notebook not found: ${n}`);let a=qb(i.rawContent),o=e.name??i.title??r,s=e.description??(typeof a.description==`string`?a.description.replace(/^"|"$/g,``):``),c=e.icon??(typeof a.icon==`string`?a.icon.replace(/^"|"$/g,``):`📓`),l=`---\ndescription: ${JSON.stringify(s)}\nicon: ${JSON.stringify(c)}\n---\n\n# ${o}\n`,u=await B9(t.storage,{noteId:n,title:o,rawContent:l});return await t.storage.readwrite(`notes`).put({...u.note,notebookId:n,...i.public===void 0?{}:{public:i.public}}),await t.onMutated?.([`notes`,`block_revisions`]),{action:`update`,notebookId:n,slug:r,name:o}}if(e.action===`promote`){if(!e.noteId)throw Error('`noteId` is required when action="promote".');let r=await HS(t.storage,{noteId:e.noteId,notebookIds:[n],sessionIds:e.sessionIds,shareSessionsPublicly:e.public});return await t.onMutated?.([`notes`,`sessions`,`notebook_links`]),{action:`promote`,noteId:e.noteId,notebookIds:r.notebookIds,promotedSessionIds:r.promotedSessionIds}}if(e.action===`detach`){if(!e.noteId)throw Error('`noteId` is required when action="detach".');let r=await WS(t.storage,e.noteId,n);return await t.onMutated?.([`notes`,`notebook_links`]),{action:`detach`,noteId:e.noteId,notebookIds:r}}if(xs(n))throw Error(`Notebook '${n}' is private/system and cannot be published.`);let i=await JS(t.storage,n,e.public??!0);return await t.onMutated?.([`notes`]),{action:`set-public`,notebookId:n,public:i.public===!0}}}),P9({name:`wod_notebook_delete`,title:`Delete User Notebook`,description:"Delete a user-created Notebook landing note and detach member links while keeping all member Notes safely in `notebook/journal` (Tier 2 destructive).",tier:2,domain:`notebook`,annotations:{title:`Delete User Notebook`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({notebookId:G().min(1).describe(`User Notebook ID or slug to delete (member Notes stay safe in notebook/journal).`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact notebookId or slug to confirm deletion.`)}),cliEquivalent:`wod notebook delete <slug> --yes <slug> --json`,async execute(e,t){let n=Cs(e.notebookId),r=Ss(n);if(H9.has(r))throw Error(`Built-in Notebook '${n}' cannot be deleted.`);let i=e.confirmId===n||e.confirmId===r?n:void 0;await F9(t,{action:`wod_notebook_delete`,targetId:n,summary:`Delete user Notebook "${r}" (${n}); member Notes remain in notebook/journal`},i);let a=await yC(t.storage,n);return await t.onMutated?.([`notes`,`notebook_links`]),a}})];function rTe(e){return e.id.startsWith(`notebook/`)&&e.notebookId===e.id}var iTe=[P9({name:`wod_note_list`,title:`List Notes`,description:`List workout and reference Notes with optional filtering by Notebook, search query, tag, and origin.`,tier:0,domain:`note`,annotations:{title:`List Notes`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({notebookId:G().optional().describe(`Filter by notebook ID or slug (e.g. "journal", "custom", "guides", "notebook/strength").`),search:G().optional().describe(`Case-insensitive substring filter over title and Markdown content.`),tag:G().optional().describe(`Filter to Notes carrying this tag label.`),origin:Qt([`all`,`user`,`feed`,`seed`]).optional().describe(`Filter by Note origin ("user", "feed", "seed", or "all"; defaults to "all").`),includeSeed:Gt().optional().describe(`Include read-only Seed/Feed notes (default true; pass false for user-authored notes only).`),orphanedOnly:Gt().optional().describe("When true, return only user Notes not belonging to any Notebook (equivalent to `:note{!notebook:*}`)."),limit:se().int().min(1).max(200).optional().describe(`Max notes to return (default 50).`)}),cliEquivalent:`wod note list --json`,async execute(e,t){let n=e.notebookId?Cs(e.notebookId):void 0,r=e.includeSeed??!0,i=e.origin??`all`,a=e.orphanedOnly===!0,o=e.search?.trim().toLowerCase(),s=e.tag?.trim().toLowerCase(),c=e.limit??50,{allNotes:l,linkedNoteIdsForNb:u,noteIdsWithLinks:d}=await t.storage.transaction([`notes`,`notebook_links`],`readonly`,async e=>{let t=await e.readonly(`notes`).getAll(),r,i=new Set;try{if(n){let t=await e.readonly(`notebook_links`).getAllFromIndex(`by-notebook`,n);r=new Set(t.filter(e=>e.targetKind===`note`).map(e=>e.noteId))}if(a){let t=await e.readonly(`notebook_links`).getAll();for(let e of t)e.targetKind===`note`&&i.add(e.noteId)}}catch{r=new Set}return{allNotes:t,linkedNoteIdsForNb:r,noteIdsWithLinks:i}}),f=l.filter(e=>{if(rTe(e))return!1;let t=e.seedOrigin===`seed`||e.feedOrigin===`feed`;return!(i===`user`&&t||i===`feed`&&e.feedOrigin!==`feed`||i===`seed`&&e.seedOrigin!==`seed`||!r&&t||a&&(t||d.has(e.id)||Hy(e).length>0)||n&&!(u?.has(e.id)||e.notebookId===n||(e.notebookIds??[]).includes(n)||Hy(e).includes(n))||s&&!(e.tags??[]).some(e=>e.toLowerCase()===s)||o&&!e.title.toLowerCase().includes(o)&&!e.rawContent.toLowerCase().includes(o))}).sort((e,t)=>(t.date??t.createdAt)-(e.date??e.createdAt));return{totalCount:f.length,notes:f.slice(0,c).map(e=>{let n=Wy(e),r=Uy(e);return{id:e.id,title:e.title,sourceRevision:e.sourceRevision,date:e.date,createdAt:e.createdAt,editable:Os(e,n,r),notebooks:Hy(e),tags:e.tags??[],wodBlockCount:Object.values(e.blocks??{}).filter(e=>e.kind===`wod`).length,url:V9(e,t.baseUrl)}})}}}),P9({name:`wod_note_get`,title:`Get Note Details`,description:"Read a full Note by ID including authored Markdown, `sourceRevision`, parsed workout blocks, attached Session count, upstream provenance, and publication visibility.",tier:0,domain:`note`,annotations:{title:`Get Note Details`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`Unique Note ID (UUID or seed route ID).`)}),cliEquivalent:`wod note get <noteId> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.noteId);if(!n)throw Error(`Note not found: ${e.noteId}`);let r=Os(n,Wy(n),Uy(n)),[i,a,o,s,c,l]=await Promise.all([GS(t.storage,n.id),LC(t.storage,n),qS(t.storage,n.id),t.storage.readonly(`sessions`).getAllFromIndex(`by-note`,n.id).catch(async()=>(await t.storage.readonly(`sessions`).getAll()).filter(e=>e.noteId===n.id)),ew(t.storage,n.id).catch(()=>[]),JC(t.storage,n.id).catch(()=>[])]),u=zs(n.rawContent,{registeredWidgets:Ns}),d=Object.values(n.blocks??{}).sort((e,t)=>e.from-t.from).map(e=>{let t=u.find(t=>t.from===e.from&&t.to===e.to);return{id:e.id,kind:e.kind,version:e.version,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{},content:t?.scriptBlock?.content??n.rawContent.slice(e.from,e.to)}});return{id:n.id,title:n.title,rawContent:n.rawContent,portableMarkdown:Gb(n),sourceRevision:n.sourceRevision,editable:r,date:n.date,createdAt:n.createdAt,tags:n.tags??[],notebooks:i.map(e=>({id:e,slug:Ss(e)})),scheduleCount:c.length,scheduleItems:c,revisionCount:l.length,blocks:d,sessionCount:s.length,recentSessions:s.sort((e,t)=>t.startTime-e.startTime).slice(0,10).map(e=>({id:e.id,blockId:e.blockId,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,public:e.public===!0})),...a?{provenance:a}:{},visibility:o,url:V9(n,t.baseUrl)}}}),P9({name:`wod_note_upsert`,title:`Create or Update Note`,description:"Create a new workout/reference Note or update an existing editable Note with full block-revision pinning, effort/equipment indexing, and optimistic concurrency (`expectedSourceRevision`).",tier:1,domain:`note`,annotations:{title:`Create or Update Note`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Existing Note ID to update, or omit to create a new Note.`),title:G().optional().describe(`Note title (defaults to # H1 heading in content).`),content:G().min(1).describe(`Full Markdown document or Whiteboard Script body.`),sport:G().optional().describe(`Optional sport fence tag when passing bare Whiteboard Script.`),expectedSourceRevision:se().int().min(0).optional().describe(`Optimistic concurrency guard: pass the current sourceRevision from wod_note_get when updating.`),notebookId:G().optional().describe(`Optional user Notebook ID/slug to assign this Note into (omit for unfiled/existing memberships).`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" to place the Note on that Journal calendar day.`)}),cliEquivalent:`wod note save <file|-> --json`,async execute(e,t){let n=L9(e.content,e.sport,e.title),r=await B9(t.storage,{noteId:e.noteId,title:e.title,rawContent:n,expectedSourceRevision:e.expectedSourceRevision,notebookId:e.notebookId,journalDate:e.journalDate});return await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`tags`,`note_tags`,`page`,`page_notes`,`notebook_links`]),{id:r.note.id,noteId:r.note.id,title:r.note.title,created:r.created,sourceRevision:r.note.sourceRevision,blockCount:r.blockCount,effortSlugs:r.effortSlugs,equipmentSlugs:r.equipmentSlugs,tags:r.tagLabels,url:V9(r.note,t.baseUrl)}}}),P9({name:`wod_note_clone`,title:`Clone Note with Provenance`,description:"Clone any Note (especially read-only Seed or Feed workouts) into a writable user Notebook or Journal day while recording structured upstream `NoteProvenance`.",tier:1,domain:`note`,annotations:{title:`Clone Note`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({sourceNoteId:G().min(1).describe(`Source Note ID (including read-only Seed/Feed Notes) to clone.`),targetNotebookId:G().optional().describe(`Target writable user Notebook ID/slug (defaults to "notebook/journal").`),title:G().optional().describe(`Optional title override for the cloned Note.`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" to pin the clone onto a Journal day.`)}),cliEquivalent:`wod note clone <sourceNoteId> --notebook <slug> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.sourceNoteId);if(!n)throw Error(`Source Note not found: ${e.sourceNoteId}`);let r=Cs(e.targetNotebookId??`notebook/journal`);if(bs(r))throw Error(`Target Notebook '${r}' is read-only.`);let i=Date.now(),a=I9(),o=Hy(n)[0],s=RC(n,o,i),c={...(await B9(t.storage,{noteId:a,title:e.title??n.title,rawContent:n.rawContent,notebookId:r,journalDate:e.journalDate,tags:(n.tags??[]).map(e=>({label:e})),now:i})).note,sourceId:n.id,provenance:s};return await t.storage.readwrite(`notes`).put(c),r!==`notebook/journal`&&await HS(t.storage,{noteId:a,notebookIds:[r]}),await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`notebook_links`,`page`,`page_notes`]),{id:c.id,noteId:c.id,title:c.title,sourceRevision:c.sourceRevision,targetNotebookId:r,provenance:s,url:V9(c,t.baseUrl)}}}),P9({name:`wod_note_delete`,title:`Delete Note`,description:`Permanently delete a Note and detach its projections, tag links, and calendar placements (Tier 2 destructive — requires user confirmation or matching confirmId).`,tier:2,domain:`note`,annotations:{title:`Delete Note`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`ID of the Note to delete.`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact noteId to confirm deletion.`)}),cliEquivalent:`wod note delete <noteId> --yes <noteId> --json`,async execute(e,t){let n=await t.storage.readonly(`notes`).get(e.noteId);if(!n)return{deleted:!1,noteId:e.noteId,reason:`not_found`};await F9(t,{action:`wod_note_delete`,targetId:e.noteId,summary:`Delete Note "${n.title||e.noteId}" (${e.noteId})`},e.confirmId);let r=await Jwe(t.storage,e.noteId);return r&&await t.onMutated?.([`notes`,`block_index`,`block_efforts`,`block_equipment`,`note_tags`,`page_notes`,`notebook_links`,`meta`]),{deleted:r,noteId:e.noteId,title:n.title}}})],aTe=[P9({name:`wod_schedule_list`,title:`List Scheduled Workouts`,description:"List M:N ScheduleItem instances by date range (`from`/`to`) or for a specific Note ID.",tier:0,domain:`journal`,annotations:{title:`List Scheduled Workouts`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({from:G().optional().describe(`Start date in YYYY-MM-DD format (inclusive, or "today").`),to:G().optional().describe(`End date in YYYY-MM-DD format (inclusive, or "today").`),noteId:G().optional().describe(`Optional Note ID to list scheduled dates for one workout.`)}),cliEquivalent:`wod schedule list --json`,async execute(e,t){let n;if(e.noteId){if(n=await ew(t.storage,e.noteId),e.from){let t=R9(e.from);n=n.filter(e=>e.date>=t)}if(e.to){let t=R9(e.to);n=n.filter(e=>e.date<=t)}}else if(e.from||e.to){let r=R9(e.from??e.to),i=R9(e.to??e.from);n=await $C(t.storage,r,i)}else n=(await t.storage.readonly(`schedule_items`).getAll()).sort((e,t)=>e.date.localeCompare(t.date)||(e.position??0)-(t.position??0));let r=[...new Set(n.map(e=>e.noteId))],i=await t.storage.readonly(`notes`).getMany(r),a=new Map;return i.forEach((e,t)=>{e&&a.set(r[t],e.title)}),{totalCount:n.length,items:n.map(e=>({...e,noteTitle:a.get(e.noteId)??e.noteId}))}}}),P9({name:`wod_schedule_add`,title:`Schedule Workout onto Day`,description:`Link an existing Note onto a Journal calendar date via a ScheduleItem (M:N link-first scheduling without cloning user Notes or forcing notebook/journal).`,tier:1,domain:`journal`,annotations:{title:`Schedule Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({noteId:G().min(1).describe(`Canonical Note ID to schedule onto a calendar day.`),date:G().optional().describe(`Calendar date YYYY-MM-DD or "today" (defaults to "today").`),slot:G().optional().describe(`Optional slot badge such as "AM", "PM", or "Warmup".`),position:se().int().optional().describe(`Optional ordering index within the day.`),notes:G().optional().describe(`Optional scaling or session intent notes for this scheduled instance.`)}),cliEquivalent:`wod schedule add <noteId> --date YYYY-MM-DD --json`,async execute(e,t){let n=R9(e.date),r=await YC(t.storage,{noteId:e.noteId,date:n,...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}});return await t.onMutated?.([`schedule_items`,`notes`]),{item:r}}}),P9({name:`wod_schedule_batch`,title:`Batch Schedule Workouts`,description:`Schedule one or more existing Notes across target calendar dates atomically via ScheduleItem links.`,tier:1,domain:`journal`,annotations:{title:`Batch Schedule Workouts`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({items:me(yi({noteId:G().min(1),date:G().describe(`Calendar date YYYY-MM-DD or "today".`),slot:G().optional(),position:se().int().optional(),notes:G().optional()})).min(1).describe(`List of Note + date pairs to schedule atomically.`)}),cliEquivalent:`wod schedule batch --json`,async execute(e,t){let n=await XC(t.storage,e.items.map(e=>({noteId:e.noteId,date:R9(e.date),...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}})));return await t.onMutated?.([`schedule_items`,`notes`]),{scheduledCount:n.length,items:n}}}),P9({name:`wod_schedule_update`,title:`Update Scheduled Workout`,description:"Reschedule, reorder, or update status (`planned`, `completed`, `moved`, `skipped`) on a ScheduleItem.",tier:1,domain:`journal`,annotations:{title:`Update Scheduled Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({scheduleItemId:G().min(1).describe(`ScheduleItem ID to update.`),date:G().optional().describe(`New calendar date YYYY-MM-DD or "today".`),status:Qt([`planned`,`completed`,`moved`,`skipped`]).optional().describe(`Updated schedule status.`),slot:G().optional().describe(`Updated slot label.`),position:se().int().optional().describe(`Updated intra-day ordering index.`),notes:G().optional().describe(`Updated intent or scaling notes.`)}),cliEquivalent:`wod schedule update <scheduleItemId> --json`,async execute(e,t){let n=await ZC(t.storage,e.scheduleItemId,{...e.date===void 0?{}:{date:R9(e.date)},...e.status===void 0?{}:{status:e.status},...e.slot===void 0?{}:{slot:e.slot},...e.position===void 0?{}:{position:e.position},...e.notes===void 0?{}:{notes:e.notes}});return await t.onMutated?.([`schedule_items`]),{item:n}}}),P9({name:`wod_schedule_remove`,title:`Unschedule Workout Instance`,description:`Remove a single ScheduleItem from a calendar day while leaving the canonical Note and recorded Sessions intact.`,tier:1,domain:`journal`,annotations:{title:`Unschedule Workout`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({scheduleItemId:G().min(1).describe(`ScheduleItem ID to remove from the calendar.`)}),cliEquivalent:`wod schedule remove <scheduleItemId> --json`,async execute(e,t){return await QC(t.storage,e.scheduleItemId),await t.onMutated?.([`schedule_items`]),{removed:!0,scheduleItemId:e.scheduleItemId}}})];function U9(e,t=[]){for(let n of e.metrics??[])(n.value===`?`||n.origin===`collectible`)&&t.push({...e.id===void 0?{}:{id:e.id},text:e.raw??``,metricType:n.type});for(let n of e.children??[])U9(n,t);return t}var oTe=[P9({name:`wod_parse_script`,title:`Parse Whiteboard Script`,description:"Validate Whiteboard Script syntax, inspect parsed statements, typed metrics, unresolved choices, and collectible `?` placeholders. Defaults to dry-run (`save: false`); pass `save: true` to persist as a Note.",tier:0,domain:`script`,annotations:{title:`Parse Whiteboard Script`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({source:G().min(1).describe("Whiteboard Script body OR full Markdown document containing ```time / ```wod blocks."),sport:G().optional().describe(`Optional sport fence dialect override (e.g. "crossfit", "climbing", "running").`),save:Gt().optional().describe(`Default false (dry-run syntax & metric inspection). Set true to persist as a Note.`),noteId:G().optional().describe(`Optional target Note ID when save=true.`),title:G().optional().describe(`Optional Note title when save=true.`),notebookId:G().optional().describe(`Optional user Notebook slug/ID when save=true.`)}),cliEquivalent:`wod parse - --no-save --json`,async execute(e,t){let n=await dS(t.storage,{...e.notebookId?{notebookId:e.notebookId}:{}}).catch(()=>void 0),r=zs(e.source,{registeredWidgets:Ns}).filter(e=>e.scriptBlock),i=nu({...n?{references:n.referenceIndex,tags:n.tagIndex}:{}}),a=(r.length>0?r.map((t,n)=>({index:n,sport:e.sport??t.scriptBlock?.sport,dialect:t.scriptBlock?.dialect??`time`,body:t.scriptBlock.content})):[{index:0,sport:e.sport,dialect:`time`,body:e.source}]).map(e=>{let t=i.read(e.body,e.sport),n=wae(t),r=Rm(t.statements).map(e=>({statementIndex:e.statementIndex,statementId:e.statementId,choice:e.choice})),a=U9(n);return{index:e.index,dialect:e.dialect,...e.sport?{sport:e.sport}:{},valid:(t.errors?.length??0)===0,errors:t.errors??[],statementCount:t.statements.length,tree:n,unresolvedChoices:r,collectibles:a}}),o=a.every(e=>e.valid),s;if(e.save&&o){let n=L9(e.source,e.sport,e.title),r=await B9(t.storage,{noteId:e.noteId,title:e.title,rawContent:n,notebookId:e.notebookId});await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`]),s={noteId:r.note.id,title:r.note.title,sourceRevision:r.note.sourceRevision,created:r.created}}return{valid:o,blockCount:a.length,blocks:a,...s?{savedNote:s}:{}}}})];function sTe(e,t){if(!t||Object.keys(t).length===0)return e;let n=Object.entries(t),r=e;for(let[e,t]of n){let n=String(t);if(e===`?`||e==="default")r=r.replace(/\?/g,n);else{let t=RegExp(`\\?\\s*${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}\\b`,`gi`);r=t.test(r)?r.replace(t,`${n} ${e}`):r.replace(/\?/,n)}}return r}var cTe=P9({name:`wod_session_run_headless`,title:`Run Workout Session Headlessly`,description:"Execute a workout block through the headless JIT compiler and runtime state machine, recording a pinned `Session` and derived `EventRecord`s in storage. Automatically clones read-only Seed/Feed Notes into `notebook/journal`.",tier:1,domain:`session`,annotations:{title:`Run Workout Headlessly`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Existing Note ID to execute (read-only Seed/Feed Notes pin one immutable copy on first run).`),blockId:G().optional().describe("Optional workout block ID on `noteId` (defaults to first wod block)."),source:G().optional().describe("Inline Whiteboard Script or Markdown to persist & run when `noteId` is not supplied."),title:G().optional().describe("Optional Note title when running inline `source`."),sport:G().optional().describe(`Optional sport dialect override.`),journalDate:G().optional().describe(`Optional YYYY-MM-DD or "today" attributed Session calendar date.`),scheduleItemId:G().optional().describe(`Optional ScheduleItem ID that triggered this workout run.`),collectibles:Ne(G(),yn([G(),se()])).optional().describe('Optional values for collectible `?` metrics (e.g. `{ "lb": 185, "reps": 12 }`).'),stepAdvanceMs:se().int().min(100).max(36e5).optional().describe(`Simulated clock advance per step in milliseconds (default 10000).`),maxSteps:se().int().min(1).max(5e3).optional().describe(`Safety cap on execution steps (default 500).`),public:Gt().optional().describe(`Mark the recorded Session public for Feed publication.`)}),cliEquivalent:`wod run <file|--note id> --json`,async execute(e,t){let n=e.noteId;if(!n){if(!e.source?.trim())throw Error("Provide either `noteId` or inline `source` to execute a workout session.");let r=L9(e.source,e.sport,e.title);n=(await B9(t.storage,{title:e.title,rawContent:r,journalDate:e.journalDate,type:`journal`})).note.id}let r=Date.now(),i=await FC(t.storage,{noteId:n,blockId:e.blockId,journalDate:e.journalDate,...e.scheduleItemId?{scheduleItemId:e.scheduleItemId}:{},startedAt:r}),a=sTe(zs(i.revision.rawContent,{registeredWidgets:Ns}).find(e=>e.scriptBlock)?.scriptBlock?.content??i.revision.rawContent,e.collectibles),o=await dS(t.storage,{note:i.note}).catch(()=>void 0),s=e.sport??i.revision.sport,c=nu({...o?{references:o.referenceIndex,tags:o.tagIndex}:{}}).read(a,s);if(c.errors&&c.errors.length>0)throw Error(`Whiteboard Script syntax error: ${c.errors.map(e=>e.message).join(`; `)}`);let l=Dne(new Date(r)),u=new Df,d=new em,f=Tne(new Date(r)),p=new vf(c,rh(),{stack:u,clock:l,eventBus:d},{},f),{engine:m,analyticsContext:h}=Im({id:i.session.blockId,content:a,statements:c.statements,sport:s,version:i.session.blockVersion,startLine:0,endLine:0,dialect:i.revision.dialect??`time`,state:`idle`,createdAt:r});p.analyticsContext=h,p.setAnalyticsEngine(m);let g=[];p.subscribeToOutput(e=>{g.push(e)}),p.do(new nm),u.current?.key.toString().startsWith(`waiting-to-start`)&&p.handle(new th(void 0,{nowMs:()=>l.currentDate.getTime(),now:()=>l.currentDate}));let _=e.stepAdvanceMs??1e4,v=e.maxSteps??500,y=0;for(;u.count>0&&y<v;)l.advance(_),p.handle(new th(void 0,{nowMs:()=>l.currentDate.getTime(),now:()=>l.currentDate})),y+=1;let b=u.count===0,x=l.currentDate.getTime();p.dispose();let S=g.map(Fh),C={noteId:i.session.noteId,resultId:i.session.id,blockId:i.session.blockId,blockVersion:i.session.blockVersion,...i.session.blockContentId?{blockContentId:i.session.blockContentId}:{},...i.session.pageId?{pageId:i.session.pageId}:{},origin:i.session.origin,workoutTimestamp:x},w=jy(S,C),T=My(S,C),E=[...w,...T],D={...i.session,sessionDate:i.session.sessionDate??BC(r),status:b?`completed`:`in-progress`,endTime:x,duration:Math.max(0,x-r),completed:b,...e.public===void 0?{}:{public:e.public}};return await t.storage.transaction([`sessions`,`events`,`notebook_links`,`schedule_items`],`readwrite`,async e=>{await e.readwrite(`sessions`).put(D);let t=(D.notebookIds??[]).map(e=>({id:IS(Cs(e),`session`,D.id),notebookId:Cs(e),targetKind:`session`,targetId:D.id,noteId:D.noteId,createdAt:D.createdAt}));if(t.length>0&&await e.readwrite(`notebook_links`).putMany(t),D.scheduleItemId)try{let t=e.readwrite(`schedule_items`),n=await t.get(D.scheduleItemId);n&&n.status!==`completed`&&await t.put({...n,status:`completed`,updatedAt:x})}catch{}E.length>0&&await e.readwrite(`events`).putMany(E)}),e.public!==void 0&&await YS(t.storage,D.id,e.public),await t.onMutated?.([`notes`,`block_revisions`,`block_index`,`sessions`,`events`,`page`,`page_notes`,`notebook_links`]),{sessionId:D.id,noteId:D.noteId,blockId:D.blockId,blockVersion:D.blockVersion,clonedFromReadOnly:i.clonedFromReadOnly,pinnedExternalWorkout:i.pinnedExternalWorkout,...i.upstreamNoteId?{upstreamNoteId:i.upstreamNoteId}:{},completed:b,stepsExecuted:y,durationMs:D.duration,eventCount:w.length,summaryCount:T.length}}}),lTe=P9({name:`wod_session_list`,title:`List Recorded Sessions`,description:`List recorded workout Sessions ordered newest-first, optionally filtered by Note ID.`,tier:0,domain:`session`,annotations:{title:`List Sessions`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({noteId:G().optional().describe(`Filter Sessions by owning Note ID.`),completedOnly:Gt().optional().describe(`Filter to completed Sessions only.`),limit:se().int().min(1).max(200).optional().describe(`Max Sessions to return (default 50).`)}),cliEquivalent:`wod session list --json`,async execute(e,t){let n=e.limit??50,r;if(e.noteId)try{r=await t.storage.readonly(`sessions`).getAllFromIndex(`by-note`,e.noteId)}catch{r=(await t.storage.readonly(`sessions`).getAll()).filter(t=>t.noteId===e.noteId)}else r=await t.storage.readonly(`sessions`).getAll();e.completedOnly&&(r=r.filter(e=>e.completed)),r.sort((e,t)=>t.startTime-e.startTime);let i=[...new Set(r.slice(0,n).map(e=>e.noteId))],a=await t.storage.readonly(`notes`).getMany(i),o=new Map;return a.forEach((e,t)=>{e&&o.set(i[t],e.title)}),{totalCount:r.length,sessions:r.slice(0,n).map(e=>({id:e.id,noteId:e.noteId,noteTitle:o.get(e.noteId)??e.noteId,blockId:e.blockId,blockVersion:e.blockVersion,status:e.status,completed:e.completed,duration:e.duration,startTime:e.startTime,endTime:e.endTime,public:e.public===!0}))}}}),uTe=P9({name:`wod_session_get`,title:`Get Session Telemetry`,description:"Read a recorded workout Session along with its pinned `BlockRevision` and derived event/summary telemetry rows.",tier:0,domain:`session`,annotations:{title:`Get Session Telemetry`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to inspect.`)}),cliEquivalent:`wod session get <sessionId> --json`,async execute(e,t){let n=await t.storage.readonly(`sessions`).get(e.sessionId);if(!n)throw Error(`Session not found: ${e.sessionId}`);let[r,i,a]=await Promise.all([t.storage.readonly(`notes`).get(n.noteId),t.storage.readonly(`block_revisions`).get([n.noteId,n.blockId,n.blockVersion]),t.storage.readonly(`events`).getAll()]),o=a.filter(e=>e.resultId===n.id).sort((e,t)=>e.timestamp-t.timestamp);return{session:n,noteTitle:r?.title,pinnedRevision:i??null,eventCount:o.filter(e=>e.grain===`event`).length,summaryCount:o.filter(e=>e.grain===`summary`).length,events:o}}}),dTe=P9({name:`wod_session_delete`,title:`Delete Recorded Session`,description:`Permanently delete a recorded workout Session and its telemetry events (Tier 2 destructive — requires confirmation).`,tier:2,domain:`session`,annotations:{title:`Delete Session`,readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to delete.`),confirmId:G().optional().describe(`For non-interactive MCP/CLI calls, repeat the exact sessionId to confirm deletion.`)}),cliEquivalent:`wod session delete <sessionId> --yes <sessionId> --json`,async execute(e,t){let n=await t.storage.readonly(`sessions`).get(e.sessionId);if(!n)return{deleted:!1,sessionId:e.sessionId,reason:`not_found`};await F9(t,{action:`wod_session_delete`,targetId:e.sessionId,summary:`Delete workout Session ${e.sessionId} on Note ${n.noteId}`},e.confirmId);let r=await Ywe(t.storage,e.sessionId);return r&&await t.onMutated?.([`sessions`,`events`,`notebook_links`]),{deleted:r,sessionId:e.sessionId}}}),fTe=[cTe,lTe,uTe,P9({name:`wod_session_attribute`,title:`Attribute Session to Day or Plan`,description:`Associate a recorded workout Session with a specific Journal civil date and/or pair or unlink it with a planned ScheduleItem.`,tier:1,domain:`session`,annotations:{title:`Attribute Session`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({sessionId:G().min(1).describe(`Session ID to attribute to a calendar date or ScheduleItem.`),sessionDate:G().optional().describe(`Attributed Journal date (YYYY-MM-DD).`),scheduleItemId:G().nullable().optional().describe(`ScheduleItem ID to link this Session with, or null to unlink into an ad-hoc Session.`)}),cliEquivalent:`wod session attribute <sessionId> --json`,async execute(e,t){let n=await nw(t.storage,{sessionId:e.sessionId,...e.sessionDate===void 0?{}:{sessionDate:e.sessionDate},...e.scheduleItemId===void 0?{}:{scheduleItemId:e.scheduleItemId}});return await t.onMutated?.([`sessions`,`schedule_items`]),{session:n}}}),dTe],pTe=P9({name:`wod_validate_wql`,title:`Validate & Inspect WQL Query`,description:"Parse a WQL string without executing it. Returns syntax validity, query family (find, aggregate, pipeline), normalized WQL string, and the allowed filter keys and `by {}` grouping dimensions for that plane.",tier:0,domain:`wql`,annotations:{title:`Validate WQL Query`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({query:G().describe(`WQL query string to validate and inspect (e.g. ":note{notebook:journal} last 7d" or "sum:volume by {effort}").`),targetHint:G().optional().describe(`Optional target plane to list valid filter keys & grouping dimensions for (note, session, effort, equipment, tag, feed, block, event).`)}),cliEquivalent:`wod query "<wql>" --format json`,async execute(e){let t=Xg(e.query),n=!t.error,r=Lg(t)?`pipeline`:Fg(t)?`find`:`aggregate`,i=e.targetHint??(Fg(t)?t.target:Ig(t)?`event`:`note`),a=r===`find`?`find`:`aggregate`;return{valid:n,...t.error?{error:t.error}:{},family:r,target:i,normalized:n?Qg(e.query):e.query,allowedTargets:[...qh],allowedAggregators:[...Rh],allowedRollupPeriods:[...ig],validFilterKeys:[...vg(i,a)],validGroupingDimensions:[...yg(i,a)]}}}),mTe=[P9({name:`wod_query_wql`,title:`Execute WQL Query`,description:"Run any WQL find (`:note`, `:session`, `:effort`, `:equipment`, `:tag`, `:feed`, `:block`), aggregate (`sum:volume`, `max:weight`, `count:sessions`), or pipeline query against the active WOD Wiki storage.",tier:0,domain:`wql`,annotations:{title:`Execute WQL Query`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:yi({query:G().min(1).describe(`WQL query expression (e.g. ":note{notebook:journal}", ":session last 30d", "sum:volume by {week}").`),preferredUnit:G().optional().describe(`Optional display unit conversion preference (e.g. "lb", "kg", "m", "mi").`),limit:se().int().min(1).max(500).optional().describe(`Maximum rows/items to return in the response payload (default 100).`)}),cliEquivalent:`wod query '<wql>' --format json`,async execute(e,t){let n=Xg(e.query);if(n.error)throw Error(`WQL Syntax Error in "${e.query}": ${n.error}. Call wod_validate_wql to inspect valid targets and filter keys.`);let r=qwe(t.storage),i=e.limit??100;if(Lg(n)){let t=await r.runPipeline(e.query,{preferredUnit:e.preferredUnit});return{kind:`pipeline-result`,query:e.query,result:t}}if(Fg(n)){let t=await r.runFind(n);return Array.isArray(t.runs)?{kind:`rows-result`,target:n.target,query:e.query,totalRuns:t.runs.length,totalCount:t.runs.length,runs:t.runs.slice(0,i),truncated:t.runs.length>i}:Array.isArray(t.efforts)?{kind:`find-result`,target:n.target,query:e.query,totalCount:t.efforts.length,items:t.efforts.slice(0,i),truncated:t.efforts.length>i}:t.table?{kind:`find-result`,target:n.target,query:e.query,columns:t.table.columns,totalCount:t.table.rows.length,items:t.table.rows.slice(0,i),truncated:t.table.rows.length>i}:n.target===`block`?{kind:`find-result`,target:n.target,query:e.query,totalCount:t.blocks.length,items:t.blocks.slice(0,i),truncated:t.blocks.length>i}:{kind:`find-result`,target:n.target,query:e.query,totalCount:t.notes.length,items:t.notes.slice(0,i),truncated:t.notes.length>i}}let a=await r.runQuery(e.query,{preferredUnit:e.preferredUnit});return{kind:`query-result`,query:e.query,result:a}}}),pTe],W9=[...oTe,...mTe,...iTe,...tTe,...aTe,...nTe,...fTe,...$we,...eTe];new Map(W9.map(e=>[e.name,e]));async function G9(){if(typeof window>`u`||typeof window.requestAnimationFrame!=`function`){await new Promise(e=>setTimeout(e,0));return}await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e())})})}async function K9(e=2e3){let t=Date.now()+e;for(await new Promise(e=>setTimeout(e,200));$X()&&Date.now()<t;)await new Promise(e=>setTimeout(e,25));await G9()}var hTe=yi({includeSampleEntries:Gt().optional().describe(`Include up to 50 unbatched stream entries when on a stream route (default true).`)}),gTe=yi({path:G().min(1).describe(`Internal app path (with optional ?query and #hash) to navigate to, e.g. "/journal", "/day/2026-11-11", "/note/<id>", "/notebooks", "/dashboards".`),replace:Gt().optional().describe(`Replace current history entry instead of pushing.`)}),_Te=yi({action:Qt([`status`,`disconnect`]).describe(`Inspect active Chromecast/receiver session status or disconnect an active session.`)}),vTe=yi({query:G().optional().describe(`WQL query string to apply to the mounted stream view (e.g. ":note{tags:benchmark}").`),layout:Qt([`cards`,`rows`,`feed`,`agenda`,`planner`]).optional().describe(`Switch stream layout mode and sync ?layout= in URL.`),groupBy:G().nullable().optional().describe(`Grouping dimension (e.g. "date", "week", "notebook") or null to clear.`),month:G().regex(/^\d{4}-\d{2}$/,`Expected YYYY-MM calendar month`).optional().describe(`Calendar month anchor in YYYY-MM format (syncs ?month= on calendar/journal views).`),overlayMode:Qt([`all`,`planned`,`logged`]).optional().describe("Calendar schedule/session overlay filter (`all`, `planned`, or `logged`)."),resetToDefault:Gt().optional().describe(`Undo custom stream filter and restore the route default WQL query.`)}),yTe=yi({operation:Qt([`read`,`replace`,`append`,`undo`]).describe(`Read live editor buffer, replace document content, append Markdown/workout block, or undo last edit.`),content:G().optional().describe(`Markdown or Whiteboard Script content for replace / append operations.`),save:Gt().optional().describe(`Flush and persist the draft to storage immediately after applying the edit (default false).`)}),bTe=yi({blockId:G().optional().describe("Optional workout block ID in the active Note editor (defaults to first ```time block)."),autoStart:Gt().optional().describe(`Automatically start the timer after mounting the workout clock (default true).`)}),xTe=yi({command:Qt([`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`,`status`]).describe(`Live workout clock command to dispatch (or "status" to read current ClockSnapshot).`),fieldId:G().optional().describe(`Target fieldId for entry-save, entry-skip, or choice-select.`),value:se().optional().describe(`Numeric value for entry-save or reps-set.`),occurrenceId:G().optional().describe(`Rep occurrenceId for reps-adjust, reps-set, or reps-select.`),delta:yn([on(1),on(-1)]).optional().describe(`+1 or -1 delta for reps-adjust.`),index:se().int().min(0).optional().describe(`Zero-based alternative index for choice-select.`)}),STe=yi({action:Qt([`get`,`set`]).describe(`Read current Playground UI preferences ("get") or update preferences ("set").`),theme:Qt([`light`,`dark`,`system`]).optional().describe("Color theme preference (`light`, `dark`, or `system`)."),audioEnabled:Gt().optional().describe(`Enable or mute workout timer audio cues.`),debugMode:Gt().optional().describe(`Enable or disable global runtime debug mode.`),analyticsUnit:Qt([`kg`,`lb`]).optional().describe("Preferred display unit for analytics charts (`kg` or `lb`)."),leftDrawerOpen:Gt().optional().describe(`Open or close the primary navigation drawer on mobile/tablet.`),rightDrawerOpen:Gt().optional().describe(`Open or close the secondary L3 context drawer on mobile/tablet.`)}),CTe=yi({query:G().optional().describe('WQL aggregate or find query string to set on the Metric Explorer (`/dashboards`), e.g. "sum:totalVolume{} by {week}".'),submit:Gt().optional().describe("Execute/submit the query immediately (default true when `query` is provided)."),weeks:yn([on(4),on(8),on(16)]).optional().describe("Analytics lookback range in weeks (`4`, `8`, or `16`)."),openSaveDialog:Gt().optional().describe(`Open the "Save to dashboard" dialog for the active query.`),openQuerySettings:Gt().optional().describe("Open the surface query settings dialog on `/dashboards`.")}),wTe=yi({action:Qt([`get_state`,`open_popover`,`close_popover`,`open_drawer`,`close_drawer`,`toggle_drawer`]).describe(`Inspect cursor line tokens & lint fixes, open/close the anchored Option A popover, or toggle the Option B right inspector drawer.`),mode:Qt([`token`,`add`,`block`,`wiki`,`prose-tag`,`query`,`markdown`]).optional().describe(`Optional inspector view mode when opening the popover or drawer.`),tokenIndex:se().int().min(0).optional().describe(`Zero-based index of the token on the current cursor line to target.`)}),TTe=yi({activeTab:Qt([`splits`,`movement`,`compare`,`raw`]).optional().describe(`Switch the active results workbook tab.`),mobileViewMode:Qt([`grid`,`cards`]).optional().describe("Switch the mobile results presentation mode (`grid` or `cards`)."),sourceDrawerOpen:Gt().optional().describe(`Open or close the Pinned Workout Source & History drawer.`),openAddToDashboard:Gt().optional().describe(`Open the 2-step Add to Dashboard promotion sheet for the session.`),closeModals:Gt().optional().describe(`Close any open source drawer or dashboard dialog on the results workbench.`)}),ETe=yi({action:Qt([`status`,`open`,`close`]).describe(`Read active Entity Peek Drawer state ("status"), open a preview for a target entity ("open"), or dismiss it ("close").`),kind:Qt([`effort`,`equipment`,`tag`,`unrecognized`,`note`,`notebook`,`day`]).optional().describe(`Target entity kind when action="open".`),slug:G().optional().describe(`Canonical slug when kind is "effort", "equipment", or "notebook".`),label:G().optional().describe(`Tag label (required when kind="tag") or optional display label for effort/equipment.`),tagType:G().optional().describe(`Optional tag category/type when kind="tag" (e.g. "domain", "format", "general").`),term:G().optional().describe(`Unrecognized term to quick-define when kind="unrecognized".`),noteId:G().optional().describe(`Target Note ID when kind="note".`),title:G().optional().describe(`Optional display title hint when kind is "note" or "notebook".`),date:G().regex(/^\d{4}-\d{2}-\d{2}$/,`Expected YYYY-MM-DD civil date`).optional().describe(`Civil date (YYYY-MM-DD) when kind="day".`)});function DTe(e){switch(e.kind){case`effort`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="effort".`);return{kind:`effort`,slug:e.slug.trim(),...e.label?.trim()?{label:e.label.trim()}:{}};case`equipment`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="equipment".`);return{kind:`equipment`,slug:e.slug.trim(),...e.label?.trim()?{label:e.label.trim()}:{}};case`tag`:if(!e.label?.trim())throw Error(`'label' is required when kind="tag".`);return{kind:`tag`,label:e.label.trim().replace(/^#/,``),...e.tagType?.trim()?{tagType:e.tagType.trim()}:{}};case`unrecognized`:if(!e.term?.trim())throw Error(`'term' is required when kind="unrecognized".`);return{kind:`unrecognized`,term:e.term.trim()};case`note`:if(!e.noteId?.trim())throw Error(`'noteId' is required when kind="note".`);return{kind:`note`,noteId:e.noteId.trim(),...e.title?.trim()?{title:e.title.trim()}:{}};case`notebook`:if(!e.slug?.trim())throw Error(`'slug' is required when kind="notebook".`);return{kind:`notebook`,slug:e.slug.trim(),...e.title?.trim()?{title:e.title.trim()}:{}};case`day`:if(!e.date?.trim())throw Error(`'date' is required when kind="day".`);return{kind:`day`,date:e.date.trim()};default:throw Error(`'kind' is required when action="open".`)}}function OTe(){(0,K.useEffect)(()=>u7({name:`ui_peek_entity`,title:`Inspect, Open, or Close Entity Peek Drawer`,description:`Inspect, open, or close the 340px right-edge Entity Peek Drawer on the live UI.`,tier:1,scope:`editor-ui`}),[]),Or({name:`ui_peek_entity`,title:`Inspect, Open, or Close Entity Peek Drawer`,description:"Read active Entity Peek Drawer state (`status`), open a non-destructive 340px right-edge preview for an effort, equipment, tag, unrecognized term, note, notebook, or day (`open`), or dismiss the drawer (`close`). Mutually exclusive with the Whiteboard Token Inspector drawer.",inputSchema:ETe,annotations:{title:`Inspect or Control Entity Peek Drawer`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=qX(),r=vX();if(e.action===`status`){let r=n?.getTarget()??null,i={ok:!0,open:r!==null,target:r};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}if(e.action===`close`){n?n.closePeek():r?.closePeek&&r.closePeek(),await G9();let i=qX()?.getTarget()??null,a={ok:!0,open:i!==null,target:i};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),a}let i=DTe(e);if(n)try{n.openPeek(i)}catch(e){if(r?.peekEntity)r.peekEntity(i);else throw e}else if(r?.peekEntity)r.peekEntity(i);else throw Error(`No Entity Peek surface is currently mounted.`);await G9();let a=qX()?.getTarget()??i,o={ok:!0,open:a!==null,target:a};return d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_peek_entity`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}})}var kTe=()=>(OTe(),null),ATe=()=>((0,K.useEffect)(()=>{let e=u7({name:`ui_editor_draft`,title:`Read, Edit, or Undo Live Note Editor Buffer`,description:`Inspect or modify the live CodeMirror 6 Note buffer.`,tier:1,scope:`editor-ui`}),t=u7({name:`ui_start_live_workout`,title:`Start Live Interactive Workout Timer`,description:`Start the live interactive workout clock from the active Note editor.`,tier:1,scope:`editor-ui`}),n=u7({name:`ui_editor_inspector`,title:`Inspect or Control Whiteboard Token Inspector & Drawer`,description:`Inspect cursor-line tokens or control the Option A popover and Option B drawer.`,tier:1,scope:`editor-ui`});return()=>{e(),t(),n()}},[]),Or({name:`ui_editor_draft`,title:`Read, Edit, or Undo Live Note Editor Buffer`,description:"Inspect or modify the live CodeMirror 6 Note buffer (`read`, `replace`, `append`, `undo`) with full undo support and optional immediate save (`save: true`).",inputSchema:yTe,annotations:{title:`Edit Live Note Draft`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);if(e.operation===`read`){let e=n.getValue();return{operation:`read`,noteId:n.noteId??null,readonly:n.readonly,sourceRevision:n.sourceRevision??null,content:e,workoutBlockIds:n.getBlocks().map(e=>e.id)}}if(e.operation===`undo`){let e=n.undoEdit();return await G9(),{operation:`undo`,undone:e,content:n.getValue()}}if(!e.content)throw Error(`'content' is required when operation="${e.operation}".`);let r=n.getValue(),i=e.operation===`replace`?L9(e.content):`${r.trimEnd()}\n\n${L9(e.content)}`;await n.applyEdit(i,e.save===!0),await G9();let a=vX()??n,o={operation:e.operation,saved:e.save===!0,noteId:a.noteId??null,sourceRevision:a.sourceRevision??null,workoutBlockIds:a.getBlocks().map(e=>e.id),length:a.getValue().length};return d7({toolName:`ui_editor_draft`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify({operation:e.operation,save:e.save}).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_editor_draft`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify({operation:e.operation}).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),Or({name:`ui_start_live_workout`,title:`Start Live Interactive Workout Timer`,description:"Launch the live interactive workout clock on screen from a workout block in the active Note editor so the human athlete and agent can co-drive the session via `ui_clock_control`.",inputSchema:bTe,annotations:{title:`Start Live Workout Timer`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);let r=await n.startLiveWorkout(e.blockId,e.autoStart??!0);if(!r.started)throw Error(r.error??`Failed to start workout timer.`);let i=Date.now()+1500;for(;!$1()&&Date.now()<i;)await new Promise(e=>setTimeout(e,25));await G9();let a={started:!0,blockId:r.blockId??null,clock:$1()};return d7({toolName:`ui_start_live_workout`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),a}catch(n){throw d7({toolName:`ui_start_live_workout`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),Or({name:`ui_editor_inspector`,title:`Inspect or Control Whiteboard Token Inspector & Drawer`,description:"Read parsed cursor-line tokens and inline lint fixes, open or close the Option A anchored token inspector popover (`Alt+.`), or toggle the Option B right inspector drawer (`Ctrl+Alt+I` / `Cmd+Alt+I`).",inputSchema:wTe,annotations:{title:`Inspect or Control Token Inspector`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=vX();if(!n)throw Error(`No Note editor is currently mounted.`);if(e.action===`open_popover`)n.openTokenInspector?.({mode:e.mode,tokenIndex:e.tokenIndex});else if(e.action===`close_popover`)n.closeTokenInspector?.();else if(e.action===`open_drawer`)n.setInspectorDrawer?.(!0),(e.mode||e.tokenIndex!==void 0)&&n.openTokenInspector?.({mode:e.mode,tokenIndex:e.tokenIndex});else if(e.action===`close_drawer`)n.setInspectorDrawer?.(!1);else if(e.action===`toggle_drawer`){let e=n.getInspectorState?.()?.drawerOpen??!1;n.setInspectorDrawer?.(!e)}await G9();let r={ok:!0,inspector:n.getInspectorState?.()??null};return d7({toolName:`ui_editor_inspector`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),r}catch(n){throw d7({toolName:`ui_editor_inspector`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),jTe=()=>((0,K.useEffect)(()=>u7({name:`ui_set_explorer_query`,title:`Set or Run Analytics Explorer WQL Query`,description:`Update or run WQL queries, week windows, or dialogs on the Metric Explorer (/dashboards).`,tier:1,scope:`explorer-ui`}),[]),Or({name:`ui_set_explorer_query`,title:`Set or Run Analytics Explorer WQL Query`,description:"Set or execute an aggregate or find WQL query on the Metric Explorer (`/dashboards`), change the week window (`4`, `8`, `16`), or open the Save-to-Dashboard / Query Settings dialogs.",inputSchema:CTe,annotations:{title:`Set Analytics Explorer Query`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=AX();if(!n)throw Error(`Metric Explorer (/dashboards) is not currently mounted.`);e.weeks!==void 0&&n.setWeeks(e.weeks),e.query===void 0?e.submit===!0&&n.submit():(n.setDraft(e.query),e.submit!==!1&&n.submit(e.query)),e.openSaveDialog&&n.openSaveDialog(),e.openQuerySettings&&n.openQuerySettings(),await K9();let r=AX()??n,i={draft:r.draft,submitted:r.submitted,weeks:r.weeks,saveReady:r.saveReady,loading:r.loading};return d7({toolName:`ui_set_explorer_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}catch(n){throw d7({toolName:`ui_set_explorer_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),MTe=()=>((0,K.useEffect)(()=>u7({name:`ui_clock_control`,title:`Control Live Workout Clock`,description:`Dispatch live clock commands to the active workout timer.`,tier:1,scope:`clock-ui`}),[]),Or({name:`ui_clock_control`,title:`Control Live Workout Clock`,description:"Inspect or dispatch commands (`next`, `playback`, `ready-start`, `entry-save`, `entry-skip`, `reps-adjust`, `reps-set`, `choice-select`, `stop-request`, `stop-confirm`, `dismiss`) to the active on-screen workout clock.",inputSchema:xTe,annotations:{title:`Control Live Workout Clock`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},async execute(e,t){let n=performance.now();try{let r=$1();if(!r)throw Error(`No live workout clock is currently mounted.`);if(e.command===`status`)return{accepted:!0,snapshot:r};if(e.command===`stop-confirm`){if(!await M9({action:`ui_clock_control:stop-confirm`,targetId:r.runId,summary:`Stop and end the active live workout timer early`},t))throw Error(`User declined early termination of the active workout timer.`);r.stopRequested||(t0(r.runId,{kind:`stop-request`}),await G9())}let i;switch(e.command){case`entry-save`:{let t=e.fieldId??r.entry?.fieldId;if(!t||typeof e.value!=`number`)throw Error("`entry-save` requires `value` (number) and an active or explicit `fieldId`.");i={kind:`entry-save`,fieldId:t,value:e.value};break}case`entry-skip`:{let t=e.fieldId??r.entry?.fieldId;if(!t)throw Error("`entry-skip` requires `fieldId`.");i={kind:`entry-skip`,fieldId:t};break}case`reps-adjust`:{let t=e.occurrenceId??r.selectedOccurrenceId??r.reps[0]?.occurrenceId;if(!t||e.delta!==1&&e.delta!==-1)throw Error("`reps-adjust` requires `occurrenceId` and `delta` (+1 or -1).");i={kind:`reps-adjust`,occurrenceId:t,delta:e.delta};break}case`reps-set`:{let t=e.occurrenceId??r.selectedOccurrenceId??r.reps[0]?.occurrenceId;if(!t||typeof e.value!=`number`)throw Error("`reps-set` requires `occurrenceId` and integer `value`.");i={kind:`reps-set`,occurrenceId:t,value:e.value};break}case`reps-select`:if(!e.occurrenceId)throw Error("`reps-select` requires `occurrenceId`.");i={kind:`reps-select`,occurrenceId:e.occurrenceId};break;case`choice-select`:{let t=e.fieldId??r.entry?.fieldId;if(!t||typeof e.index!=`number`)throw Error("`choice-select` requires `fieldId` and `index`.");i={kind:`choice-select`,fieldId:t,index:e.index};break}default:i={kind:e.command}}let a=t0(($1()??r).runId,i);await G9();let o={accepted:a,command:e.command,snapshot:$1()};return d7({toolName:`ui_clock_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(t){throw d7({toolName:`ui_clock_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:t instanceof Error?t.message:String(t)}),t}}}),null),q9=()=>((0,K.useEffect)(()=>u7({name:`ui_results_control`,title:`Control Session Results Workbench`,description:"Switch tabs, toggle mobile grid/cards layout, open/close Source & History drawer, or open the Add-to-Dashboard sheet on `/results/:sessionId`.",tier:1,scope:`results-ui`}),[]),Or({name:`ui_results_control`,title:`Control Session Results Workbench`,description:"Control the mounted `/results/:sessionId` workbench (`activeTab`: splits|movement|compare|raw, `mobileViewMode`: grid|cards, `sourceDrawerOpen`, `openAddToDashboard`, `closeModals`).",inputSchema:TTe,annotations:{title:`Control Session Results Workbench`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=IX();if(!n)throw Error(`No session results workbench is currently mounted.`);e.closeModals&&n.closeModals(),e.activeTab!==void 0&&n.setTab(e.activeTab),e.mobileViewMode!==void 0&&n.setMobileViewMode(e.mobileViewMode),e.sourceDrawerOpen!==void 0&&n.openSourceDrawer(e.sourceDrawerOpen),e.openAddToDashboard&&n.openAddToDashboard(),await G9();let r=IX()??n,i={resultId:r.resultId,activeTab:r.activeTab,mobileViewMode:r.mobileViewMode,sourceDrawerOpen:r.sourceDrawerOpen,addToDashboardOpen:r.addToDashboardOpen};return d7({toolName:`ui_results_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}catch(n){throw d7({toolName:`ui_results_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),NTe=()=>((0,K.useEffect)(()=>u7({name:`ui_set_stream_query`,title:`Set Live Stream WQL Query or Layout`,description:`Update live WQL query, layout, grouping, calendar month, or overlay filter on the mounted stream view.`,tier:1,scope:`stream-ui`}),[]),Or({name:`ui_set_stream_query`,title:`Set Live Stream WQL Query or Layout`,description:"Update the live WQL query, layout (`cards`, `rows`, `feed`, `agenda`, `planner`), grouping, calendar `month` (`YYYY-MM`), or calendar `overlayMode` (`all`, `planned`, `logged`) on the currently mounted stream view, or pass `resetToDefault: true` to restore the route default query.",inputSchema:vTe,annotations:{title:`Set Live Stream Query`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now();try{let n=wX();if(!n)throw Error(`No stream view is currently mounted.`);e.resetToDefault?n.setQuery(n.defaultQuery):e.query!==void 0&&n.setQuery(e.query),e.layout!==void 0&&n.setLayout(e.layout),e.groupBy!==void 0&&n.setGroupBy(e.groupBy===null?void 0:e.groupBy),e.month!==void 0&&n.setMonth?.(e.month),e.overlayMode!==void 0&&n.setOverlayMode?.(e.overlayMode),await K9();let r=wX()??n,i=document.getElementById(`agent-view-state`)?.textContent,a=i?JSON.parse(i):null,o={route:r.route,query:r.query,layout:r.layout,groupBy:r.groupBy??null,month:r.month??null,overlayMode:r.overlayMode??null,totalUnbatchedCount:a?.stream?.totalUnbatchedCount??null};return d7({toolName:`ui_set_stream_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),o}catch(n){throw d7({toolName:`ui_set_stream_query`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!1,argsPreview:JSON.stringify(e).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),PTe=pee({allow:(e,t)=>!e.confirm||M9({action:`ui.${e.action}`,targetId:String(e.ref),summary:e.confirm},t)}),J9=Symbol(`wodWrappedExecuteTool`);function Y9(e){return typeof e!=`object`||!e?!1:`name`in e&&typeof e.name==`string`&&`origin`in e&&typeof e.origin==`string`&&`window`in e&&typeof e.window==`object`}function FTe(e){return typeof e==`object`&&!!e&&`name`in e}function ITe(e){let t=e.arguments??e.input??e.params??e.args;if(typeof t==`string`)try{return JSON.parse(t)}catch{return{}}return t??{}}function X9(e,t){let n=t??{};if(e===`ui_navigate`&&typeof n.path!=`string`&&typeof n.href==`string`){let e=n.href.trim();if(/^https?:\/\//i.test(e))try{let t=new URL(e);e=`${t.pathname}${t.search}${t.hash}`||`/`}catch{}return{...n,path:e}}return n}async function Z9(e,t,n){if(typeof t==`string`){let n=(await e()).find(e=>Y9(e)&&e.name===t);if(n)return n}if(Y9(n))return n;throw Error(typeof t==`string`?`executeTool: no registered tool named "${t}"`:`executeTool: expected a registered tool descriptor or a { name, arguments } envelope`)}function Q9(e){if(typeof e!=`object`||!e)return;let t=e,n=t.executeTool;if(typeof n!=`function`)return;let r;if(n[J9])r=n;else{let e=async()=>typeof t.getTools==`function`?t.getTools():typeof t.listTools==`function`?t.listTools():[],i=async(...r)=>{let[i,a]=r;if(r.length>=2&&Y9(i))return n.call(t,i,X9(i.name,a),r[2]);if(typeof i==`string`){let o=await Z9(e,i,void 0);return n.call(t,o,X9(i,a??{}),r[2])}if(FTe(i)){let r=X9(i.name,ITe(i)),a=await Z9(e,i.name,i);return n.call(t,a,r)}return n.apply(t,r)};i[J9]=!0,Object.defineProperty(t,"executeTool",{configurable:!0,writable:!0,value:i}),r=i}if(typeof t.callTool!=`function`||!t.callTool[J9]){let e=async(...e)=>r.apply(t,e);e[J9]=!0,Object.defineProperty(t,"callTool",{configurable:!0,writable:!0,value:e})}}var LTe=({spec:e})=>((0,K.useEffect)(()=>u7({name:e.name,title:e.title,description:e.description,tier:e.tier,scope:`domain`}),[e]),Or({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,annotations:e.annotations,async execute(t,n){let r=performance.now(),i={storage:X.storage,baseUrl:typeof window<`u`?window.location.origin:``,feedLifecycle:{subscribe:async(e,t)=>{if(t?.notebookIds?.length){VI(e,!0);for(let n of t.notebookIds)UI(e,n,!0);await JF()}let n=t?.notebookIds?.length?await sV(e,{notebookIds:t.notebookIds,preserveSubscriptionState:!0}):await cV(e,{offlinePolicy:e===`core`?`offline-full`:`index-only`});return{sourceId:e,subscribed:!0,notebookIds:t?.notebookIds??null,synced:n!==`error`}},unsubscribe:async e=>{let{deleted:t}=await dV(e);return{sourceId:e,unsubscribed:!0,deletedNotes:t}},delete:async e=>{let{deleted:t}=await fV(e);return{sourceId:e,deleted:!0,deletedNotes:t}}},confirmDestructive:e=>M9(e,n),onMutated:async()=>{BP(),await Xq().catch(()=>{})}};try{let n=await e.execute(t,i);return await G9(),d7({toolName:e.name,timestamp:Date.now(),durationMs:Math.round(performance.now()-r),ok:!0,argsPreview:JSON.stringify(t??{}).slice(0,120)}),n}catch(n){throw d7({toolName:e.name,timestamp:Date.now(),durationMs:Math.round(performance.now()-r),ok:!1,argsPreview:JSON.stringify(t??{}).slice(0,120),error:n instanceof Error?n.message:String(n)}),n}}}),null),RTe=()=>{let e=dt(),t=Qe(),n=RZ(),r=zZ(),i=tZ(),a=EX(),o=MX(),s=RW(),c=bX(),l=YX(),u=RX(),d=(0,K.useSyncExternalStore)(e0,$1,()=>null),{theme:f,setTheme:p}=So(),m=kB(),{isDebugMode:h,toggleDebugMode:g}=Ew(),{unit:_,setUnit:v}=fk(typeof window<`u`?window.localStorage:void 0),{navState:y,dispatch:b}=NV();return(0,K.useEffect)(()=>{if(typeof navigator<`u`&&typeof document<`u`){let e=document,t=navigator;if(e.modelContext&&!t.modelContext)try{Object.defineProperty(navigator,"modelContext",{configurable:!0,enumerable:!0,get:()=>e.modelContext})}catch{}let n=e.modelContext,r=t.modelContext;Q9(n),r!==n&&Q9(r);let i=navigator;if((r||n)&&!i.modelContextTesting)try{Object.defineProperty(navigator,"modelContextTesting",{configurable:!0,enumerable:!0,value:{listTools:async()=>{let e=i.modelContext;return e&&typeof e.listTools==`function`?e.listTools():e&&typeof e.getTools==`function`?e.getTools():[]},executeTool:async(...e)=>{let t=i.modelContext;if(!t||typeof t.executeTool!=`function`)throw Error(`navigator.modelContext.executeTool is unavailable`);return t.executeTool(...e)},callTool:async(...e)=>{let t=i.modelContext;if(t&&typeof t.callTool==`function`)return t.callTool(...e);if(t&&typeof t.executeTool==`function`)return t.executeTool(...e);throw Error(`navigator.modelContext.callTool is unavailable`)}}})}catch{}let a=Si(PTe,{allow:()=>!0});return()=>{a()}}},[]),(0,K.useEffect)(()=>{let e=u7({name:`ui_get_view_context`,title:`Get Active UI View Context`,description:`Read current browser route, readiness, stream results, editor, and clock.`,tier:0,scope:`global-ui`}),t=u7({name:`ui_navigate`,title:`Navigate Playground Route`,description:`Navigate the SPA router to any internal WOD Wiki path.`,tier:1,scope:`global-ui`}),n=u7({name:`ui_cast_control`,title:`Inspect or Disconnect Cast Session`,description:`Inspect or disconnect Chromecast / receiver display session.`,tier:1,scope:`global-ui`}),r=u7({name:`ui_preferences`,title:`Get or Set Playground UI Preferences`,description:`Read or update theme, audio cues, debug mode, analytics units, and mobile drawers.`,tier:1,scope:`global-ui`}),i=Ii.map(e=>u7({name:e.name,title:`UI-SDK ${e.name[0].toUpperCase()}${e.name.slice(1)}`,description:e.description,tier:+(e.name===`act`),scope:`global-ui`}));return()=>{e(),t(),n(),r();for(let e of i)e()}},[]),Or({name:`ui_get_view_context`,title:`Get Active UI View Context`,description:`Read the current browser route, hydration/loading state, unbatched stream results, active editor metadata, and live workout clock snapshot.`,inputSchema:hTe,annotations:{title:`Get Active UI View Context`,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let l=performance.now(),u=e.includeSampleEntries!==!1,p=a&&s&&s.pathname===t.pathname?s:null,g={hydrated:document.body.dataset.appHydrated===`true`,status:i||n===`preparing`||r?`loading`:`ready`,feedReadiness:n,importPending:r,route:{pathname:t.pathname,search:t.search,hash:t.hash,href:window.location.href},stream:a?{route:a.route,query:a.query,defaultQuery:a.defaultQuery,layout:a.layout,availableLayouts:a.availableLayouts,groupBy:a.groupBy??null,loading:a.loading,totalUnbatchedCount:p?p.entries.length:null,...u&&p?{entries:p.entries.slice(0,50).map(e=>({id:e.id,title:e.title,date:e.date??null,notebookId:e.notebookId??null}))}:{}}:null,editor:c?{noteId:c.noteId??null,readonly:c.readonly,sourceRevision:c.sourceRevision??null,workoutBlockIds:c.getBlocks().map(e=>e.id)}:null,explorer:o?{draft:o.draft,submitted:o.submitted,weeks:o.weeks,loading:o.loading,saveReady:o.saveReady}:null,preferences:{theme:f,audioEnabled:m?.isEnabled??!1,debugMode:h,analyticsUnit:_,leftDrawerOpen:y.leftDrawerOpen,rightDrawerOpen:y.rightDrawerOpen},clock:d};return d7({toolName:`ui_get_view_context`,timestamp:Date.now(),durationMs:Math.round(performance.now()-l),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),g}}),Or({name:`ui_navigate`,title:`Navigate Playground Route`,description:"Navigate the React Router SPA to any WOD Wiki route (`/journal`, `/day/:date`, `/note/:id`, `/notebooks`, `/dashboards`, `/run/:id?note=:noteId`) and wait for UI commit.",inputSchema:gTe,annotations:{title:`Navigate Route`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(t){let n=performance.now(),r=t.path.startsWith(`/`)?t.path:`/${t.path}`;e(r,{replace:t.replace===!0}),await G9();let i={navigatedTo:r,href:window.location.href};return d7({toolName:`ui_navigate`,timestamp:Date.now(),durationMs:Math.round(performance.now()-n),ok:!0,argsPreview:JSON.stringify(t).slice(0,120)}),i}}),Or({name:`ui_cast_control`,title:`Inspect or Disconnect Cast Session`,description:`Check active Chromecast / receiver display session state or cleanly disconnect an active Cast session.`,inputSchema:_Te,annotations:{title:`Cast Session Control`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now(),n=V1(),r=U1.getActiveHandle();e.action===`disconnect`&&r&&(U1.dispose(!0),yB(null),await G9());let i={action:e.action,backendState:n.state,connected:!!U1.getActiveHandle()};return d7({toolName:`ui_cast_control`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),i}}),Or({name:`ui_preferences`,title:`Get or Set Playground UI Preferences`,description:"Read or update global Playground UI preferences (`theme`, `audioEnabled`, `debugMode`, `analyticsUnit`, and mobile navigation drawers).",inputSchema:STe,annotations:{title:`Playground UI Preferences`,readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async execute(e){let t=performance.now(),n=f,r=m?.isEnabled??!1,i=h,a=_,o=y.leftDrawerOpen,s=y.rightDrawerOpen;e.action===`set`&&(e.theme!==void 0&&e.theme!==f&&(p(e.theme),n=e.theme),e.audioEnabled!==void 0&&m&&e.audioEnabled!==m.isEnabled&&(m.toggleAudio(),r=e.audioEnabled),e.debugMode!==void 0&&e.debugMode!==h&&(g(),i=e.debugMode),e.analyticsUnit!==void 0&&e.analyticsUnit!==_&&(v(e.analyticsUnit),a=e.analyticsUnit),e.leftDrawerOpen!==void 0&&(b({type:`SET_LEFT_DRAWER`,open:e.leftDrawerOpen}),o=e.leftDrawerOpen),e.rightDrawerOpen!==void 0&&(b({type:`SET_RIGHT_DRAWER`,open:e.rightDrawerOpen}),s=e.rightDrawerOpen),await G9());let c={theme:n,audioEnabled:r,debugMode:i,analyticsUnit:a,leftDrawerOpen:o,rightDrawerOpen:s};return d7({toolName:`ui_preferences`,timestamp:Date.now(),durationMs:Math.round(performance.now()-t),ok:!0,argsPreview:JSON.stringify(e).slice(0,120)}),c}}),(0,q.jsxs)(q.Fragment,{children:[W9.map(e=>(0,q.jsx)(LTe,{spec:e},e.name)),a&&(0,q.jsx)(NTe,{stream:a}),o&&(0,q.jsx)(jTe,{explorer:o}),c&&(0,q.jsx)(ATe,{editor:c}),(l||c)&&(0,q.jsx)(kTe,{}),u&&(0,q.jsx)(q9,{results:u}),d&&(0,q.jsx)(MTe,{clock:d})]})};function zTe(){let{pathname:e,hash:t}=Qe(),{scrollToSection:n}=NV();return(0,K.useLayoutEffect)(()=>{if(SK(e),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 BTe(){return Vwe(),S9(),(0,K.useEffect)(()=>{qP.current().catch(console.error),Ule(),HZ(),wz().catch(()=>{}),V5().catch(()=>{})},[]),null}function $9({settling:e}){let t=BZ();if(e){let e=rZ(t);return(0,q.jsxs)(`div`,{role:`status`,className:`flex min-h-dvh flex-col items-center justify-center gap-2 text-muted-foreground`,children:[(0,q.jsx)(`span`,{children:t?nZ(t):`Loading library…`}),e&&(0,q.jsx)(`span`,{className:`text-xs`,"data-testid":`boot-progress-detail`,children:e})]})}return(0,q.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The feed corpus has not supplied this page. Re-running the feed import usually restores it.`}),(0,q.jsx)(J,{variant:`outline`,size:`sm`,"data-testid":`root-refeed`,onClick:()=>{iV().then(()=>BP())},children:`Re-import library`})]})}function VTe(){let e=(0,K.useRef)(()=>{}),t=Oq(),n=RZ(),r=(0,K.useMemo)(()=>ZK(()=>e.current(),t),[t]);return(0,q.jsx)(Xee,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,q.jsx)(Tw,{children:(0,q.jsx)(xV,{children:(0,q.jsx)(TV,{children:(0,q.jsx)(EB,{children:(0,q.jsx)(R,{children:(0,q.jsxs)(Rt,{children:[(0,q.jsx)(BTe,{}),(0,q.jsx)(ite,{}),(0,q.jsxs)(RV,{tree:r,children:[(0,q.jsx)(zTe,{}),(0,q.jsx)(RTe,{}),(0,q.jsx)(Uwe,{}),(0,q.jsx)(Gwe,{}),(0,q.jsx)(zwe,{searchHandlerRef:e,canvasRouteList:t,rootUnavailable:t.length===0?(0,q.jsx)($9,{settling:n===`preparing`||VB()&&n!==`error`}):void 0,pageSettlingFallback:t.length===0&&(n===`preparing`||VB()&&n!==`error`)?(0,q.jsx)($9,{settling:!0}):void 0}),(0,q.jsx)(Bwe,{})]})]})})})})})})})}function HTe({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e);return KP(),(0,q.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,q.jsx)(`p`,{className:`text-sm font-semibold`,children:`The API data store could not be opened.`}),(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,q.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.`,!1]}),(0,q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,q.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`}),!1]}),!1]})}function UTe(){let e=(0,K.useSyncExternalStore)(jE,AE),t=e.phase===`updating`;return(0,q.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,q.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,q.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var WTe=(0,bo.createRoot)(document.getElementById(`root`));function GTe(){let[e,t]=(0,K.useState)(!1),[n,r]=(0,K.useState)(null),[i,a]=(0,K.useState)(0),o=(0,K.useSyncExternalStore)(jE,AE);return(0,K.useEffect)(()=>{let e=!1,n;return ZP().then(()=>ZF(X.storage)).then(()=>FR?BR():void 0).then(()=>jI.ensureNotebooks().catch(e=>dR(`NotebookService`,`ensureNotebooks failed`,e))).then(()=>ER().catch(e=>dR(`resultRecorder`,`boot unload flush failed`,e))).then(()=>{e||(n=eF(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),(0,K.useEffect)(()=>{if(!e){delete document.body.dataset.appHydrated;return}return document.body.dataset.appHydrated=`true`,()=>{delete document.body.dataset.appHydrated}},[e]),n?(0,q.jsx)(HTe,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,q.jsx)(UTe,{}):e?(0,q.jsx)(VTe,{}):(0,q.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Opening local library…`})}WTe.render((0,q.jsx)(K.StrictMode,{children:(0,q.jsx)(GTe,{})}));
|
|
1203
|
+
//# sourceMappingURL=main-COJt7UId.js.map
|