@bitcobblers/wod-wiki-tools 0.41.2146 → 0.42.2147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/bin/wod.cjs +1 -1
  2. package/dist/bin/wod.cjs.map +1 -1
  3. package/dist/bin/wod.mjs +2 -2
  4. package/dist/{chunk-X6QPURH2.mjs → chunk-AVU5FAUG.mjs} +4 -4
  5. package/dist/{chunk-X6QPURH2.mjs.map → chunk-AVU5FAUG.mjs.map} +1 -1
  6. package/dist/{chunk-DE4Q2F7R.mjs → chunk-TKKEYIGO.mjs} +3 -3
  7. package/dist/chunk-TKKEYIGO.mjs.map +1 -0
  8. package/dist/index.cjs +1 -1
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.mjs +2 -2
  11. package/dist/{scaffoldCatalog-SEDEF7DP.mjs → scaffoldCatalog-D37HXUUT.mjs} +3 -3
  12. package/dist/{scaffoldCatalog-SEDEF7DP.mjs.map → scaffoldCatalog-D37HXUUT.mjs.map} +1 -1
  13. package/dist/web/playground/assets/main-Ct4mjCft.js +206 -0
  14. package/dist/web/playground/assets/main-vBlbZKmX.css +2 -0
  15. package/dist/web/playground/assets/{statementBuilderFlow-BTfJbJ1N.js → statementBuilderFlow-BZytUeqo.js} +2 -2
  16. package/dist/web/playground/index.html +2 -2
  17. package/dist/web/playground/seed/core/chunks/{canvas.f1fc1b8a.json → canvas.9fedd32d.json} +1 -1
  18. package/dist/web/playground/seed/core/chunks/{efforts.9bb037d9.json → efforts.d89473f5.json} +1 -1
  19. package/dist/web/playground/seed/core/manifest.json +7 -7
  20. package/dist/web/playground/seed/core/report.html +11 -11
  21. package/dist/web/server/assets/{main-CCnQ9nH-.js → main-CqewmQAx.js} +48 -36
  22. package/dist/web/server/assets/main-vBlbZKmX.css +2 -0
  23. package/dist/web/server/assets/{statementBuilderFlow-BIBCbahc.js → statementBuilderFlow-D6p7_NoH.js} +2 -2
  24. package/dist/web/server/index.html +2 -2
  25. package/dist/web/server/seed/core/chunks/{canvas.f1fc1b8a.json → canvas.9fedd32d.json} +1 -1
  26. package/dist/web/server/seed/core/chunks/{efforts.9bb037d9.json → efforts.d89473f5.json} +1 -1
  27. package/dist/web/server/seed/core/manifest.json +7 -7
  28. package/dist/web/server/seed/core/report.html +11 -11
  29. package/package.json +6 -6
  30. package/dist/chunk-DE4Q2F7R.mjs.map +0 -1
  31. package/dist/web/playground/assets/main-CVrXfYFg.css +0 -2
  32. package/dist/web/playground/assets/main-mBMAP-SO.js +0 -194
  33. package/dist/web/server/assets/main-CVrXfYFg.css +0 -2
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-DEqYb4q_.js","assets/rolldown-runtime-C0FnF6B9.js","assets/statementBuilderFlow-BIBCbahc.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-DEqYb4q_.js","assets/rolldown-runtime-C0FnF6B9.js","assets/statementBuilderFlow-D6p7_NoH.js"])))=>i.map(i=>d[i]);
2
2
  import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{$ as n,$n as r,$r as i,$t as a,A as o,An as s,Ar as c,B as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Cr as h,D as g,Dn as _,Dr as v,Dt as y,E as b,En as x,Er as S,Et as C,F as w,Fn as T,Fr as E,Ft as D,G as O,Gn as k,Gr as A,Gt as j,H as M,Hn as N,Hr as P,Ht as F,I,In as ee,Ir as te,It as ne,J as re,Jn as ie,Jr as ae,Jt as oe,K as se,Kn as ce,Kr as L,Kt as le,L as ue,Ln as R,Lr as de,Lt as fe,M as pe,Mn as me,Mr as he,N as ge,Nn as _e,Nr as ve,O as ye,On as be,Or as xe,P as Se,Pn as Ce,Pr as we,Pt as Te,Q as Ee,Qn as De,Qr as Oe,Qt as ke,R as Ae,Rn as je,Rr as Me,Rt as Ne,S as Pe,Sn as Fe,Sr as Ie,St as Le,T as Re,Tn as ze,U as Be,Un as Ve,Ur as He,Ut as Ue,V as We,Vn as Ge,Vr as Ke,Vt as qe,W as Je,Wn as Ye,Wr as Xe,Wt as Ze,X as Qe,Xr as $e,Xt as et,Y as tt,Yn as nt,Yr as rt,Yt as it,Z as at,Zn as ot,Zr as st,Zt as ct,_ as lt,_n as ut,_r as dt,_t as ft,a as pt,ai as mt,an as ht,ar as gt,at as _t,b as vt,bn as yt,br as bt,bt as xt,c as St,ci as Ct,cn as wt,cr as Tt,ct as Et,d as Dt,di as Ot,dn as kt,dr as At,dt as jt,ei as Mt,en as Nt,er as Pt,et as Ft,f as It,fi as Lt,fn as Rt,fr as zt,ft as Bt,g as Vt,gn as Ht,gr as Ut,gt as Wt,h as Gt,hn as Kt,hr as qt,ht as Jt,i as Yt,ii as Xt,in as Zt,ir as Qt,it as $t,j as en,jn as tn,jr as nn,k as rn,kn as an,kr as on,l as sn,li as cn,ln,lr as un,lt as dn,m as fn,mn as pn,mr as mn,mt as hn,n as gn,ni as _n,nn as vn,nr as yn,nt as bn,o as xn,oi as Sn,on as Cn,or as wn,ot as Tn,p as En,pn as Dn,pr as On,pt as kn,q as An,qn as jn,qr as Mn,qt as Nn,r as Pn,ri as z,rn as Fn,rr as In,rt as Ln,s as Rn,si as zn,sn as Bn,sr as Vn,st as Hn,t as Un,ti as Wn,tn as Gn,tr as Kn,tt as qn,u as Jn,ui as Yn,un as Xn,ur as Zn,ut as Qn,v as $n,vn as er,vr as tr,vt as nr,w as rr,wn as ir,wr as ar,wt as or,x as sr,xn as cr,xr as lr,xt as ur,y as dr,yn as fr,yr as pr,yt as mr,z as hr,zn as gr,zr as _r,zt as vr}from"./vendor-DEqYb4q_.js";import{$ as yr,A as br,B,C as xr,D as Sr,E as Cr,F as wr,G as Tr,H as Er,I as Dr,J as Or,K as kr,L as Ar,M as jr,N as Mr,O as Nr,P as Pr,Q as Fr,R as Ir,S as Lr,T as Rr,U as zr,V as Br,W as Vr,X as Hr,Y as Ur,Z as Wr,_ as Gr,a as Kr,at as qr,b as Jr,c as Yr,ct as Xr,d as Zr,et as Qr,f as $r,g as ei,h as ti,i as ni,it as ri,j as ii,k as ai,l as oi,lt as si,m as ci,n as li,nt as ui,o as di,ot as fi,p as pi,q as mi,r as hi,rt as gi,s as _i,st as vi,t as yi,tt as bi,u as xi,ut as Si,v as Ci,w as wi,x as Ti,y as Ei,z as Di}from"./vendor-codemirror-Cfqm6RaY.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Oi=Yn(),V=e(Lt(),1),H=Oe(),ki=(0,V.createContext)({theme:`system`,setTheme:()=>null});function Ai({children:e,defaultTheme:t=`system`,storageKey:n=`vite-ui-theme`}){let[r,i]=(0,V.useState)(()=>localStorage.getItem(n)||t);(0,V.useEffect)(()=>{let e=window.document.documentElement,t=()=>{if(e.classList.remove(`light`,`dark`),r===`system`){let t=window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;e.classList.add(t);return}e.classList.add(r)};if(t(),r===`system`){let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>t();return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)}},[r]);let a=(0,V.useCallback)(e=>{localStorage.setItem(n,e),i(e)},[n]),o=(0,V.useMemo)(()=>({theme:r,setTheme:a}),[r,a]);return(0,H.jsx)(ki.Provider,{value:o,children:e})}var ji=()=>{let e=(0,V.useContext)(ki);if(e===void 0)throw Error(`useTheme must be used within a ThemeProvider`);return e};function U(...e){return v(st(e))}function Mi(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t&=t}return Math.abs(t)}var Ni=xe(`inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-input bg-background hover:bg-accent hover:text-accent-foreground`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-10 px-4 py-2`,sm:`h-9 rounded-md px-3`,lg:`h-11 rounded-md px-8`,icon:`h-10 w-10`}},defaultVariants:{variant:`default`,size:`default`}}),W=V.memo(V.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...i},a)=>{let o=r?on:`button`;return(0,H.jsx)($e,{as:o,className:U(Ni({variant:t,size:n,className:e})),ref:a,...i})}));W.displayName=`Button`;var Pi=[`parser`,`dialect`,`user-plan`,`runtime`,`user-entry`],Fi={parser:`parser`,compiler:`dialect`,dialect:`dialect`,hinted:`dialect`,"user-plan":`user-plan`,runtime:`runtime`,tracked:`runtime`,analyzed:`runtime`,"analyzed-estimated":`runtime`,execution:`runtime`,user:`user-entry`,collected:`user-entry`};function Ii(e){return Fi[e??`parser`]??`parser`}var G=function(e){return e.Duration=`duration`,e.Spans=`spans`,e.SystemTime=`system-time`,e.Time=`time`,e.Elapsed=`elapsed`,e.Total=`total`,e.Rep=`rep`,e.Effort=`effort`,e.Equipment=`equipment`,e.Distance=`distance`,e.Rounds=`rounds`,e.CurrentRound=`current-round`,e.Action=`action`,e.Increment=`increment`,e.Group=`group`,e.Text=`text`,e.Resistance=`resistance`,e.Sound=`sound`,e.System=`system`,e.Label=`label`,e.Lap=`lap`,e.Metric=`metric`,e.Hint=`hint`,e.Custom=`custom`,e.Volume=`volume`,e.Intensity=`intensity`,e.Grade=`grade`,e.Load=`load`,e.Work=`work`,e.RIR=`rir`,e.SessionRPE=`session-rpe`,e.SessionLoad=`session-load`,e.METScore=`met-score`,e.TIS=`tis`,e.Calculated=`calculated`,e.Choice=`choice`,e}({}),Li={parser:0,dialect:1,"user-plan":2,runtime:3,"user-entry":4};function Ri(e){return e.ownershipLayer??Ii(e.origin)}function zi(e){return Li[Ri(e)]??0}function Bi(e){return e.map((e,t)=>{let n=Ri(e);return{metric:e,type:e.type,layer:n,layerRank:Li[n]??0,index:t,isSuppressor:e.action===`suppress`}})}function Vi(e,t){return t?e.filter(e=>!(t.types&&!t.types.includes(e.type)||t.layers&&!t.layers.includes(e.layer))):[...e]}function Hi(e){let t=new Map;for(let n of e){let e=t.get(n.type);if(e){e.push(n);continue}t.set(n.type,[n])}return t}function Ui(e){let t;for(let n of e)n.isSuppressor||(t==null||n.layerRank>t)&&(t=n.layerRank);return t}function Wi(e,t){return{metric:e.metric,type:e.type,layer:e.layer,outcome:t}}function Gi(e,t){return e.index-t.index}function Ki(e){let t=Bi(e);return{raw(e){return Vi(t,e).map(e=>e.metric)},visible(e){let n=Hi(Vi(t,e)),r=[];for(let e of n.values()){if(e.some(e=>e.isSuppressor))continue;let t=Ui(e);if(t!=null)for(let n of e)!n.isSuppressor&&n.layerRank===t&&r.push(n)}return r.sort(Gi),r.map(e=>e.metric)},byLayer(e){let n=Vi(t,e),r={};for(let e of Pi)r[e]=[];for(let e of n)r[e.layer].push(e.metric);for(let e of Pi)r[e]?.length===0&&delete r[e];return r},promotionCandidates(e){let n=Hi(Vi(t,e)),r=[];for(let e of n.values()){let t=e.filter(e=>e.isSuppressor),n=e.filter(e=>!e.isSuppressor);if(n.length===0)continue;if(t.length>0){let e=Math.max(...n.map(e=>e.layerRank)),i=Math.max(...t.map(e=>e.layerRank));for(let t of n)t.layerRank===e&&r.push({metric:t.metric,type:t.type,layer:t.layer,reason:`suppressed`,blockedByLayer:Pi[i]});continue}let i=Ui(n);if(i==null)continue;let a=n.filter(e=>e.layerRank<i);if(a.length===0)continue;let o=Math.max(...a.map(e=>e.layerRank));for(let e of a)e.layerRank===o&&r.push({metric:e.metric,type:e.type,layer:e.layer,reason:`shadowed-by-higher-layer`,blockedByLayer:Pi[i]})}return r.sort((e,t)=>{let n=(Li[t.layer]??0)-(Li[e.layer]??0);return n===0?0:n}),r},explain(e){let n=Hi(Vi(t,e)),r=[];for(let[e,t]of n.entries()){let n=t.some(e=>e.isSuppressor),i=n?void 0:Ui(t),a=t.map(e=>e.isSuppressor?Wi(e,`suppressor`):n?Wi(e,`hidden-by-suppressor`):i!=null&&e.layerRank===i?Wi(e,`visible`):Wi(e,`hidden-by-layer`));r.push({type:e,winnerLayer:i==null?void 0:Pi[i],suppressed:n,entries:a})}return r}}}function qi(e,t){let n=[...e];return(t?.types?.includes(G.Hint)??!1)||(n=n.filter(e=>e.type!==G.Hint)),t?(t.origins&&(n=n.filter(e=>t.origins.includes(e.origin??`parser`))),t.types&&(n=n.filter(e=>t.types.includes(e.type))),t.excludeTypes&&(n=n.filter(e=>!t.excludeTypes.includes(e.type))),n):n}var Ji=class{resolve(e,t){return Ki(qi(e,t)).visible()}resolveOne(e,t){return this.resolve(e,{types:[t]})[0]}resolveAll(e,t){let n=e.filter(e=>e.type===t);return n.length<=1?n:[...n].sort((e,t)=>zi(t)-zi(e))}};function Yi(e){let t=e.split(/[\s_\-\u2010-\u2015]+/).filter(Boolean),n=[];for(let e of t){let t=e.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu,`$1\0$2`).replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu,`$1\0$2`);for(let e of t.split(`\0`))e&&n.push(e)}return n}function Xi(e){let t=Yi(e);return t.length===0?``:t.map((e,t)=>{let n=e.toLowerCase();return t===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join(``)}function Zi(e){return e.split(`.`).map(Xi).filter(e=>e.length>0).join(`.`)}function Qi(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(Array.isArray(e))return`array`;switch(typeof e){case`number`:return`number`;case`string`:return`string`;case`boolean`:return`boolean`;case`object`:return`object`;default:return`undefined`}}function $i(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}var ea=class extends Error{code;constructor(e,t){super(t),this.name=`UnitConversionError`,this.code=e}},ta=[{canonical:`m`,dimension:`distance`,factor:1,aliases:[`meter`,`meters`,`metre`,`metres`]},{canonical:`km`,dimension:`distance`,factor:1e3,aliases:[`kilometer`,`kilometers`,`kilometre`,`kilometres`]},{canonical:`cm`,dimension:`distance`,factor:.01,aliases:[`centimeter`,`centimeters`]},{canonical:`mm`,dimension:`distance`,factor:.001,aliases:[`millimeter`,`millimeters`]},{canonical:`ft`,dimension:`distance`,factor:.3048,aliases:[`foot`,`feet`]},{canonical:`in`,dimension:`distance`,factor:.0254,aliases:[`inch`,`inches`]},{canonical:`yd`,dimension:`distance`,factor:.9144,aliases:[`yard`,`yards`]},{canonical:`mi`,dimension:`distance`,factor:1609.344,aliases:[`mile`,`miles`]},{canonical:`kg`,dimension:`mass`,factor:1,aliases:[`kilogram`,`kilograms`,`kilo`,`kilos`]},{canonical:`g`,dimension:`mass`,factor:.001,aliases:[`gram`,`grams`]},{canonical:`lb`,dimension:`mass`,factor:.45359237,aliases:[`lbs`,`pound`,`pounds`]},{canonical:`ms`,dimension:`duration`,factor:.001,aliases:[`millisecond`,`milliseconds`]},{canonical:`s`,dimension:`duration`,factor:1,aliases:[`sec`,`secs`,`second`,`seconds`]},{canonical:`min`,dimension:`duration`,factor:60,aliases:[`mins`,`minute`,`minutes`]},{canonical:`h`,dimension:`duration`,factor:3600,aliases:[`hr`,`hrs`,`hour`,`hours`]},{canonical:`count`,dimension:`count`,factor:1},{canonical:`rep`,dimension:`count`,factor:1,aliases:[`reps`]},{canonical:`pull-up`,dimension:`count`,factor:1},{canonical:`thruster`,dimension:`count`,factor:1},{canonical:`problem`,dimension:`count`,factor:1},{canonical:`count/s`,dimension:`count-rate`,factor:1},{canonical:`bpm`,dimension:`count-rate`,factor:1/60},{canonical:`cal`,dimension:`energy`,factor:1,aliases:[`calorie`,`calories`]},{canonical:`kcal`,dimension:`energy`,factor:1e3,aliases:[`kilocalorie`,`kilocalories`]},{canonical:`m/s`,dimension:`speed`,factor:1},{canonical:`km/h`,dimension:`speed`,factor:1e3/3600,aliases:[`kmh`,`kph`]},{canonical:`mph`,dimension:`speed`,factor:1609.344/3600},{canonical:`min/km`,dimension:`pace`,factor:1},{canonical:`min/mi`,dimension:`pace`,factor:1e3/1609.344},{canonical:`s/m`,dimension:`pace`,factor:1/60},{canonical:`ratio`,dimension:`ratio`,factor:1,aliases:[`x`]},{canonical:`%`,dimension:`ratio`,factor:.01,aliases:[`pct`,`percent`]},{canonical:`au`,dimension:`ratio`,factor:1,aliases:[`AU`]},{canonical:`pts`,dimension:`ratio`,factor:1,aliases:[`point`,`points`]},{canonical:`rating`,dimension:`ratio`,factor:1,aliases:[`ratings`]}],na=(()=>{let e=new Map;for(let t of ta){e.set(t.canonical.toLowerCase(),t);for(let n of t.aliases??[])e.has(n.toLowerCase())||e.set(n.toLowerCase(),t)}return e})();function ra(e){if(typeof e==`string`)return na.get(e.trim().toLowerCase())}function ia(e){return ra(e)?.dimension}var aa=Object.freeze({mass:`kg`,distance:`m`,duration:`s`,count:`count`,"count-rate":`count/s`,energy:`cal`,speed:`m/s`,pace:`min/km`,ratio:void 0});function oa(e){return aa[e]}function sa(e,t,n){let r=ra(t);if(!r)throw new ea(`unknown-unit`,`Unknown unit "${t}"`);let i=ra(n);if(!i)throw new ea(`unknown-unit`,`Unknown unit "${n}"`);if(r.dimension!==i.dimension)throw new ea(`dimension-mismatch`,`Cannot convert ${t} (${r.dimension}) to ${n} (${i.dimension})`);if(r.dimension===`ratio`&&r.canonical!==i.canonical&&r.canonical!==`ratio`&&i.canonical!==`ratio`)throw new ea(`scale-mismatch`,`Named scales ${t} and ${n} are not interchangeable`);if(!Number.isFinite(e))throw new ea(`non-finite`,`Non-finite value cannot be converted`);return e*r.factor/i.factor}var ca=`references`,la=[`explicit`,`split`,`whole`,`default`,`none`];function ua(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`effort`||t.kind===`equipment`)&&typeof t.slug==`string`&&!!t.slug&&typeof t.label==`string`}function da(e){return!e||typeof e!=`object`?!1:typeof e.reason==`string`}function fa(e){let t=e?.[ca];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.matched!=`string`||!la.includes(n.matched))&&typeof n.source==`string`&&!(n.refs!==void 0&&(!Array.isArray(n.refs)||!n.refs.every(ua)))&&!(n.diagnostics!==void 0&&(!Array.isArray(n.diagnostics)||!n.diagnostics.every(da))))return t}var pa=class{line;startOffset;endOffset;length;columnStart;columnEnd;raw;constructor(e,t,n,r,i=0,a=0,o=``){this.line=e,this.startOffset=t,this.endOffset=n,this.length=r,this.columnStart=i,this.columnEnd=a,this.raw=o}},K=class e{_metrics;_indexedLength=0;_resolver=new Ji;id;constructor(t,n=`metrics`){if(this.id=n,t instanceof e){this._metrics=t.toArray(),this.syncIndexProperties();return}this._metrics=Array.isArray(t)?[...t]:[],this.syncIndexProperties()}static from(t,n=`metrics`){if(t instanceof e)return t.clone(n);if(Array.isArray(t))return new e(t,n);if(typeof t==`object`&&t&&`_metrics`in t){let r=t._metrics;if(Array.isArray(r))return new e(r,n)}return e.empty(n)}static empty(t=`metrics`){return new e(void 0,t)}clone(t=this.id){return new e(this._metrics,t)}get all(){return[...this._metrics]}get length(){return this._metrics.length}get size(){return this._metrics.length}get isEmpty(){return this._metrics.length===0}getByType(e){let t=this._metrics.filter(t=>t.type===e||t.name===e);return t.length<=1?t:[...t].sort((e,t)=>zi(t)-zi(e))}getFirst(e){let t=this.getByType(e);return t.length>0?t[0]:void 0}get(e){return this.getFirst(e)}has(e){return this._metrics.some(t=>t.type===e||t.name===e)}hasMetric(e){return this.has(e)}getDisplayMetrics(e){return this.resolve(e)}getMetric(e){return this._resolver.resolveOne(this._metrics,e)}getAllMetricsByType(e){return this.getByType(e)}get rawMetrics(){return this.toArray()}getAll(){return this.toArray()}getByOrigin(e){return this._metrics.filter(t=>(t.origin??`parser`)===e)}resolve(e){return this._resolver.resolve(this._metrics,e)}add(...e){return this._metrics.push(...e),this.syncIndexProperties(),this}remove(e){let t=[];return this._metrics=this._metrics.filter(n=>!e(n)||(t.push(n),!1)),this.syncIndexProperties(),t}removeByType(e){return this.remove(t=>t.type===e||t.name===e)}clear(){return this._metrics=[],this.syncIndexProperties(),this}replaceByType(e,...t){let n=this.removeByType(e);return this._metrics.push(...t),this.syncIndexProperties(),n}merge(t){let n=t instanceof e?t._metrics:Array.isArray(t)?t:t.metrics.toArray(),r=new Map;for(let e of n){let t=r.get(e.type)??[];t.push(e),r.set(e.type,t)}for(let[e,t]of r){let n=this._metrics.filter(t=>t.type===e);if(n.length===0){this._metrics.push(...t);continue}let r=Math.max(...n.map(e=>zi(e))),i=Math.max(...t.map(e=>zi(e)));i>r?(this._metrics=this._metrics.filter(t=>t.type!==e),this._metrics.push(...t)):i===r&&this._metrics.push(...t)}return this.syncIndexProperties(),this}[Symbol.iterator](){return this._metrics[Symbol.iterator]()}filter(e){return this._metrics.filter(e)}map(e){return this._metrics.map(e)}flatMap(e){return this._metrics.flatMap(e)}find(e){return this._metrics.find(e)}some(e){return this._metrics.some(e)}every(e){return this._metrics.every(e)}toArray(){return[...this._metrics]}get raw(){return this._metrics}syncIndexProperties(){for(let e=0;e<this._indexedLength;e++)delete this[e];for(let e=0;e<this._metrics.length;e++)this[e]=this._metrics[e];this._indexedLength=this._metrics.length}toString(){return`MetricContainer(${this._metrics.length})[${this._metrics.map(e=>e.type).join(`, `)}]`}},ma=class{exerciseId;line;text;raw;dialect;hasMetric(e){return this.metricContainer.hasMetric(e)}getDisplayMetrics(e){return this.metricContainer.getDisplayMetrics(e)}getMetric(e){return this.metricContainer.getMetric(e)}getAllMetricsByType(e){return this.metricContainer.getAllMetricsByType(e)}get rawMetrics(){return this.metricContainer.rawMetrics}get metricContainer(){return this.metrics instanceof K?this.metrics:K.from(this.metrics,this.id)}},ha=class extends ma{id=0;parent;children=[];meta=new pa(0,0,0,0);_metrics=K.empty();metricMeta=new Map;isLeaf;get metrics(){return this._metrics}set metrics(e){this._metrics=K.from(e,this.id)}constructor(e){super(),e&&(Object.assign(this,e),e.metrics&&(this.metrics=K.from(e.metrics,this.id)),this.metricMeta||=new Map)}},ga=class e extends ma{static nextId=1e6;id;outputType;timeSpan;sourceStatementId;sourceBlockKey;stackLevel;metrics;metricMeta;completionReason;parent;children;isLeaf;meta;statement;timestamp;constructor(t,n,r){if(super(),t&&`outputType`in t&&`timeSpan`in t){let n=t;this.id=e.nextId++,this.outputType=n.outputType,this.timeSpan=n.timeSpan,this.sourceBlockKey=n.sourceBlockKey??``,this.sourceStatementId=n.sourceStatementId,this.line=n.line,this.text=n.text,this.dialect=n.dialect,this.stackLevel=n.stackLevel??0,this.metrics=K.from(n.metrics,this.id),this.metricMeta=n.metricMeta??new Map,this.completionReason=n.completionReason,this.parent=n.parent,this.children=n.children??[],this.isLeaf=this.children.length===0,this.meta=new pa(0,0,0,0)}else{let i=t;this.id=e.nextId++,this.statement=i,this.outputType=`segment`,this.timeSpan={started:r??Date.now()},this.sourceBlockKey=``,this.sourceStatementId=typeof i?.id==`number`?i.id:void 0,this.stackLevel=0,this.metrics=K.from(n,this.id),this.metricMeta=new Map,this.children=[],this.isLeaf=!0,this.meta=i?.meta??new pa(0,0,0,0),this.line=i?.line,this.text=i?.text,this.dialect=i?.dialect,this.timestamp=r??Date.now()}}static resetIdCounter(t=1e6){e.nextId=t}},_a=class{value;constructor(e){this.value=e??(typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2))}toString(){return this.value}valueOf(){return this.value}equals(e){return this.value===e?.value}};function va(e){let t=e.trim(),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return`bc-${(n>>>0).toString(16).padStart(8,`0`)}`}var ya=[`segment`,`system`,`load`,`event`,`compiler`,`completion`,`analytics`,`wellness`];function ba(e){return e===`time`?`run`:e===`log`?`log`:null}function xa(e){let t=e.trim();return t.startsWith(`notebook/`)||t.startsWith(`notebook:`)?t.slice(9):t}function Sa(e){return`notebook/${xa(e)}`}function Ca(e){return e.seedOrigin!==`seed`}var wa=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`];function Ta(e){let t=e.match(/^`{3,}(time|log)(?::([\w-]+))?\s*$/i);return t?{dialect:t[1].toLowerCase()===`time`?`time`:`log`,...t[2]?{sport:t[2]}:{}}:null}function Ea(e){let t=e.type?.toLowerCase();if(t===`youtube`||t===`strava`||t===`amazon`||t===`file`||t===`effort`||t===`equipment`)return t;let n=(e.url||e.link||``).replace(/^[a-z][a-z0-9+.-]*:\/\//i,``).split(/[/?#:]/,1)[0].toLowerCase();return n===`youtu.be`||n===`youtube.com`||n.endsWith(`.youtube.com`)?`youtube`:n===`strava.com`||n.endsWith(`.strava.com`)?`strava`:n===`amzn.to`||n===`amazon.com`||n.endsWith(`.amazon.com`)?`amazon`:[`baseAttributes`,`discipline`,`effortType`,`targetRPE`,`equipment`,`aliases`,`derivation`].some(t=>t in e)?`effort`:[`slug`,`label`,`registrySource`,`ownerNoteId`,`sourcePath`].some(t=>t in e)?`equipment`:`default`}function Da(e){return/^#{1,6}\s/.test(e)?`heading`:/^[-*+]\s|^\d+\.\s/.test(e)?`list`:/^>\s?/.test(e)?`blockquote`:e.startsWith(`|`)&&/^\|[\s:]*-+/m.test(e)?`table`:`paragraph`}function Oa(e,t={}){if(!e)return[];let n=e.split(/\r\n|\n|\r/),r=[],i=[],a=0;for(let t of n){r.push(a),a+=t.length;let n=e.startsWith(`\r
3
3
  `,a)?`\r
4
4
  `:/[\r\n]/.test(e[a]??``)?e[a]:``;i.push(n),a+=n.length}let o=[],s=Date.now(),c=!0,l=0;function u(t,a,o){let c=r[a],l=r[o]+n[o].length;return{id:crypto.randomUUID(),type:t,from:c,to:l,rawContent:e.slice(c,l),displayContent:e.slice(c,l),startLine:a,endLine:o,lineCount:o-a+1,version:1,createdAt:s,separatorAfter:i[o]}}for(;l<n.length;){let a=n[l].trim(),d=a.match(/^(`{3,}|~{3,})(.*)$/);if(d){let a=d[1],c=l+1,f=RegExp(`^${a[0]}{${a.length},}\\s*$`);for(;c<n.length&&!f.test(n[c].trim());)c++;let p=c<n.length,m=p?c:n.length-1,h=d[2].trim(),g=a[0]==="`"?Ta(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i):null,y=t.registeredWidgets??wa,b=_&&(`has`in y?y.has(_[1]):y.includes(_[1])),x=p&&g?g.dialect:p&&b?`widget`:p&&v?`query`:`code`,S=u(x,l,m);S.contentFrom=r[l]+n[l].length+i[l].length,S.contentTo=p?r[c]:S.to,S.displayContent=e.slice(S.contentFrom,S.contentTo),g&&p&&(S.sport=g.sport,S.contentId=va(S.displayContent),S.scriptBlock={id:S.id,contentId:S.contentId,dialect:g.dialect,sport:g.sport,startLine:l,endLine:m,content:S.displayContent,state:`idle`,version:1,createdAt:s}),x===`widget`&&_&&(S.widgetName=_[1]),x===`query`&&v&&(S.querySuffix=(v[1]??``).trim()),o.push(S),l=m+1;continue}if(a===`---`&&n[l+1]?.trim()){let t=l+1;for(;t<n.length&&n[t].trim()!==`---`&&!/^(`{3,}|~{3,})/.test(n[t].trim());)t++;let i=n.slice(l+1,t);if(n[t]?.trim()===`---`&&i.some(e=>/^[A-Za-z_][\w-]*\s*:/.test(e.trim()))){let n=u(`frontmatter`,l,t);n.contentFrom=r[l+1],n.contentTo=r[t],n.displayContent=e.slice(n.contentFrom,n.contentTo),n.properties={};for(let e of i){let t=e.match(/^([^:]+):\s*(.*)$/);t&&(n.properties[t[1].trim()]=t[2].trim())}n.frontmatterType=Ea(n.properties),o.push(n),l=t+1;continue}}let f=a.match(/^(!)?\[([^\]]*)\]\((https?:\/\/[^)\s]+|\/[^)\s]+)\)$/);if(f){let e=u(`embed`,l,l),t=!!f[1];e.embed={type:t?`image`:/(?:youtube\.com|youtu\.be)/i.test(f[3])?`youtube`:`link`,label:f[2],url:f[3],isImage:t},o.push(e),l++;continue}let p=l;if(a)for(;p+1<n.length&&n[p+1].trim()&&!/^(?:`{3,}|~{3,}|---\s*$|!?\[[^\]]*\]\()/.test(n[p+1].trim());)p++;let m=u(a&&c?`title`:`markdown`,l,p);m.subtype=Da(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function ka(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Aa(e,t){if(!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw Error(`Invalid source revision`);let n=Object.create(null),r=Object.values(t.blocks??{}).filter(e=>e&&typeof e==`object`),i=t.createId??(()=>crypto.randomUUID());for(let a of Oa(e,t)){let e=ka(a);if(!e)continue;let o=r.filter(t=>t.from===a.from&&t.to===a.to&&t.kind===e),s=o.length===1?o[0]:void 0,c=s?.id??i();if(!c||Object.hasOwn(n,c))throw Error(`Duplicate block occurrence ID`);n[c]={id:c,kind:e,from:a.from,to:a.to,sourceRevision:t.sourceRevision,version:s?.version??1,...e===`wod`&&(a.type===`time`||a.type===`log`)?{dialect:a.type,...a.sport?{sport:a.sport}:{}}:{}}}return n}function ja(e,t,n,r={}){if(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid Note source or blocks`);for(let[e,r]of Object.entries(t))if(!r||r.id!==e||!e||!Number.isSafeInteger(r.version)||r.version<1||r.sourceRevision!==n||!Number.isSafeInteger(r.from)||!Number.isSafeInteger(r.to))throw Error(`Invalid block identity, version or source revision`);let i=Aa(e,{...r,sourceRevision:n,blocks:t});if(Object.keys(i).length!==Object.keys(t).length)throw Error(`Incomplete actionable block map`);for(let[e,n]of Object.entries(t)){let t=i[e];if(!t||t.from!==n.from||t.to!==n.to||t.kind!==n.kind||t.dialect!==n.dialect||t.sport!==n.sport)throw Error(`Block does not match authored source`)}}function Ma(e,t){let n=0;for(let e of t){if(!Number.isSafeInteger(e.from)||!Number.isSafeInteger(e.to)||e.from<n||e.to<e.from||typeof e.insert!=`string`)throw Error(`Invalid source changes`);n=e.to}let r={};for(let n of Object.values(e)){let e=n.from,i=n.to,a=!1;for(let r of t){let t=r.insert.length-(r.to-r.from);if(r.from<=n.from&&r.to>=n.to||r.from<n.from&&r.to>n.from||r.from<n.to&&r.to>n.to){a=!0;break}r.to<=n.from?(e+=t,i+=t):r.from<n.to&&(i+=t)}a||(r[n.id]={...n,from:e,to:i})}return r}var Na=/^[A-Za-z][\w.-]*$/,Pa=/^---\r?\n([\s\S]*?)\r?\n---/;function Fa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ia(e){let t=e.trim();return t===``||t.startsWith(`#`)}function La(e){return Array.isArray(e)}function Ra(e){if(e===``)return`""`;let t=!isNaN(Number(e)),n=/^(true|false|null|yes|no|on|off)$/i.test(e);return/[:"'\n#{}[\],&*?|<>=%!@`]/.test(e)||e!==e.trim()||e.startsWith(`-`)||t||n?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e}function za(e,t,n){let r=` `.repeat(e);return La(n)?n.length===0?[`${r}${t}: []`]:[`${r}${t}:`,...n.map(e=>`${r} - ${typeof e==`number`?String(e):Ra(e)}`)]:[`${r}${t}: ${typeof n==`number`?String(n):Ra(n)}`]}function Ba(e,t,n,r){let i=[],a=r;for(let r=t;r<e.length;r++)r===e.length-1?i.push(...za(a,e[r],n)):i.push(`${` `.repeat(a)}${e[r]}:`),a+=2;return i}function Va(e){let t=!1,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){i===`\\`?r++:i===`"`&&(n=!1);continue}if(t){i===`'`&&(t=!1);continue}if(i===`"`)n=!0;else if(i===`'`)t=!0;else if(i===`#`&&(r===0||/\s/.test(e[r-1])))return r}return-1}function Ha(e,t,n){let r=[t],i=[];for(let a=t+1;a<e.length;a++){let t=e[a];if(Ia(t)){i.push(a);continue}if(t.length-t.trimStart().length>n)r.push(...i,a),i=[];else break}return r}function Ua(e,t,n,r,i){let a=RegExp(`^ {${n}}${Fa(t)}\\s*:`);for(let t=r;t<i;t++)if(a.test(e[t]))return t;return-1}function Wa(e,t,n){if(t.length===0||!t.every(e=>typeof e==`string`&&Na.test(e)))return e;let r=e.includes(`\r
@@ -97,7 +97,7 @@ sum:$metric{} by {week}
97
97
  `)?e:e+`
98
98
  `;return{statements:ks(ri.create({doc:n,extensions:[Ls]}),t),errors:[],success:!0}}catch(e){return{statements:[],errors:[{message:e instanceof Error?e.message:`Unknown parse error`,severity:`error`}],success:!1}}}function uF(e,...t){console.warn(`[${e}]`,...t)}function dF(e,...t){console.error(`[${e}]`,...t)}function fF(e,t={}){let n=t.sourceRevision??1,r=Aa(e,{...t,blocks:t.noteBlocks,sourceRevision:n}),i=Oa(e,t),a=[];for(let e of i){if(!ka(e))continue;let t=Object.values(r).find(t=>t.from===e.from&&t.to===e.to);t&&(e.id=t.id,e.version=t.version,e.scriptBlock&&(e.scriptBlock=pF({...e.scriptBlock,id:t.id,version:t.version}),a.push(e.scriptBlock)))}return{sections:i,blocks:a,noteBlocks:r,rawContent:e,sourceRevision:n}}function pF(e){try{let t=lF(e.content,e.sport);return{...e,statements:t.statements,errors:t.errors,state:t.success?`parsed`:`error`}}catch(t){return dF(`WorkbenchDocumentModel`,`Block parse error:`,t),e}}function mF(e){if(e.kind!==`wod`||!e.dialect)throw Error(`The saved revision is not a workout.`);let t=Oa(e.rawContent).find(t=>t.type===e.dialect);if(!t?.scriptBlock)throw Error(`The saved workout fence cannot be read.`);let n=t.scriptBlock.content;return{id:e.blockId,content:n,dialect:e.dialect,sport:e.sport,statements:Is().read(n,e.sport).statements,startLine:0,endLine:e.rawContent.split(`
99
99
  `).length-1,version:e.version,state:`idle`,widgetIds:{},createdAt:e.savedAt}}async function hF(e,t,n,r,i=Nj){let a=Date.now(),o=await i.startSession(e,{id:n,noteId:e.noteId,blockId:t.id,blockContentId:t.contentId,origin:r??`journal`,startTime:a,endTime:a,duration:0,completed:!1,status:`in-progress`,createdAt:a});return{...o,block:mF(o.revision)}}async function gF(e,t,n,r){let i=await X.getNote(e);if(!i)throw Error(`The note is unavailable. Save the note before starting a workout.`);return hF({noteId:i.id,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:i.sourceRevision},t,n,r)}var _F={handleStart:()=>{},handlePause:()=>{},handleStop:()=>{},handleNext:()=>{},handleStartWorkoutAction:()=>{}},vF={content:``,sections:null,noteBlocks:{},sourceRevision:0,capturedRun:null,saveError:null,blocks:[],activeBlockId:null,saveState:`idle`,lastSavedContent:``,loadedRouteId:null,results:[],currentEntry:null,historyEntries:[],panelLayouts:{},attachments:[],runtime:null,execution:{status:`idle`,elapsedTime:0,stepCount:0,startTime:null,start:()=>{},pause:()=>{},stop:()=>{},reset:()=>{},step:()=>{}},handles:_F,activeSegmentIds:new Set,activeStatementIds:new Set,analyticsSegments:[],analyticsGroups:[],selectedAnalyticsIds:new Set,lastSelectedAnalyticsId:null,outputStatementList:[],logOutputList:[],userOutputOverrides:new Map,gridViewPreset:`default`,hoveredBlockKey:null,documentItems:[],selectedBlock:null,selectedBlockId:null,cursorLine:1,highlightedLine:null,subscriptionManager:null,viewMode:`plan`},yF=5e3;function bF(e={}){let t=e.listeners??[],n=e.nowProvider??Fc,r=e.notePersistence,i=e.setTimeout??((e,t)=>window.setTimeout(e,t)),a=e.clearTimeout??(e=>{typeof e==`number`&&window.clearTimeout(e)}),o=null,s=[],c=fn()((t,n)=>{let c=Promise.resolve(),l=async i=>{let a=n(),o=a.currentEntry?.id??a.loadedRouteId;if(!(!o||!r||!e.provider?.capabilities.canWrite)&&(i.rawContent!==a.lastSavedContent||JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(a.currentEntry?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))){t({saveState:`saving`,saveError:null});try{let e=await r.saveNote({noteId:o,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:a.sourceRevision,metadata:{title:i.rawContent.match(/^#\s+(.+)$/m)?.[1]?.trim()??`Untitled Session`},noteType:`playground`}),s=n();t({currentEntry:e,...s.content===i.rawContent&&JSON.stringify(Object.values(s.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision??a.sourceRevision,lastSavedContent:i.rawContent,saveState:`saved`})}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}}},u=()=>{o=null;let e=n(),t={rawContent:e.content,blocks:e.noteBlocks,sourceRevision:e.sourceRevision},r=c.catch(()=>{}).then(()=>l(t));return c=r,r};return{...vF,setContent:r=>{let s=fF(r,{noteBlocks:n().noteBlocks,sourceRevision:Math.max(1,n().sourceRevision)}),c=n(),l={content:r,sections:s.sections,blocks:s.blocks,noteBlocks:s.noteBlocks};r!==c.lastSavedContent&&(c.saveState===`idle`&&(l.saveState=`changed`),o!==null&&a(o),e.provider&&e.provider.capabilities.canWrite&&(o=i(()=>{u().catch(()=>{})},yF))),t(l)},setBlocks:e=>t({blocks:e}),setEditorIdentity:r=>{let s=JSON.stringify(Object.values(n().noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(r.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));t({content:r.rawContent,noteBlocks:r.blocks}),s&&e.provider?.capabilities.canWrite&&(o!==null&&a(o),o=i(()=>{u().catch(()=>{})},yF))},acceptSaved:e=>t(t=>({...t.content===e.rawContent&&JSON.stringify(Object.values(t.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision,lastSavedContent:e.rawContent})),restoreBlock:async e=>{if(!r)throw Error(`Note persistence is unavailable.`);await u();let i=n(),a=KP({rawContent:i.content,blocks:i.noteBlocks,sourceRevision:i.sourceRevision},e),o=await r.saveNote({noteId:e.noteId,rawContent:a.rawContent,blocks:a.blocks,expectedSourceRevision:i.sourceRevision}),s=fF(o.rawContent,{noteBlocks:o.blocks,sourceRevision:o.sourceRevision});t({content:o.rawContent,noteBlocks:o.blocks,sourceRevision:o.sourceRevision,lastSavedContent:o.rawContent,currentEntry:o,sections:s.sections,blocks:s.blocks})},startPinnedRun:async e=>{await c.catch(()=>{});let i=n(),a=i.currentEntry?.id??i.loadedRouteId;if(!a||!r)throw Error(`Save the note before starting a workout.`);try{let n=await hF({noteId:a,rawContent:i.content,blocks:i.noteBlocks,expectedSourceRevision:i.sourceRevision},e,C(),void 0,r);return t({capturedRun:n,noteBlocks:n.note.blocks,sourceRevision:n.note.sourceRevision,currentEntry:{...i.currentEntry,...n.note,updatedAt:Date.now(),targetDate:i.currentEntry?.targetDate??Date.now(),schemaVersion:1},lastSavedContent:n.note.rawContent,saveError:null}),n.block}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}},setActiveBlockId:e=>t({activeBlockId:e}),setSaveState:e=>t({saveState:e}),flushSave:async()=>{o!==null&&a(o),o=null,await u()},markSaved:e=>t({lastSavedContent:e,saveState:`saved`}),setResults:e=>t({results:e}),resetResults:()=>t({results:[]}),setCurrentEntry:e=>{if(e&&e.id!==n().currentEntry?.id){let n=fF(e.rawContent,{noteBlocks:e.blocks,sourceRevision:Math.max(1,e.sourceRevision??0)});t({currentEntry:e,content:e.rawContent,noteBlocks:n.noteBlocks,sections:n.sections,blocks:n.blocks,sourceRevision:e.sourceRevision??0,lastSavedContent:e.rawContent})}else t({currentEntry:e})},setHistoryEntries:e=>t({historyEntries:e}),setPanelLayouts:e=>t({panelLayouts:e}),expandPanel:(e,n)=>t(t=>{let r=t.panelLayouts[e]??{viewId:e,panelSpans:{},expandedPanelId:null},i=r.expandedPanelId?r.panelSpans:{...r.panelSpans};return{panelLayouts:{...t.panelLayouts,[e]:{...r,panelSpans:{...i,[n]:3},expandedPanelId:n}}}}),collapsePanel:e=>t(t=>{let n=t.panelLayouts[e];return n?{panelLayouts:{...t.panelLayouts,[e]:{...n,expandedPanelId:null}}}:t}),setAttachments:e=>t({attachments:e}),addAttachment:async r=>{let i=e.notePersistence,a=e.provider,o=n().currentEntry?.id;if(!o||!a?.capabilities.canWrite||!i)return;console.log(`[WorkbenchSession] Processing attachment: ${r.name}`);let s=await ay.process(r),{v7:c}=await cn(async()=>{let{v7:e}=await import(`./vendor-DEqYb4q_.js`).then(e=>e.Tt);return{v7:e}},__vite__mapDeps([0,1]));console.log(`[WorkbenchSession] Saving attachment to entry ${o}`),await i.mutateNote(o,{attachments:{add:[{id:c(),label:s.label,mimeType:s.mimeType,data:s.data,timeSpan:s.timeSpan??{start:Date.now(),end:Date.now()}}]}}),t({attachments:(await i.getNote(o,{projection:`workbench`,includeAttachments:!0})).attachments??[]}),console.log(`[WorkbenchSession] Attachment saved successfully`)},deleteAttachment:async r=>{let i=e.notePersistence,a=n().currentEntry?.id;!a||!i||(await i.mutateNote(a,{attachments:{remove:[r]}}),t({attachments:(await i.getNote(a,{projection:`workbench`,includeAttachments:!0})).attachments??[]}))},patchCurrentEntryResults:e=>t(t=>t.currentEntry?{currentEntry:{...t.currentEntry,results:e}}:t),completeWorkout:async(e,i)=>{let a=n().capturedRun,o=i??a?.session.id;if(!o||!r?.finishSession)throw Error(`The saved run pin is unavailable.`);let s=await r.finishSession(o,e,e.endTime);return t(t=>({results:[...t.results,e]})),s.id},loadEntry:async r=>{let i=e.notePersistence,a=e.provider;if(!i||!a)return null;let{routeId:o,routeView:s,routeSectionId:c,routeResultId:l,resultFromLocationState:u,initialActiveEntryId:d,propInitialContent:f}=r;if(n().setContent(``),n().setBlocks([]),t({currentEntry:null,loadedRouteId:o??null}),o){if(a.mode===`history`||a.mode===`static`)try{let e=l?{mode:`by-result-id`,resultId:l}:c&&s===`review`?{mode:`latest-for-section`,blockId:c}:{mode:`latest`},d=await i.getNote(o,{projection:s===`review`?`review`:`workbench`,includeAttachments:!0,includeSections:!0,resultSelection:e}).catch(async t=>(console.warn(`[WorkbenchSession] Note persistence projection failed, falling back to provider entry:`,{routeId:o,projection:s===`review`?`review`:`workbench`,resultSelectionMode:e.mode,err:t}),a.getEntry(o)));if(d){let e=fF(d.rawContent,{noteBlocks:d.blocks,sourceRevision:Math.max(1,d.sourceRevision??0)});return t({currentEntry:d,content:d.rawContent,sections:e.sections,blocks:e.blocks,noteBlocks:e.noteBlocks,sourceRevision:d.sourceRevision??0,lastSavedContent:d.rawContent,saveState:`saved`}),s===`review`&&u&&t(e=>e.currentEntry?{currentEntry:{...e.currentEntry,results:u}}:e),r.onLoaded?.(d),d}if(a.mode===`static`){let e=await YP(o);if(e)return n().setContent(e),null}}catch(e){console.error(`[WorkbenchSession] Failed to load entry for ID:`,o,e)}}else d&&e.navigate?.({type:`goToPlan`,noteId:d});return n().setContent(f??``),null},setActiveSegmentIds:e=>t({activeSegmentIds:e}),setActiveStatementIds:e=>t({activeStatementIds:e}),setAnalytics:(e,n)=>t({analyticsSegments:e,analyticsGroups:n}),appendOutputStatement:e=>t(t=>{let n=[...t.outputStatementList,e],{segments:r,groups:i}=zP(t.runtime);return t.runtime?{outputStatementList:n,analyticsSegments:r,analyticsGroups:i}:{outputStatementList:n}}),clearOutputStatementList:()=>t({outputStatementList:[]}),feedLogOutputs:(e,n)=>{let{segments:r,groups:i}=BP(e,n);t({logOutputList:e,analyticsSegments:r,analyticsGroups:i})},toggleAnalyticsSegment:(e,n,r)=>t(t=>{let i=new Set(t.selectedAnalyticsIds);if(n?.shiftKey&&t.lastSelectedAnalyticsId!==null&&r){let n=r.indexOf(t.lastSelectedAnalyticsId),a=r.indexOf(e);if(n!==-1&&a!==-1){let e=Math.min(n,a),t=Math.max(n,a);r.slice(e,t+1).forEach(e=>i.add(e))}}else n?.ctrlKey?i.has(e)?i.delete(e):i.add(e):(i.clear(),i.add(e));return{selectedAnalyticsIds:i,lastSelectedAnalyticsId:e}}),setUserOverride:(e,n)=>t(t=>{let r=new Map(t.userOutputOverrides);return r.set(e,K.from(n,e)),{userOutputOverrides:r}}),clearUserOverride:e=>t(t=>{let n=new Map(t.userOutputOverrides);return n.delete(e),{userOutputOverrides:n}}),setGridViewPreset:e=>t({gridViewPreset:e}),setHoveredBlockKey:e=>t({hoveredBlockKey:e}),setDocumentItems:e=>t({documentItems:e}),setSelectedBlock:e=>t({selectedBlock:e,selectedBlockId:e?.id??null}),setSelectedBlockId:e=>t({selectedBlockId:e}),setCursorLine:e=>t({cursorLine:e}),setHighlightedLine:e=>t({highlightedLine:e}),setSubscriptionManager:e=>{t({subscriptionManager:e}),cF.setSubscriptionRegistry(e)},setViewMode:e=>t({viewMode:e}),setRuntime:e=>{for(let e of s)e();if(s=[],e){let r=zP(e);t({runtime:e,outputStatementList:[],analyticsSegments:r.segments,analyticsGroups:r.groups}),s.push(e.subscribeToOutput(()=>{n().appendOutputStatement({})})),s.push(e.subscribeToStack(e=>{let n=e.blocks[0],r=new Set;for(let t of e.blocks)r.add(Mi(t.key.toString()));let i=new Set;if(n&&Array.isArray(n.sourceIds))for(let e of n.sourceIds)i.add(e);t({activeSegmentIds:r,activeStatementIds:i})}));let i=JO();if(i?.connected){let t=new rF(i);s.push(e.subscribeToStack(e=>t.onStackSnapshot(e)),e.subscribeToOutput(e=>t.onOutput(e)),()=>t.dispose());try{t.onStackSnapshot(e.getStackSnapshot())}catch{}}}else t({runtime:null,outputStatementList:[]})},setExecution:e=>t({execution:e}),setHandles:e=>t({handles:e}),getNote:async(e,t)=>{if(!r)throw Error(`[WorkbenchSession] getNote called without a notePersistence port`);return r.getNote(e,t)},resetStore:()=>{o!==null&&(a(o),o=null);for(let e of s)e();s=[],t({...vF})}}});return t.length>0&&c.subscribe(e=>{for(let n of t)n(e)}),Object.assign(c,{__nowProvider:n})}var xF=bF();function SF(e){let t=xF;return xF=e,t}function CF(){return xF}var wF=e=>En(xF,e),TF=({nowProvider:e,notePersistence:t,provider:n,navigate:r,children:i})=>{let a=(0,V.useMemo)(()=>bF({nowProvider:e,notePersistence:t,provider:n,navigate:r}),[e,t,n,r]);return(0,V.useEffect)(()=>{let e=SF(a);return()=>{SF(e),a.getState().resetStore()}},[a]),V.createElement(V.Fragment,null,i)},EF={getEventsByTimeRange:(e,t)=>X.getEventsByTimeRange(e,t),getEventsByMetricDates:e=>X.getEventsByMetricDates(e),getEventsByResult:e=>X.getEventsByResult(e),getEventsForNote:e=>X.getEventsForNote(e),getEventsByContent:e=>X.getEventsByContent(e),scanAll:()=>X.scanAll(),appendEvents:e=>X.appendEvents(e),finalizeSummaries:(e,t)=>X.finalizeSummaries(e,t),deleteEvents:e=>X.deleteEvents(e)},DF={getAllNotes:()=>X.getAllNotes(),getNotesByIds:async e=>[...(await X.getEntryBatches(e)).values()].map(e=>e.note),getNoteIdsForTag:async e=>new Set((await X.getNotesForTag(e)).map(e=>e.id)),getNoteTagLabels:async e=>(await X.getTagsForNote(e)).map(e=>e.label),queryDomain:async e=>{if(!X.queryDomain)return;let t=await X.queryDomain({...e,plan:`notes`});return t&&t.plan===`notes`?t:void 0}},OF={getAllBlocks:()=>X.getAllBlockIndex(),queryDomain:async e=>{if(!X.queryDomain)return;let t=await X.queryDomain({...e,plan:`blocks`});return t&&t.plan===`blocks`?t:void 0}},kF=class{async getAllEfforts(){let e=IE();return e.isInitialized()||await PE(e),[...e.list()]}},AF=new Xh,jF={events:[],notes:[]},MF={events:[],notes:[]};AF.set(`@session`,jF),AF.set(`@today`,MF);function NF(){let e=CF().getState(),t=e.runtime?.getOutputStatements()??[],n=e.currentEntry;return jF.notes=n?[{id:n.id,title:n.title,createdAt:n.createdAt,date:n.targetDate,rawContent:n.rawContent,sourceRevision:n.sourceRevision??1,blocks:n.blocks??{}}]:[],t.length===0?(jF.events=[],jF):(jF.events=sg(t.map(Ff),{noteId:n?.id??``,resultId:`live:${n?.id??`session`}`,origin:`playground`,workoutTimestamp:n?.targetDate}),jF)}function PF(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 Ph(e.date??e.createdAt,r)}async function FF(e,t){let n=Ph(e.instant,e.timeZone),r=zh(n,e.timeZone),i=zh(Fh(n,1),e.timeZone),[a,o,s,c]=await Promise.all([X.getEventsByTimeRange(r,i),X.getAllNotes(),X.getAllPageNotes(),X.getAllPages()]),l=a.filter(e=>e.timestamp>=r&&e.timestamp<i),u=new Map(c.map(e=>[e.id,e])),d=new Map;for(let e of s){let t=d.get(e.noteId);t?t.push(e):d.set(e.noteId,[e])}let f=[];for(let t of o)PF(t,d.get(t.id)??[],u,e.timeZone)===n&&f.push(t);t===RF&&(MF.events=l,MF.notes=f,NF())}var IF=null,LF=null,RF=0,zF=!1,BF=new Set;function VF(){for(let e of BF)e()}function HF(e,t){LF=t;let n=++RF;return IF=FF(e,n),IF.then(()=>{n===RF&&UF()},()=>{n===RF&&UF()}),IF}function UF(){zF=!0,VF()}function WF(){let e=Oh(),t=Ph(e.instant,e.timeZone);return!IF||LF!==t?HF(e,t):IF}function GF(){zF=!1;let e=Oh();return HF(e,Ph(e.instant,e.timeZone))}function KF(){return zF}function qF(e){return BF.add(e),()=>{BF.delete(e)}}var JF=class extends Vg{async runQuery(e,t){return await WF(),super.runQuery(e,t)}async runPipeline(e,t){return await WF(),super.runPipeline(e,t)}async runFind(e,t){return await WF(),super.runFind(e,t)}async runRows(e,t){return await WF(),super.runRows(e,t)}async run(e,t){return await WF(),super.run(e,t)}};function YF(){return new JF({eventStore:EF,noteStore:DF,blockStore:OF,effortStore:new kF,blockEffortsStore:{getAllFromIndex:(e,t)=>X.getAllFromIndex(`block_efforts`,e,t)},tagsStore:{getAllFromIndex:(e,t)=>X.getAllFromIndex(`tags`,e,t)},noteTagsStore:{getAllFromIndex:(e,t)=>X.getAllFromIndex(`note_tags`,e,t)},pageStore:{getNotePages:e=>X.getNotePages(e),getPage:e=>X.getPage(e)},relationStore:{getBatches:e=>X.getEntryBatches(e)},datasetStore:{getDataset:e=>e===`@session`?NF():AF.getDataset(e)}})}var XF=YF();function ZF(e){let t=e.split(`/`),n=t[0]??e,r=t[1]??``;return n===`journal`?{kind:`journal`,id:r,raw:e}:n===`playground`?{kind:`playground`,id:r,raw:e}:t.length<2?{kind:`workout`,id:n,raw:e}:{kind:`workout`,category:n,id:r,raw:e}}var QF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $F(e){return typeof e==`string`&&e&&!QF.test(e)?e:void 0}function eI(e){return!!e.sourceId?.startsWith(`collection:`)||!!e.sourceId?.startsWith(`page:collection:`)||e.type===`feed`||/^markdown\/collections\/[^/]+\/.+/.test(e.sourcePath??``)}function tI(e){return!!e.sourceId?.startsWith(`feed:`)||e.sourcePath?.startsWith(`markdown/feeds/`)===!0}function nI(e){return e.type===`dashboard`||e.sourceId===`dashboards`||e.sourcePath?.startsWith(`markdown/dashboards/`)===!0}function rI(e){return e.sourceId===`efforts`||e.sourcePath?.startsWith(`markdown/efforts/`)===!0}function iI(e){return e.sourceId===`equipment`||e.sourcePath?.startsWith(`markdown/equipment/`)===!0}function aI(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 oI(e){let t=e.sourceId;if(t?.startsWith(`page:collection:`)){let e=t.slice(16);if(e)return{catalog:e,item:``}}else if(t?.startsWith(`collection:`)){let e=t.slice(11);if(e){let t=e.indexOf(`/`);return t===-1?{catalog:e,item:``}:{catalog:e.slice(0,t),item:e.slice(t+1)}}}let n=/^markdown\/collections\/([^/]+)\/(.+)\.md$/.exec(e.sourcePath??``);if(n)return{catalog:n[1],item:n[2].toLowerCase()===`readme`?``:n[2]};let r=e.id.replace(/^page:collection:/,``);if(QF.test(r))return{catalog:e.catalog??``,item:``};let[i,...a]=r.split(`/`);return{catalog:i,item:a.join(`/`)}}function sI(e){return e.sourceId===`playground`||e.type===`playground`||e.id.startsWith(`playground/`)}function cI(e){return e.id.startsWith(`playground/`)?e.id.slice(11):e.id}function lI(e){return{...uI(e),noteType:e.type,catalog:gg(e),notebookId:_g(e),editable:Ca(e),noteId:e.id}}function uI(e){let t=e.id,n=e.title,r=e.tags&&e.tags.length>0?e.tags:void 0;if(sI(e))return{id:t,kind:`note`,sourceCatalog:`playground`,sourceItem:cI(e),sourceId:e.sourceId,title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}};if(eI(e)){let i=t.replace(/^page:collection:/,``),{catalog:a,item:o}=oI(e);return{id:i,kind:`session`,sourceCatalog:a,sourceItem:!o||e.type===`feed`||e.type===`page`?``:o,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?$F(e.slug):void 0,title:n,date:e.date?Bj(new Date(e.date)):null,createdAt:e.createdAt,subtitle:e.catalog??a,...r?{tags:r}:{}}}if(tI(e)){let i=e.sourceId?.startsWith(`feed:`)?e.sourceId.slice(5):e.sourcePath?.startsWith(`markdown/feeds/`)?e.sourcePath.slice(9).replace(/\.md$/,``):e.id,a=(i.startsWith(`feeds/`)?i.slice(6):i).split(`/`),o=a[1]&&/^\d{4}-\d{2}-\d{2}$/.test(a[1])?a[1]:null;return{id:t,kind:`post`,sourceCatalog:a[0],sourceItem:a.slice(2).join(`/`)||a[a.length-1],sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:o,createdAt:e.createdAt,subtitle:e.catalog??a[0],...r?{tags:r}:{}}}if(nI(e))return{id:t,kind:`dashboard`,sourceCatalog:`dashboards`,sourceItem:aI(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:e.catalog??`dashboards`,...r?{tags:r}:{}};if(rI(e)){let i=aI(e,2)??t,a=e.sourcePath?.match(/^markdown\/efforts\/([^/]+)\//)?.[1];return{id:t,kind:`effort`,sourceCatalog:`efforts`,sourceItem:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:a,effort:{slug:i},...r?{tags:r}:{}}}if(iI(e))return{id:t,kind:`equipment`,sourceCatalog:`equipment`,sourceItem:aI(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`equipment`,...r?{tags:r}:{}};if(e.sourceId?.startsWith(`guides:`)){let i=e.sourceId.slice(7)||t;return{id:t,kind:`note`,sourceCatalog:`guides`,sourceItem:i,sourceId:e.sourceId,sourcePath:e.sourcePath,pageSlug:$F(i.replace(/^\//,``).replace(/^guide\//,``)),title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}}}let i=null;return`journalDate`in e&&typeof e.journalDate==`string`?i=e.journalDate:`date`in e&&typeof e.date==`string`?i=e.date:`targetDate`in e&&e.targetDate&&(typeof e.targetDate==`number`||typeof e.targetDate==`string`)?i=Bj(new Date(e.targetDate)):e.createdAt&&(i=Bj(new Date(e.createdAt))),{id:t,kind:`note`,sourceCatalog:`journal`,sourceItem:t,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?$F(e.slug):void 0,title:n,date:i,createdAt:e.createdAt,...r?{tags:r}:{}}}function dI(e){return{id:e.noteId,title:e.noteTitle,createdAt:e.createdAt,type:`note`,sourceId:e.sourceId,sourcePath:e.sourcePath,rawContent:``,sourceRevision:1,blocks:{}}}var fI=3,pI=120;function mI(e){return e.split(`
100
- `).map(e=>e.trim()).filter(Boolean).slice(0,fI).map(e=>e.length>pI?`${e.slice(0,119)}…`:e)}function hI(e){let t=lI(dI(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,catalog:gg(e),block:{blockId:e.blockId,dataType:e.dataType,preview:mI(e.rawContent)}}}function gI(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 _I(e){if(!Number.isFinite(e)||e<=0)return`00:00`;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;if(n>=60){let e=Math.floor(n/60),t=n%60;return`${e}:${String(t).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function vI(e){if(!e)return`Workout Session`;let t=ZF(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?gI(t.id)||t.id:t.id?gI(t.id):e}function yI(e){let t=[e.baseAttributes?.discipline,e.baseAttributes?.met==null?void 0:`MET ${e.baseAttributes.met.toFixed(1)}`,e.baseAttributes?.intensityTier].filter(Boolean);return{id:e.slug,kind:`effort`,sourceCatalog:e.registrySource??`effort`,sourceItem:e.slug,title:e.label,date:null,subtitle:t.join(` • `),detail:e.aliases&&e.aliases.length>0?`Aliases: ${e.aliases.join(`, `)}`:void 0,effort:{slug:e.slug,label:e.label,discipline:e.baseAttributes?.discipline,met:e.baseAttributes?.met,intensityTier:e.baseAttributes?.intensityTier,aliases:e.aliases,registrySource:e.registrySource}}}function bI(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.value==`number`?e.value:Number(e.value);return Number.isFinite(r)?t===`rep`||n===`reps`||n===`rep`?{kind:`rep`,val:r}:t===`weight`||t===`load`||n===`load`||n===`weight`||n===`volume`?{kind:`load`,val:r}:t===`distance`||n===`distance`?{kind:`distance`,val:r}:t===`tis`||n===`tis`?{kind:`tis`,val:r}:t===`duration`||n===`duration`?{kind:`duration`,val:r}:null:null}function xI(e){let t=1/0,n=-1/0,r=0,i=0,a=0,o=0,s=new Set;for(let c of e.events)if(c.outputType===`segment`&&o++,c.effortSlug&&s.add(c.effortSlug),c.timeSpan?.started!=null&&(c.timeSpan.started<t&&(t=c.timeSpan.started),c.timeSpan.ended!=null&&c.timeSpan.ended>n&&(n=c.timeSpan.ended)),Array.isArray(c.metrics))for(let e of c.metrics){let t=bI(e);t&&(t.kind===`rep`?r+=t.val:t.kind===`load`?i+=t.val:t.kind===`tis`&&t.val>a&&(a=t.val))}return{elapsedMs:Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,reps:r>0?r:void 0,loadLbs:i>0?i:void 0,tis:a>0?a:void 0,segmentCount:o>0?o:void 0,effortSlugs:Array.from(s)}}function SI(e,t){let n=xI(e),r=[];n.elapsedMs!=null&&r.push(_I(n.elapsedMs)),n.tis!=null&&r.push(`TIS ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${n.loadLbs.toLocaleString()} lbs`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`);let i=n.effortSlugs.map(gI),a=Bj(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;return{id:e.resultId,kind:`result`,sourceCatalog:`results`,sourceItem:e.resultId,title:t?.noteTitle??vI(e.noteId),date:a,blockContentId:o,subtitle:r.join(` • `),detail:i.length>0?i.join(`, `):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:`all`,elapsedMs:n.elapsedMs,reps:n.reps,loadLbs:n.loadLbs,tis:n.tis,segmentCount:n.segmentCount,events:e.events}}}function CI(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=bI(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`?i=e.val:e.kind===`distance`?a=e.val:e.kind===`tis`?o=e.val:e.kind===`duration`&&!n&&(n=e.val))}let s=e.outputType===`segment`?`segment`:`event`,c=t?.index??0,l=e.effortSlug?gI(e.effortSlug):e.outputType===`segment`?`Round ${c+1}`:`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${c+1}`,u=[];n!=null&&u.push(_I(n)),r!=null&&i!=null?u.push(`${r} reps @ ${i} lbs`):r==null?i!=null&&u.push(`${i} lbs`):u.push(`${r} reps`),a!=null&&u.push(`${a}m`),o!=null&&u.push(`TIS ${o.toFixed(1)}`);let d=Bj(new Date(e.timestamp));return{id:e.id,kind:s,sourceCatalog:`results`,sourceItem:e.id,title:l,date:d,blockContentId:e.blockContentId,subtitle:u.join(` • `),detail:e.effortSlug?gI(e.effortSlug):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:e.outputType,effortSlug:e.effortSlug,elapsedMs:n,reps:r,loadLbs:i,distanceMeters:a,tis:o,metrics:e.metrics}}}function wI(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(CI(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(CI(i,{index:e++}))}return t}return e.runs.map(e=>SI(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function TI(e,t,n){let r=typeof e.__id==`string`&&e.__id?e.__id:void 0,i=typeof e.__resultId==`string`&&e.__resultId?e.__resultId:void 0,a=typeof e.effort==`string`&&e.effort?e.effort:void 0,o=[];for(let[t,n]of Object.entries(e))t.startsWith(`__`)||t===`date`||t===`effort`||(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&o.push(`${t}: ${n}`);return{id:r??i??`${t}:${n}`,kind:t,sourceCatalog:`results`,sourceItem:i??r??`${t}:${n}`,title:a?gI(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function EI(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function DI(e){return typeof e==`object`&&!!e&&`runFind`in e}var OI=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){DI(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver)}get service(){return this.customService??XF}withNoteBlockInfo(){let t=new e({service:this.service,noteTitleResolver:this.noteTitleResolver,noteTagsResolver:this.noteTagsResolver,noteBlockInfo:!0});return Object.prototype.hasOwnProperty.call(this,`query`)&&(t.query=this.query),t}async hydrateEntries(e,t){let n=e=>e.noteId??e.id,r=new Set;for(let i of e)i.sourceCatalog===`journal`&&r.add(n(i)),t&&(!i.title||!i.tags||i.tags.length===0)&&r.add(n(i));if(r.size===0)return;let i=await X.getEntryBatches([...r]);for(let t of e){if(t.sourceCatalog!==`journal`)continue;let e=i.get(n(t)),r=[...e?.links??[]].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt);for(let n of r){let r=e?.pages.find(e=>e.id===n.pageId);if(r&&(t.pageId??=r.id,!r.date&&r.slug)){t.pageSlug=r.slug;break}}}if(t)for(let t of e){let e=i.get(n(t));!t.title&&e?.note.title&&(t.title=e.note.title),e&&e.tags.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.tags.map(e=>e.label)),t.typedTags=e.tags.map(e=>({label:e.label,type:e.type})))}}async query(e,t){let n=typeof e==`string`?Y(e):e;if(!n||n.error)return[];if(tm(n)){if(n.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(n):await this.service.runFind(n),r=(e.efforts??[]).map(yI);return EI(t,e.stages,r),r}if(n.target===`block`){let e=await this.service.runFind(n),r=e.blocks.map(hI);return await this.hydrateEntries(r,!0),EI(t,e.stages,r),r}if(n.target===`session`){let e=await this.service.runFind(n);t?.(e.stages);let r;if(this.noteTitleResolver&&e.runs){r=new Map;for(let t of e.runs)if(!r.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&r.set(t.noteId,e)}}let i=wI(e,{noteTitles:r});return EI(t,e.stages,i),i}if(n.target===`segment`||n.target===`event`){let e=n.target,r=await this.service.runFind(n),i=(r.table?.rows??[]).map((t,n)=>TI(t,e,n));return EI(t,r.stages,i),i}let e=await this.service.runFind(n),r=e.notes.map(lI);if(this.noteTagsResolver?(await this.hydrateEntries(r,!1),await Promise.all(r.map(async e=>{if(!e.tags||e.tags.length===0){let t=await this.noteTagsResolver(e.id);t&&t.length>0&&(e.tags=t)}}))):await this.hydrateEntries(r,!0),EI(t,e.stages,r),this.noteBlockInfo)for(let t=0;t<r.length;t++){let n=r[t],i=e.notes[t];n.excerpt=mI(i.rawContent);try{ja(i.rawContent,i.blocks,i.sourceRevision)}catch{continue}let a=Object.values(i.blocks).sort((e,t)=>e.from-t.from).find(e=>e.kind===`wod`),o=a&&Oa(i.rawContent).find(e=>e.from===a.from&&e.scriptBlock);if(a&&o?.scriptBlock){let e=o.scriptBlock.content,t=va(e);n.wodBlock={blockId:a.id,blockVersion:a.version,blockContentId:t,content:e},n.blockContentId=t}}return r}return[]}};async function kI(e,t=OI,n){return t.query(e,n)}function AI(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function jI(e){try{let t=(await kI(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 MI(e){let t=AI(e),n=(0,V.useRef)(e);n.current=e;let[r,i]=(0,V.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,V.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`?jI(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),r}function NI(){let[e]=Gt(`s`,{shallow:!0}),{navState:t}=hA(),n=t.activeL3Id??``;return e||n||``}function PI({entry:e,active:t,onActivate:n}){let r=e.onRun;return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:U(`group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors`,e.muted?`text-[11.5px]`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:U(`hover:bg-muted/60 hover:text-foreground`,e.muted?`text-muted-foreground/70`:`text-muted-foreground`)),children:[e.icon&&(0,H.jsx)(e.icon,{className:`size-4 shrink-0`}),e.timestamp&&(0,H.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60`,children:e.timestamp}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,H.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground/50`,children:e.badge}),r&&(0,H.jsx)(`span`,{role:`button`,tabIndex:-1,title:e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,onClick:t=>{t.stopPropagation(),e.onRun?.()},className:`flex size-5 shrink-0 items-center justify-center rounded text-primary opacity-0 transition-all group-hover:opacity-100 hover:bg-primary/10`,children:e.runIcon===`link`?(0,H.jsx)(l,{className:`size-3.5`}):e.runIcon===`stop`?(0,H.jsx)(b,{className:`size-3.5`}):e.runIcon===`edit`?(0,H.jsx)(o,{className:`size-3.5`}):(0,H.jsx)(rn,{className:`size-3.5`})})]})}function FI({entries:e,activeId:t,onSection:n}){let r=Sn(),{scrollToSection:i}=hA(),a=e=>{if(n)return n(e);if(e.onRun)return e.onRun();if(e.to)return r(e.to);if(e.sectionId)return i(e.sectionId)};return(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,H.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,H.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,H.jsx)(FI,{entries:e.entries,activeId:t,onSection:n})]},e.id):e.kind===`wql`?null:(0,H.jsx)(PI,{entry:e,active:t!=null&&e.sectionId===t,onActivate:a},e.id))})}function II(){let e=Sn(),{scrollToSection:t}=hA();return{navigate:(t,n)=>e(t,{replace:n?.replace}),setQueryParam:(e,t)=>{},scrollToSection:t}}function LI(){let e=II(),{openCreateJournal:t}=hA();return n=>{if(n.id===`home-new-journal`){t({mode:`blank`});return}KM(n.action,e)}}function RI(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 zI({items:e}){let{navState:t}=hA(),n=mt(),r=LI();return(0,H.jsx)(sM,{children:e.map(e=>{if(e.variant===`notable`)return(0,H.jsx)(`div`,{className:`mb-2`,children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`nav-item-${e.id}`,onClick:()=>r(e),className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,H.jsx)(Kt,{className:`size-4 shrink-0`}),(0,H.jsx)(`span`,{children:e.label})]})},e.id);let i=RI(e,t,n);return e.children&&e.children.length>0?(0,H.jsx)(ZM,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>RI(e,t,n)),collapsible:e.id!==`syntax-group`,children:e.children.map(e=>{let i=RI(e,t,n);return(0,H.jsxs)(cM,{onClick:()=>r(e),current:i,children:[e.icon&&(0,H.jsx)(e.icon,{"data-slot":`icon`}),(0,H.jsx)(lM,{children:e.label})]},e.id)})},e.id):(0,H.jsxs)(cM,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:e.disabled?`opacity-60`:void 0,children:[e.icon&&(0,H.jsx)(e.icon,{"data-slot":`icon`}),(0,H.jsx)(lM,{children:e.disabled?`+`:e.label})]},e.id)})})}function BI({navSpec:e}){let{tree:t,navState:n,dispatch:r,contextNav:i}=hA(),a=mt(),o=MI(e),s=(t??[]).find(e=>e?.id===n.activeL1Id)??null,c=i?.pathname===a.pathname?i:null;return(0,H.jsxs)(iM,{children:[(0,H.jsx)(aM,{children:(0,H.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:s?.label??`Wod Wiki`})}),(0,H.jsxs)(oM,{children:[(()=>{if(c||!s)return null;if(s.panel){let e=s.panel;return(0,H.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,H.jsx)(e,{item:s,navState:n,dispatch:r})})}return s.children&&s.children.length>0?(0,H.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,H.jsx)(zI,{items:s.children})}):null})(),c?(0,H.jsx)(`div`,{className:`pt-1`,children:(0,H.jsx)(FI,{entries:c.spec})}):o.length>0&&(0,H.jsx)(`div`,{className:`pt-1`,children:(0,H.jsx)(FI,{entries:o})})]})]})}var VI=`0.41.2146`,HI=`https://github.com/bitcobblers/wod-wiki/releases`;function UI(e){return/-pr\.\d+$/.test(e)?HI:`${HI}/tag/v${e}`}function WI({onSearch:e,onCreate:t}){let{tree:n,navState:r,dispatch:i}=hA(),a=Sn(),o=mt(),s=Qj(),c={navigate:(e,t)=>a(e,{replace:t?.replace}),setQueryParam:()=>{},scrollToSection:()=>{}},l=(n??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),u=o.pathname.startsWith(`/settings`);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(`/`),"aria-label":`Wod Wiki home`,className:`mb-3 grid size-8 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/20 rotate-3`,children:(0,H.jsx)(ce,{size:17})}),(0,H.jsx)(`nav`,{"aria-label":`Primary`,className:`flex flex-col items-center gap-1.5`,children:l.map(e=>{let t=e.icon,n=RI(e,r,o);return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{i({type:`SET_ACTIVE_L1`,id:e.id}),KM(e.action,c)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,className:U(`relative grid size-9 place-items-center rounded-lg transition-colors`,n?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[n&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(t,{className:`size-5`})]},e.id)})}),(0,H.jsx)(`div`,{className:`flex-1`}),(0,H.jsx)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,H.jsx)(en,{className:`size-5`})}),(0,H.jsx)(`a`,{href:WN,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,H.jsx)(GN,{className:`size-5`})}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":o.pathname.startsWith(`/settings/profile`)?`page`:void 0,"data-testid":`nav-profile`,className:U(`relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,o.pathname.startsWith(`/settings/profile`)?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[o.pathname.startsWith(`/settings/profile`)&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(f,{className:`size-5`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":u?`page`:void 0,"data-testid":`nav-settings`,className:U(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,u?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[u&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(Bn,{className:`size-5`}),(0,H.jsxs)(`span`,{role:`tooltip`,className:`pointer-events-none absolute bottom-0 left-full z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 font-mono text-[10px] text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`v`,VI]})]})]})}function GI({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,H.jsx)(`nav`,{className:U(`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,H.jsx)(`button`,{onClick:()=>KM(e.action,r),className:U(`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 KI=(0,V.createContext)(void 0),qI=(0,V.createContext)(null),JI={getState:()=>CF().getState(),setState:(e,t)=>{let n=CF();typeof e==`function`?n.setState(e(n.getState()),t):n.setState(e,t)},subscribe:e=>CF().subscribe(e)},YI=({factory:e,children:t})=>{let[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null),u=(0,V.useRef)(e);u.current=e;let d=(0,V.useRef)(null),f=(0,V.useRef)(null),p=(0,V.useRef)(!1),m=(0,V.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),JI.getState().setSubscriptionManager(null);let e=d.current;if(d.current=null,e)try{u.current.disposeRuntime(e)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime:`,e)}r(null),l(null)},[]),h=(0,V.useCallback)(e=>{if(!p.current){p.current=!0,s(!0),l(null);try{f.current&&=(f.current.dispose(),null);let t=d.current;if(d.current=null,t)try{u.current.disposeRuntime(t)}catch(e){console.error(`[RuntimeProvider] Error disposing existing runtime:`,e)}let n=u.current.createRuntime(e);if(d.current=n,r(n),n){let e=new vf(n);e.add(new _f({id:`local`})),f.current=e,a(e),JI.getState().setSubscriptionManager(e)}else f.current=null,a(null),JI.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,V.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,H.jsx)(KI.Provider,{value:g,children:(0,H.jsx)(qI.Provider,{value:i,children:t})})};function XI({factory:e,children:t}){return(0,H.jsx)(YI,{factory:e,children:t})}var ZI=`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`,QI=`flex flex-col flex-1 min-w-0 xl:max-w-[984px] 2xl:max-w-none min-h-screen lg:rounded-[2.5rem]`;function $I({id:e,title:t,subtitle:n,titleAccessory:r,actions:i,queryBar:a,subheader:o,titleTestId:s,className:c}){return(0,H.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:U(`max-lg:hidden lg:sticky lg:top-0 z-30 bg-background/80 backdrop-blur-md border-b border-border/50 transition-colors`,c),children:[(0,H.jsxs)(`div`,{className:`flex items-start justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,children:[t&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[(0,H.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`h1`,{"data-testid":s,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:t}),n&&(0,H.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:n})]}),r]})]}),a&&(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:a}),i&&(0,H.jsx)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:i})]}),o&&(0,H.jsx)(`div`,{className:`bg-background/40`,children:o})]})}function eL({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,V.useRef)(``),u=(0,V.useRef)(i),d=(0,V.useRef)(a),f=(0,V.useRef)(null),p=(0,V.useRef)(1);(0,V.useEffect)(()=>{u.current=i},[i]),(0,V.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,V.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,V.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,V.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,V.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 tL({title:e,titleAccessory:t,actions:n,subheader:r,children:i,index:a=[],activeSectionId:o,hero:s,sections:c,className:l}){let u=!!(c&&c.length>0)&&!e,[,d]=Gt(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,V.useState)(c?.[0]?.id??``);if(eL({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}),eL({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,H.jsxs)(`div`,{className:U(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,H.jsx)(GI,{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,H.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,H.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,H.jsx)(XI,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,H.jsx)(`div`,{className:U(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,H.jsxs)(`div`,{className:U(QI,ZI),children:[(0,H.jsx)($I,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,H.jsx)(`div`,{className:`flex-1`,children:i})]})})}var nL=`[data-page-sticky-boundary="true"]`,rL=0;function iL(e,t=rL){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(nL)).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 aL(e,t=rL){let[n,r]=(0,V.useState)(e);return(0,V.useEffect)(()=>{let n=0,i=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>r(iL(e,t)))};return i(),window.addEventListener(`scroll`,i,{passive:!0}),window.addEventListener(`resize`,i),()=>{cancelAnimationFrame(n),window.removeEventListener(`scroll`,i),window.removeEventListener(`resize`,i)}},[e,t]),n}function oL({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,H.jsxs)(`div`,{"data-testid":a,className:U(`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,H.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,H.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var sL=(0,V.createContext)(null),cL=(0,V.createContext)(null);function lL({children:e}){let[t,n]=(0,V.useState)(null);return(0,H.jsx)(cL.Provider,{value:n,children:(0,H.jsx)(sL.Provider,{value:t,children:e})})}function uL({className:e}){let t=(0,V.useContext)(cL);return(0,H.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function dL(){return(0,V.useContext)(sL)}function fL({editor:e,title:t,subtitle:n,titleTestId:r,actions:i,timerOverlay:a,reviewOverlay:o,isTimerOpen:s=!1,isReviewOpen:c=!1,onCloseTimer:l,onCloseReview:u,className:d}){return(0,H.jsxs)(`div`,{className:U(`relative flex w-full min-h-screen justify-start items-start`,d),children:[(0,H.jsxs)(`div`,{className:U(QI,ZI),children:[(0,H.jsx)($I,{title:t,subtitle:n,titleTestId:r,actions:i}),(0,H.jsx)(`main`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),s&&a&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,H.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,H.jsx)(`button`,{onClick:l,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:a})]})}),c&&o&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,H.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,H.jsx)(`button`,{onClick:u,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:o})]})})]})}function pL(e){return e.map(e=>{let t=e.action,n=e.secondaryAction?.action,r={kind:`link`,id:e.id,label:e.label,muted:e.level===3&&!!e.secondaryAction};return n&&n.type===`call`&&(r.onRun=n.handler,r.runIcon=e.secondaryRunIcon??`play`),t.type===`route`?{...r,to:t.to}:t.type===`scroll`?{...r,sectionId:t.sectionId}:t.type===`call`?{...r,onRun:t.handler}:r})}var mL=V.createContext(null);function hL(){let e=V.useContext(mL);if(!e)throw Error(`DropdownMenu components must be used inside a DropdownMenu`);return e}var gL=({children:e,open:t,onOpenChange:n})=>{let r=V.useContext(mL),i=V.useId(),a=r?`${r.portalChain}/${i}`:i,[o,s]=V.useState(t??!1),c=V.useRef(null),[l,u]=V.useState(-1),d=V.useRef(new Map),[,f]=V.useReducer(e=>e+1,0);V.useEffect(()=>{t!==void 0&&s(t)},[t]);let p=V.useCallback(e=>{s(e),u(-1),n?.(e)},[n]),m=V.useCallback((e,t)=>{d.current.set(e,t),f()},[]),h=V.useCallback(e=>{d.current.delete(e),f()},[]),g=V.useCallback(e=>Array.from(d.current.keys()).indexOf(e),[]),_=d.current.size,v=V.useMemo(()=>({isOpen:o,setIsOpen:p,triggerRef:c,registerItem:m,unregisterItem:h,getItemIndex:g,activeIndex:l,setActiveIndex:u,itemCount:_,menuId:i,portalChain:a}),[o,p,m,h,g,l,_,i,a]);return(0,H.jsx)(mL.Provider,{value:v,children:(0,H.jsx)(`div`,{ref:c,className:`relative inline-block`,children:e})})},_L=V.forwardRef(({className:e,children:t,asChild:n,...r},i)=>{let{isOpen:a,setIsOpen:o}=hL(),s=e=>{e.stopPropagation(),o(!a)};return n&&V.isValidElement(t)?V.cloneElement(t,{...r,onClick:s}):(0,H.jsx)(`button`,{ref:i,className:e,onClick:s,...r,children:t})});_L.displayName=`DropdownMenuTrigger`;var vL=V.forwardRef(({className:e,children:t,align:n=`center`,side:r=`bottom`,...i},a)=>{let{isOpen:o,setIsOpen:s,triggerRef:c,setActiveIndex:l,itemCount:u,menuId:d,portalChain:f}=hL(),p=V.useRef(null),m=a||p,[h,g]=V.useState({top:0,bottom:0,left:0,width:0});V.useEffect(()=>{if(!o||!c.current)return;let e=c.current.getBoundingClientRect();g({top:e.bottom+8,bottom:window.innerHeight-e.top+8,left:e.left,width:e.width})},[o,c]),V.useEffect(()=>{if(!o||u===0)return;let e=setTimeout(()=>{l(0)},0);return()=>clearTimeout(e)},[o,u,l]),V.useEffect(()=>{if(!o)return;let e=e=>{let t=e.target;if(m.current&&m.current.contains(t)||c.current&&c.current.contains(t))return;let n=t.closest?.(`[data-dropdown-chain]`)?.getAttribute(`data-dropdown-chain`);n&&n.split(`/`).includes(d)||s(!1)},t=setTimeout(()=>{document.addEventListener(`mousedown`,e)},0);return()=>{clearTimeout(t),document.removeEventListener(`mousedown`,e)}},[o,s,m,c,d]);let _=e=>{if(u!==0)switch(e.key){case`ArrowDown`:e.preventDefault(),l(e=>e<u-1?e+1:0);break;case`ArrowUp`:e.preventDefault(),l(e=>e>0?e-1:u-1);break;case`Home`:e.preventDefault(),l(0);break;case`End`:e.preventDefault(),l(u-1);break;case`Escape`:e.preventDefault(),s(!1),c.current?.querySelector(`button`)?.focus();break;case`Tab`:s(!1)}};if(!o)return null;let v={position:`fixed`,zIndex:9999};return r===`top`?v.bottom=h.bottom:v.top=h.top,n===`end`?v.right=window.innerWidth-h.left-h.width:n===`start`?v.left=h.left:(v.left=h.left+h.width/2,v.transform=`translateX(-50%)`),aS.createPortal((0,H.jsx)(`div`,{ref:m,role:`menu`,"data-dropdown-chain":f,className:U(`min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95`,e),style:v,onKeyDown:_,...i,children:t}),document.body)});vL.displayName=`DropdownMenuContent`;var yL=V.forwardRef(({className:e,disabled:t,inset:n,onClick:r,onKeyDown:i,...a},o)=>{let{setIsOpen:s,registerItem:c,unregisterItem:l,getItemIndex:u,activeIndex:d}=hL(),f=V.useId(),p=V.useRef(null),m=V.useCallback(e=>{p.current=e,typeof o==`function`?o(e):o&&(o.current=e)},[o]);V.useEffect(()=>(c(f,p),()=>l(f)),[f,c,l]);let h=u(f)===d;return V.useEffect(()=>{h&&p.current?.focus()},[h]),(0,H.jsx)(`div`,{ref:m,role:`menuitem`,tabIndex:t?-1:h?0:-1,"aria-disabled":t,"data-active":h?`true`:void 0,className:U(`relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors`,`focus:bg-accent focus:text-accent-foreground`,`data-[active]:bg-accent data-[active]:text-accent-foreground`,n&&`pl-8`,t&&`pointer-events-none opacity-50`,e),onClick:e=>{t||(r?.(e),s(!1))},onKeyDown:e=>{t||(i?.(e),(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r?.(e),s(!1)))},...a})});yL.displayName=`DropdownMenuItem`;var bL=V.forwardRef(({className:e,inset:t,...n},r)=>(0,H.jsx)(`div`,{ref:r,className:U(`px-2 py-1.5 text-sm font-semibold`,t&&`pl-8`,e),...n}));bL.displayName=`DropdownMenuLabel`;var xL=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`-mx-1 my-1 h-px bg-muted`,e),...t}));xL.displayName=`DropdownMenuSeparator`;function SL({className:e,children:t,...n}){return(0,H.jsx)(`div`,{className:U(`px-2 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,e),...n,children:t})}var CL=[{label:`Past 1 week`,value:`last 1w`},{label:`Past 2 weeks`,value:`last 2w`},{label:`Past 4 weeks`,value:`last 4w`},{label:`Past 8 weeks`,value:`last 8w`},{label:`Past 12 weeks`,value:`last 12w`},{label:`Past 1 year`,value:`last 52w`},{label:`All time`,value:`all`}],wL=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function TL(e,t){return new Date(e,t+1,0).getDate()}function EL(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function DL(e,t){let n=Y(e);if(n.error)return e;if(!t||t===`all`)return Km({...n,window:void 0});let r=Y(`:note ${t}`);return r.error||r.family!==`find`||!r.window?e:Km({...n,window:r.window})}function OL(e){let t=Y(e);return t.error||t.family===`pipeline`?null:`window`in t?t.window??null:null}function kL({query:e,onQueryChange:t,highlightDates:n=new Set,className:r}){let i=(0,V.useMemo)(()=>OL(e),[e]),[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(()=>new Date),l=s.getFullYear(),u=s.getMonth(),d=(0,V.useMemo)(()=>i?i.kind===`relative`?`last ${i.size}${i.unit}`:i.end?`from ${i.start} to ${i.end}`:`from ${i.start}`:`All time`,[i]),f=(0,V.useMemo)(()=>{if(!i)return null;if(i.kind===`range`)return{start:i.start,end:i.end??i.start};let e=new Date,t=new Date;return i.unit===`d`?t.setDate(e.getDate()-i.size):t.setDate(e.getDate()-i.size*7),{start:Bj(t),end:Bj(e)}},[i]),p=(0,V.useMemo)(()=>{let e=TL(l,u),t=EL(l,u),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[l,u]),m=n=>{if(!a)o(n),t(DL(e,`from ${n} to ${n}`));else{let[r,i]=a<=n?[a,n]:[n,a];o(null),t(DL(e,`from ${r} to ${i}`))}},h=e=>{e.stopPropagation(),c(new Date(l,u-1,1))},g=e=>{e.stopPropagation(),c(new Date(l,u+1,1))},_=s.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),v=Bj(new Date);return(0,H.jsxs)(`div`,{className:U(`relative inline-flex items-center`,r),children:[(0,H.jsxs)(gL,{children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`wql-window-picker-trigger`,className:`flex h-9 items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,H.jsx)(qt,{className:`size-3.5 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`font-mono text-xs`,children:d}),(0,H.jsx)(un,{className:`size-3 text-muted-foreground`,"aria-hidden":`true`})]})}),(0,H.jsxs)(vL,{align:`end`,className:`w-72 p-3`,children:[(0,H.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-1 border-b border-border/60 pb-2`,children:CL.map(n=>{let r=n.value===`all`?!i:i?.kind===`relative`&&`last ${i.size}${i.unit}`===n.value;return(0,H.jsx)(`button`,{type:`button`,"data-testid":`wql-window-preset-${n.value}`,onClick:()=>{o(null),t(DL(e,n.value))},className:U(`rounded-md px-2 py-1 text-[11px] font-medium transition-colors`,r?`bg-primary text-primary-foreground`:`bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground`),children:n.label},n.value)})}),(0,H.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:h,"data-testid":`wql-calendar-prev-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,H.jsx)(Tt,{className:`size-4`})}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:_}),(0,H.jsx)(`button`,{type:`button`,onClick:g,"data-testid":`wql-calendar-next-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,H.jsx)(Vn,{className:`size-4`})})]}),(0,H.jsx)(`div`,{className:`mb-1 grid grid-cols-7 gap-1`,children:wL.map(e=>(0,H.jsx)(`div`,{className:`text-center text-[10px] font-medium text-muted-foreground`,children:e},e))}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-1`,"data-testid":`wql-calendar-grid`,children:p.map((e,t)=>{if(e===null)return(0,H.jsx)(`div`,{className:`size-8`},`empty-${t}`);let r=`${l}-${String(u+1).padStart(2,`0`)}-${String(e).padStart(2,`0`)}`,i=f&&r>=f.start&&r<=f.end,o=f&&r===f.start||a===r,s=f&&r===f.end,c=r===v,d=n.has(r);return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`wql-calendar-day-${r}`,onClick:()=>m(r),className:U(`relative flex size-8 items-center justify-center rounded-md text-xs transition-colors`,o||s?`bg-primary font-bold text-primary-foreground`:i?`bg-primary/15 font-semibold text-primary`:c?`border border-primary font-semibold text-primary`:`text-foreground hover:bg-muted`),children:[(0,H.jsx)(`span`,{children:e}),d&&!o&&!s&&(0,H.jsx)(`span`,{className:`absolute bottom-0.5 size-1 rounded-full bg-primary`})]},r)})}),a&&(0,H.jsxs)(`div`,{className:`mt-2 text-center text-[10px] text-muted-foreground`,children:[`Select second date to complete range (starting from `,a,`)`]})]})]}),i&&(0,H.jsx)(`button`,{type:`button`,"data-testid":`wql-window-picker-clear`,onClick:()=>{o(null),t(DL(e,null))},title:`Clear time window`,"aria-label":`Clear time window`,className:`ml-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3.5`})})]})}function AL(e){switch(e.kind){case`note`:case`post`:return`note`;case`session`:return`session`;case`result`:return`result`;case`segment`:case`event`:return`segment`;case`effort`:return`effort`;default:return`note`}}var jL=[{id:`title`,label:`Title`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`tags`,label:`Tags`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.tags??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)},{id:`excerpt`,label:`Text Excerpt`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.preview?.join(` `)||e.detail||``,formatValue:e=>String(e??``)},{id:`catalog`,label:`Catalog Source`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.sourceCatalog,formatValue:e=>String(e??``)},{id:`date`,label:`Date`,level:`note`,defaultVisible:!0,align:`right`,getValue:e=>e.date,formatValue:e=>String(e??``)}],ML={note:jL,session:[{id:`title`,label:`Title`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`protocol`,label:`Protocol`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.dataType||e.subtitle||``,formatValue:e=>String(e??``)},{id:`movements`,label:`Movements`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.detail||``,formatValue:e=>String(e??``)},{id:`targetDuration`,label:`Target Duration`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`sessionLoad`,label:`Session Load`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``}],result:[{id:`title`,label:`Title`,level:`result`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`elapsedTime`,label:`Elapsed Time`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`totalTonnage`,label:`Total Tonnage`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`tis`,label:`TIS Score`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.tis,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`prBadges`,label:`PR Badges`,level:`result`,defaultVisible:!0,align:`center`,getValue:e=>e.detail&&/\bPR\b/.test(e.detail)?`PR`:``,formatValue:e=>String(e??``)}],segment:[{id:`splitDuration`,label:`Split Duration`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`roundIndex`,label:`Round/Lap Index`,level:`segment`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`reps`,label:`Reps`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.reps,formatValue:e=>e==null?``:String(e)},{id:`load`,label:`Load`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`pacingTier`,label:`Pacing / HR Tier`,level:`segment`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier||e.execution?.effortSlug||``,formatValue:e=>String(e??``)}],effort:[{id:`label`,label:`Label`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.label||e.title,formatValue:e=>String(e??``)},{id:`canonicalSlug`,label:`Canonical Slug`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.slug||e.id,formatValue:e=>String(e??``)},{id:`discipline`,label:`Discipline`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.discipline??``,formatValue:e=>String(e??``)},{id:`met`,label:`MET Score`,level:`effort`,defaultVisible:!0,align:`right`,getValue:e=>e.effort?.met,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`intensityTier`,label:`Intensity Tier`,level:`effort`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier??``,formatValue:e=>String(e??``)},{id:`aliases`,label:`Aliases`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.aliases??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)}]};function NL(e){return ML[e]??jL}function PL(e){return NL(e).filter(e=>e.defaultVisible).map(e=>e.id)}var FL=[{id:`cards`,label:`Cards`,icon:s},{id:`rows`,label:`Rows`,icon:oe},{id:`feed`,label:`Feed`,icon:Rt}];function IL({streamControls:e}){return(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`l3-stream-controls`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date window`}),(0,H.jsx)(kL,{query:e.query,onQueryChange:e.onQueryChange,className:`w-full justify-between`})]}),e.availableGroupDims.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Group by`}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-groupby-options`,children:e.availableGroupDims.map(t=>{let n=e.groupDims.some(e=>e.toLowerCase()===t.id.toLowerCase());return(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-groupby-${t.id}`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleGroupDim(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,H.jsx)(`span`,{children:t.label})]},t.id)})})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Layout`}),(0,H.jsx)(`div`,{className:`grid grid-cols-3 gap-1`,"data-testid":`l3-layout-options`,children:FL.map(t=>{let n=t.icon,r=e.settings.layout===t.id;return(0,H.jsxs)(`button`,{type:`button`,"aria-pressed":r,onClick:()=>e.onLayoutChange(t.id),"data-testid":`l3-layout-${t.id}`,className:`flex min-h-8 items-center justify-center gap-1 rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors ${r?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[(0,H.jsx)(n,{"aria-hidden":!0,className:`size-3`}),t.label]},t.id)})})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Fields`}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-field-options`,children:NL(e.level).map(t=>{let n=e.settings.visibleFields.includes(t.id);return(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-field-${t.id}`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleField(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,H.jsx)(`span`,{children:t.label})]},t.id)})})]})]})}function LL({spec:e,pageAction:t}){let{l3Items:n,streamControls:r}=hA(),i=MI(e),a=(0,V.useMemo)(()=>pL(n),[n]),o=NI();return i.length===0&&a.length===0&&!r&&!t?null:(0,H.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[r&&(0,H.jsx)(`div`,{className:`pb-3 border-b border-border/50`,children:(0,H.jsx)(IL,{streamControls:r})}),i.length>0&&(0,H.jsx)(FI,{entries:i,activeId:o}),a.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col`,children:[(0,H.jsx)(`div`,{className:`px-2 pb-1 pt-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,H.jsx)(FI,{entries:a,activeId:o})]}),t&&(0,H.jsx)(`div`,{className:`pt-2 border-t border-border/50`,children:t})]})}var RL=1023;function zL(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function BL(e,t){if(e===`query:new`)return``;let n=e=>{let n=`/${e}`;for(let r of Object.keys(t))if(r===e||r.endsWith(n))return r;return null},r=e=>{let r=n(e);return r===null?null:Db(t[r])};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i=e;if(e.startsWith(`wods/examples/`))i=`markdown/canvas/`+e.replace(/^wods\/examples\//,``);else if(e.startsWith(`wods/`))i=`markdown/canvas/`+e.replace(/^wods\//,``);else if(e.startsWith(`collections/`))i=`markdown/collections/`+e.replace(/^collections\//,``);else if(e.startsWith(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;let n=r(`markdown/collections/`+e);if(n!==null)return n;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function VL(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function HL(e){let t=new Map,n=null;for(let r of e)VL(r)&&(n=r),t.set(r.id,n);return t}function UL(){let[e,t]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${RL}px)`).matches);return(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${RL}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var WL=`wodwiki:fabAlignment`,GL=[{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 KL(){try{return qL(localStorage.getItem(WL))}catch{return}}function qL(e){return e===`right`||e===`left`?e:void 0}var JL=typeof window>`u`?void 0:KL();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===WL&&(JL=qL(e.newValue))});function YL(e){JL=e;try{e===`right`?localStorage.removeItem(WL):localStorage.setItem(WL,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:WL,newValue:e}))}function XL(){let[e,t]=(0,V.useState)(()=>JL??`right`);return(0,V.useEffect)(()=>{let e=e=>{e.key===WL&&t(qL(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,YL]}function ZL({onOpen:e}){return(0,H.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,"data-testid":`search-fab`,className:U(`size-14 rounded-full flex items-center justify-center`,`bg-primary text-primary-foreground shadow-lg`,`hover:bg-primary/90 active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:(0,H.jsx)(en,{className:`size-6`})})}var QL=(0,V.createContext)(null),$L=(0,V.createContext)(!1),eR=(0,V.createContext)(null);function tR(){return(0,V.useContext)(QL)!==null}function nR({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,V.useContext)(QL),o=(0,V.useContext)($L),s=UL(),c=(0,V.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=(0,H.jsx)($L.Provider,{value:!0,children:n});return(0,V.useEffect)(()=>{if(!(!l&&!u))return a.register({id:c,primary:e,navbar:t,children:d,label:r??`Page options`,fallback:i}),()=>a.unregister(c)},[l,u,a,c,e,d,r,i]),i||a&&s&&!o?null:(0,H.jsx)($L.Provider,{value:!0,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function rR({onSearch:e,children:t}){let[n,r]=(0,V.useState)([]),i=(0,V.useCallback)(e=>r(t=>[...t.filter(t=>t.id!==e.id),e]),[]),a=(0,V.useCallback)(e=>r(t=>t.filter(t=>t.id!==e)),[]),o=(0,V.useMemo)(()=>({register:i,unregister:a}),[i,a]),s=(0,V.useMemo)(()=>{for(let e=n.length-1;e>=0;--e)if(!n[e].fallback)return n[e].navbar??null;return null},[n]);return(0,H.jsx)(QL.Provider,{value:o,children:(0,H.jsxs)(eR.Provider,{value:s,children:[t,(0,H.jsx)(aR,{registrations:n,onSearch:e})]})})}function iR(){let e=(0,V.useContext)(eR);return e?(0,H.jsx)(H.Fragment,{children:e}):null}function aR({registrations:e,onSearch:t}){let n=UL(),[r]=XL(),i=sS(),[a,o]=(0,V.useState)(!1),s=(0,V.useRef)(null),c=mt(),[l,u]=(0,V.useState)(!1),d=(0,V.useRef)(0),f=i.offsetBottom>0,p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),g=(0,V.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]);(0,V.useEffect)(()=>{o(!1),u(!1),d.current=window.scrollY},[c.pathname]),(0,V.useEffect)(()=>{if(!n)return;let e=()=>{let e=window.scrollY;if(e<=0||f||a){d.current=e,u(!1);return}let t=e-d.current;Math.abs(t)<8||(d.current=e,u(t>0))};return window.addEventListener(`scroll`,e,{passive:!0}),()=>window.removeEventListener(`scroll`,e)},[n,f,a]),(0,V.useLayoutEffect)(()=>{a&&s.current?.focus()},[a]);let[_,v]=(0,V.useState)({active:0,global:0});(0,V.useLayoutEffect)(()=>{let e=p.current?.childElementCount??0,t=m.current?.childElementCount??0;v(n=>n.active===e&&n.global===t?n:{active:e,global:t})},[h,g]);let y=_.active>0||_.global>0;return!n||!t&&!h&&!g?null:(0,H.jsxs)(`div`,{"data-testid":`actions-dock`,className:U(`lg:hidden fixed z-40 flex flex-col items-center gap-2`,`transition-[transform,visibility] duration-200 ease-out`,r===`left`?`left-4 items-start`:`right-4 items-end`,l&&!a&&!f&&`translate-y-[calc(100%+2rem)] invisible pointer-events-none`),style:{bottom:`calc(1rem + var(--thumb-dock-lift, 0px) + ${i.offsetBottom}px + env(safe-area-inset-bottom))`},children:[(0,H.jsxs)(`div`,{className:`relative z-40 flex flex-col items-center gap-2`,children:[h?.primary&&(0,H.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:h.primary}),t&&(0,H.jsx)(ZL,{onOpen:()=>{o(!1),t()}})]}),a&&y&&(0,H.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 cursor-default`,onClick:()=>o(!1)}),(0,H.jsxs)(`div`,{ref:s,role:`dialog`,"aria-label":h?.label??g?.label??`Page options`,tabIndex:-1,hidden:!a||!y,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),o(!1))},className:U(`relative z-40 flex w-60 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/5 outline-none`,`[&_button]:min-h-11 [&_button]:min-w-11`),style:{maxHeight:`calc(${i.height===null?`100dvh`:`${i.height}px`} - 6rem - env(safe-area-inset-bottom))`},children:[(0,H.jsx)(`div`,{ref:p,className:`contents`,children:h?.children}),_.active>0&&_.global>0&&(0,H.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,H.jsx)(`div`,{ref:m,className:`contents`,children:g?.children})]}),y&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-label":h?.label??g?.label??`Page options`,"aria-expanded":a,"data-testid":`actions-overflow`,className:U(`relative z-40 flex size-12 items-center justify-center rounded-full`,`bg-card text-foreground shadow-lg ring-1 ring-foreground/10`,`hover:bg-muted active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:a?(0,H.jsx)(Re,{className:`size-6`}):(0,H.jsx)(ge,{className:`size-6`})})]})}function oR(){return(0,H.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,H.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 sR(){return(0,H.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,H.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 cR(){let{tree:e,navState:t,contextNav:n}=hA(),r=mt(),i=Qj();return!e.find(e=>e.id===t.activeL1Id)?.applyFooter||n?.pathname===r.pathname?null:(0,H.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:i,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})}function lR({open:e,close:t,onSearch:n,onCreate:r,children:i}){return(0,H.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,H.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,H.jsx)(A,{transition:!0,className:`fixed inset-y-0 left-0 w-full transition duration-300 ease-out data-closed:-translate-x-full`,children:(0,H.jsx)(Zj,{close:t,children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,H.jsx)(`div`,{className:`flex h-full w-14 shrink-0 flex-col items-center border-r border-zinc-950/5 bg-background/72 py-3 dark:border-white/5 [&_a]:size-11 [&_button]:size-11`,children:(0,H.jsx)(WI,{onSearch:()=>{t(),n?.()},onCreate:r?()=>{t(),r()}:void 0})}),(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,H.jsx)(`div`,{className:`flex items-center px-4 pt-3`,children:(0,H.jsx)(rt,{as:PP,"aria-label":`Close navigation`,children:(0,H.jsx)(sR,{})})}),(0,H.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i}),(0,H.jsx)(cR,{})]})]})})})]})}function uR({open:e,close:t,children:n}){return(0,H.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,H.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,H.jsx)(A,{transition:!0,className:`fixed inset-y-0 right-0 w-full transition duration-300 ease-out data-closed:translate-x-full`,children:(0,H.jsx)(Zj,{close:t,children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-card`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-end px-4 pt-3`,children:(0,H.jsx)(rt,{as:PP,"aria-label":`Close page options`,children:(0,H.jsx)(sR,{})})}),(0,H.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:n}),(0,H.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})]})})})]})}function dR({navbar:e,sidebar:t,onSearch:n,onCreate:r,secondary:i,pageAction:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,V.useState)(!1),[u,d]=(0,V.useState)(!1),f=(0,V.useRef)(null),[p,m]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>m(t=>{let n=e.childElementCount>0;return t===n?t:n}),n=new MutationObserver(t);return n.observe(e,{childList:!0,subtree:!0}),t(),()=>n.disconnect()},[]);let{streamControls:h}=hA(),g=(0,V.useMemo)(()=>{let e=Y(h?.query??``);return!e.error&&tm(e)&&e.filters.length>0},[h?.query]);return(0,H.jsx)(lL,{children:(0,H.jsx)(rR,{onSearch:n,children:(0,H.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,H.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,H.jsxs)(`nav`,{"aria-label":`Main`,className:`hidden lg:flex`,children:[(0,H.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,H.jsx)(WI,{onSearch:n??(()=>{}),onCreate:r})}),(0,H.jsx)(`div`,{className:U(`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,H.jsx)(lR,{open:c,close:()=>l(!1),onSearch:n,onCreate:r,children:t}),(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col min-w-0 xl:max-w-[984px] 2xl:max-w-none`,children:[(0,H.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 border-b border-border/50`,children:[(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:()=>l(!0),"aria-label":`Open navigation`,children:(0,H.jsx)(oR,{})})}),(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),r&&(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:r,"aria-label":`New journal note`,children:(0,H.jsx)(Ut,{className:`size-5`})})}),p&&(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:()=>d(!0),"aria-label":`Open page options`,children:(0,H.jsxs)(`span`,{className:`relative inline-flex`,children:[(0,H.jsx)(Zt,{className:`size-5`}),g&&(0,H.jsx)(`span`,{"data-testid":`drawer-filters-active`,className:`absolute -top-1 -right-1 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`})]})})})]}),(0,H.jsxs)(`main`,{className:`flex flex-1 flex-col lg:min-w-0`,children:[(0,H.jsx)(`div`,{className:`grow w-full max-lg:pb-48 lg:overflow-visible`,children:s}),(0,H.jsx)(fR,{})]})]}),(0,H.jsx)(`aside`,{className:`hidden 2xl:flex w-60 shrink-0 sticky top-0 h-svh flex-col overflow-y-auto bg-background/72 backdrop-blur-sm`,children:(0,H.jsx)(`div`,{ref:f,className:`contents`,children:(0,H.jsx)(LL,{spec:i,pageAction:a})})}),(0,H.jsx)(uR,{open:u,close:()=>d(!1),children:(0,H.jsx)(LL,{spec:i,pageAction:a})})]})})})})}function fR(){let e=(0,V.useRef)(null),[t,n]=(0,V.useState)(0);return(0,V.useEffect)(()=>{let t=e.current;if(!t)return;let r=new ResizeObserver(e=>{let t=Math.round(e[0]?.contentRect.height??0);n(e=>e===t?e:t)});r.observe(t,{box:`content-box`});let i=Math.round(t.getBoundingClientRect().height);return n(e=>e===i?e:i),()=>r.disconnect()},[]),(0,V.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${t}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[t]),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`lg:hidden fixed inset-x-0 bottom-0 z-30`,t>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,H.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,H.jsx)(uL,{className:`flex w-full min-w-0`})})}),(0,H.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:t}})]})}function pR(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function mR(e){return String(Ob(Sb(e).meta,`search`)??``).toLowerCase()===`hidden`}function hR(e){let t=Ob(Sb(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 gR(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=Ob(Sb(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():zE(r),category:pR(n),content:i,date:hR(i),searchHidden:mR(i)}})}function _R(){let e=sD();return(0,V.useMemo)(()=>e?gR(e):[],[e])}var vR={};function yR(e){if(!(`payload`in e))return;let t=e.payload;if(!t||typeof t!=`object`)return;let n=t;return n.targetDate??n.updatedAt}function bR(e,t){let{canvasPage:n,workoutItems:r,recentResults:i,selectWorkout:a}=t;if(n){let t=/^\/(?:c|collections)\//.test(e),i=t?e.split(`/`).pop()??null:null;if(e===`/`)return[];let o=[],s=e.startsWith(`/guide/`);return n.sections.filter(e=>e.level>1).forEach(e=>{if(o.push({id:e.id,label:e.heading,type:`heading`}),!s){let t=nP(e).split(`
100
+ `).map(e=>e.trim()).filter(Boolean).slice(0,fI).map(e=>e.length>pI?`${e.slice(0,119)}…`:e)}function hI(e){let t=lI(dI(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,catalog:gg(e),block:{blockId:e.blockId,dataType:e.dataType,preview:mI(e.rawContent)}}}function gI(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 _I(e){if(!Number.isFinite(e)||e<=0)return`00:00`;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;if(n>=60){let e=Math.floor(n/60),t=n%60;return`${e}:${String(t).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function vI(e){if(!e)return`Workout Session`;let t=ZF(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?gI(t.id)||t.id:t.id?gI(t.id):e}function yI(e){let t=[e.baseAttributes?.discipline,e.baseAttributes?.met==null?void 0:`MET ${e.baseAttributes.met.toFixed(1)}`,e.baseAttributes?.intensityTier].filter(Boolean);return{id:e.slug,kind:`effort`,sourceCatalog:e.registrySource??`effort`,sourceItem:e.slug,title:e.label,date:null,subtitle:t.join(` • `),detail:e.aliases&&e.aliases.length>0?`Aliases: ${e.aliases.join(`, `)}`:void 0,effort:{slug:e.slug,label:e.label,discipline:e.baseAttributes?.discipline,met:e.baseAttributes?.met,intensityTier:e.baseAttributes?.intensityTier,aliases:e.aliases,registrySource:e.registrySource}}}function bI(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.value==`number`?e.value:Number(e.value);return Number.isFinite(r)?t===`rep`||n===`reps`||n===`rep`?{kind:`rep`,val:r}:t===`weight`||t===`load`||n===`load`||n===`weight`||n===`volume`?{kind:`load`,val:r}:t===`distance`||n===`distance`?{kind:`distance`,val:r}:t===`tis`||n===`tis`?{kind:`tis`,val:r}:t===`duration`||n===`duration`?{kind:`duration`,val:r}:null:null}function xI(e){let t=1/0,n=-1/0,r=0,i=0,a=0,o=0,s=new Set;for(let c of e.events)if(c.outputType===`segment`&&o++,c.effortSlug&&s.add(c.effortSlug),c.timeSpan?.started!=null&&(c.timeSpan.started<t&&(t=c.timeSpan.started),c.timeSpan.ended!=null&&c.timeSpan.ended>n&&(n=c.timeSpan.ended)),Array.isArray(c.metrics))for(let e of c.metrics){let t=bI(e);t&&(t.kind===`rep`?r+=t.val:t.kind===`load`?i+=t.val:t.kind===`tis`&&t.val>a&&(a=t.val))}return{elapsedMs:Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,reps:r>0?r:void 0,loadLbs:i>0?i:void 0,tis:a>0?a:void 0,segmentCount:o>0?o:void 0,effortSlugs:Array.from(s)}}function SI(e,t){let n=xI(e),r=[];n.elapsedMs!=null&&r.push(_I(n.elapsedMs)),n.tis!=null&&r.push(`TIS ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${n.loadLbs.toLocaleString()} lbs`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`);let i=n.effortSlugs.map(gI),a=Bj(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;return{id:e.resultId,kind:`result`,sourceCatalog:`results`,sourceItem:e.resultId,title:t?.noteTitle??vI(e.noteId),date:a,blockContentId:o,subtitle:r.join(` • `),detail:i.length>0?i.join(`, `):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:`all`,elapsedMs:n.elapsedMs,reps:n.reps,loadLbs:n.loadLbs,tis:n.tis,segmentCount:n.segmentCount,events:e.events}}}function CI(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=bI(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`?i=e.val:e.kind===`distance`?a=e.val:e.kind===`tis`?o=e.val:e.kind===`duration`&&!n&&(n=e.val))}let s=e.outputType===`segment`?`segment`:`event`,c=t?.index??0,l=e.effortSlug?gI(e.effortSlug):e.outputType===`segment`?`Round ${c+1}`:`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${c+1}`,u=[];n!=null&&u.push(_I(n)),r!=null&&i!=null?u.push(`${r} reps @ ${i} lbs`):r==null?i!=null&&u.push(`${i} lbs`):u.push(`${r} reps`),a!=null&&u.push(`${a}m`),o!=null&&u.push(`TIS ${o.toFixed(1)}`);let d=Bj(new Date(e.timestamp));return{id:e.id,kind:s,sourceCatalog:`results`,sourceItem:e.id,title:l,date:d,blockContentId:e.blockContentId,subtitle:u.join(` • `),detail:e.effortSlug?gI(e.effortSlug):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:e.outputType,effortSlug:e.effortSlug,elapsedMs:n,reps:r,loadLbs:i,distanceMeters:a,tis:o,metrics:e.metrics}}}function wI(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(CI(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(CI(i,{index:e++}))}return t}return e.runs.map(e=>SI(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function TI(e,t,n){let r=typeof e.__id==`string`&&e.__id?e.__id:void 0,i=typeof e.__resultId==`string`&&e.__resultId?e.__resultId:void 0,a=typeof e.effort==`string`&&e.effort?e.effort:void 0,o=[];for(let[t,n]of Object.entries(e))t.startsWith(`__`)||t===`date`||t===`effort`||(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&o.push(`${t}: ${n}`);return{id:r??i??`${t}:${n}`,kind:t,sourceCatalog:`results`,sourceItem:i??r??`${t}:${n}`,title:a?gI(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function EI(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function DI(e){return typeof e==`object`&&!!e&&`runFind`in e}var OI=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){DI(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver)}get service(){return this.customService??XF}withNoteBlockInfo(){let t=new e({service:this.service,noteTitleResolver:this.noteTitleResolver,noteTagsResolver:this.noteTagsResolver,noteBlockInfo:!0});return Object.prototype.hasOwnProperty.call(this,`query`)&&(t.query=this.query),t}async hydrateEntries(e,t){let n=e=>e.noteId??e.id,r=new Set;for(let i of e)i.sourceCatalog===`journal`&&r.add(n(i)),t&&(!i.title||!i.tags||i.tags.length===0)&&r.add(n(i));if(r.size===0)return;let i=await X.getEntryBatches([...r]);for(let t of e){if(t.sourceCatalog!==`journal`)continue;let e=i.get(n(t)),r=[...e?.links??[]].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt);for(let n of r){let r=e?.pages.find(e=>e.id===n.pageId);if(r&&(t.pageId??=r.id,!r.date&&r.slug)){t.pageSlug=r.slug;break}}}if(t)for(let t of e){let e=i.get(n(t));!t.title&&e?.note.title&&(t.title=e.note.title),e&&e.tags.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.tags.map(e=>e.label)),t.typedTags=e.tags.map(e=>({label:e.label,type:e.type})))}}async query(e,t){let n=typeof e==`string`?Y(e):e;if(!n||n.error)return[];if(tm(n)){if(n.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(n):await this.service.runFind(n),r=(e.efforts??[]).map(yI);return EI(t,e.stages,r),r}if(n.target===`block`){let e=await this.service.runFind(n),r=e.blocks.map(hI);return await this.hydrateEntries(r,!0),EI(t,e.stages,r),r}if(n.target===`session`){let e=await this.service.runFind(n);t?.(e.stages);let r;if(this.noteTitleResolver&&e.runs){r=new Map;for(let t of e.runs)if(!r.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&r.set(t.noteId,e)}}let i=wI(e,{noteTitles:r});return EI(t,e.stages,i),i}if(n.target===`segment`||n.target===`event`){let e=n.target,r=await this.service.runFind(n),i=(r.table?.rows??[]).map((t,n)=>TI(t,e,n));return EI(t,r.stages,i),i}let e=await this.service.runFind(n),r=e.notes.map(lI);if(this.noteTagsResolver?(await this.hydrateEntries(r,!1),await Promise.all(r.map(async e=>{if(!e.tags||e.tags.length===0){let t=await this.noteTagsResolver(e.id);t&&t.length>0&&(e.tags=t)}}))):await this.hydrateEntries(r,!0),EI(t,e.stages,r),this.noteBlockInfo)for(let t=0;t<r.length;t++){let n=r[t],i=e.notes[t];n.excerpt=mI(i.rawContent);try{ja(i.rawContent,i.blocks,i.sourceRevision)}catch{continue}let a=Object.values(i.blocks).sort((e,t)=>e.from-t.from).find(e=>e.kind===`wod`),o=a&&Oa(i.rawContent).find(e=>e.from===a.from&&e.scriptBlock);if(a&&o?.scriptBlock){let e=o.scriptBlock.content,t=va(e);n.wodBlock={blockId:a.id,blockVersion:a.version,blockContentId:t,content:e},n.blockContentId=t}}return r}return[]}};async function kI(e,t=OI,n){return t.query(e,n)}function AI(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function jI(e){try{let t=(await kI(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 MI(e){let t=AI(e),n=(0,V.useRef)(e);n.current=e;let[r,i]=(0,V.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,V.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`?jI(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),r}function NI(){let[e]=Gt(`s`,{shallow:!0}),{navState:t}=hA(),n=t.activeL3Id??``;return e||n||``}function PI({entry:e,active:t,onActivate:n}){let r=e.onRun;return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:U(`group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors`,e.muted?`text-[11.5px]`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:U(`hover:bg-muted/60 hover:text-foreground`,e.muted?`text-muted-foreground/70`:`text-muted-foreground`)),children:[e.icon&&(0,H.jsx)(e.icon,{className:`size-4 shrink-0`}),e.timestamp&&(0,H.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60`,children:e.timestamp}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,H.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground/50`,children:e.badge}),r&&(0,H.jsx)(`span`,{role:`button`,tabIndex:-1,title:e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,onClick:t=>{t.stopPropagation(),e.onRun?.()},className:`flex size-5 shrink-0 items-center justify-center rounded text-primary opacity-0 transition-all group-hover:opacity-100 hover:bg-primary/10`,children:e.runIcon===`link`?(0,H.jsx)(l,{className:`size-3.5`}):e.runIcon===`stop`?(0,H.jsx)(b,{className:`size-3.5`}):e.runIcon===`edit`?(0,H.jsx)(o,{className:`size-3.5`}):(0,H.jsx)(rn,{className:`size-3.5`})})]})}function FI({entries:e,activeId:t,onSection:n}){let r=Sn(),{scrollToSection:i}=hA(),a=e=>{if(n)return n(e);if(e.onRun)return e.onRun();if(e.to)return r(e.to);if(e.sectionId)return i(e.sectionId)};return(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,H.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,H.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,H.jsx)(FI,{entries:e.entries,activeId:t,onSection:n})]},e.id):e.kind===`wql`?null:(0,H.jsx)(PI,{entry:e,active:t!=null&&e.sectionId===t,onActivate:a},e.id))})}function II(){let e=Sn(),{scrollToSection:t}=hA();return{navigate:(t,n)=>e(t,{replace:n?.replace}),setQueryParam:(e,t)=>{},scrollToSection:t}}function LI(){let e=II(),{openCreateJournal:t}=hA();return n=>{if(n.id===`home-new-journal`){t({mode:`blank`});return}KM(n.action,e)}}function RI(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 zI({items:e}){let{navState:t}=hA(),n=mt(),r=LI();return(0,H.jsx)(sM,{children:e.map(e=>{if(e.variant===`notable`)return(0,H.jsx)(`div`,{className:`mb-2`,children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`nav-item-${e.id}`,onClick:()=>r(e),className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,H.jsx)(Kt,{className:`size-4 shrink-0`}),(0,H.jsx)(`span`,{children:e.label})]})},e.id);let i=RI(e,t,n);return e.children&&e.children.length>0?(0,H.jsx)(ZM,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>RI(e,t,n)),collapsible:e.id!==`syntax-group`,children:e.children.map(e=>{let i=RI(e,t,n);return(0,H.jsxs)(cM,{onClick:()=>r(e),current:i,children:[e.icon&&(0,H.jsx)(e.icon,{"data-slot":`icon`}),(0,H.jsx)(lM,{children:e.label})]},e.id)})},e.id):(0,H.jsxs)(cM,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:e.disabled?`opacity-60`:void 0,children:[e.icon&&(0,H.jsx)(e.icon,{"data-slot":`icon`}),(0,H.jsx)(lM,{children:e.disabled?`+`:e.label})]},e.id)})})}function BI({navSpec:e}){let{tree:t,navState:n,dispatch:r,contextNav:i}=hA(),a=mt(),o=MI(e),s=(t??[]).find(e=>e?.id===n.activeL1Id)??null,c=i?.pathname===a.pathname?i:null;return(0,H.jsxs)(iM,{children:[(0,H.jsx)(aM,{children:(0,H.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:s?.label??`Wod Wiki`})}),(0,H.jsxs)(oM,{children:[(()=>{if(c||!s)return null;if(s.panel){let e=s.panel;return(0,H.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,H.jsx)(e,{item:s,navState:n,dispatch:r})})}return s.children&&s.children.length>0?(0,H.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,H.jsx)(zI,{items:s.children})}):null})(),c?(0,H.jsx)(`div`,{className:`pt-1`,children:(0,H.jsx)(FI,{entries:c.spec})}):o.length>0&&(0,H.jsx)(`div`,{className:`pt-1`,children:(0,H.jsx)(FI,{entries:o})})]})]})}var VI=`0.42.2147`,HI=`https://github.com/bitcobblers/wod-wiki/releases`;function UI(e){return/-pr\.\d+$/.test(e)?HI:`${HI}/tag/v${e}`}function WI({onSearch:e,onCreate:t}){let{tree:n,navState:r,dispatch:i}=hA(),a=Sn(),o=mt(),s=Qj(),c={navigate:(e,t)=>a(e,{replace:t?.replace}),setQueryParam:()=>{},scrollToSection:()=>{}},l=(n??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),u=o.pathname.startsWith(`/settings`);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(`/`),"aria-label":`Wod Wiki home`,className:`mb-3 grid size-8 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/20 rotate-3`,children:(0,H.jsx)(ce,{size:17})}),(0,H.jsx)(`nav`,{"aria-label":`Primary`,className:`flex flex-col items-center gap-1.5`,children:l.map(e=>{let t=e.icon,n=RI(e,r,o);return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{i({type:`SET_ACTIVE_L1`,id:e.id}),KM(e.action,c)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,className:U(`relative grid size-9 place-items-center rounded-lg transition-colors`,n?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[n&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(t,{className:`size-5`})]},e.id)})}),(0,H.jsx)(`div`,{className:`flex-1`}),(0,H.jsx)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,H.jsx)(en,{className:`size-5`})}),(0,H.jsx)(`a`,{href:WN,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,H.jsx)(GN,{className:`size-5`})}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":o.pathname.startsWith(`/settings/profile`)?`page`:void 0,"data-testid":`nav-profile`,className:U(`relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,o.pathname.startsWith(`/settings/profile`)?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[o.pathname.startsWith(`/settings/profile`)&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(f,{className:`size-5`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":u?`page`:void 0,"data-testid":`nav-settings`,className:U(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,u?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[u&&(0,H.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,H.jsx)(Bn,{className:`size-5`}),(0,H.jsxs)(`span`,{role:`tooltip`,className:`pointer-events-none absolute bottom-0 left-full z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 font-mono text-[10px] text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`v`,VI]})]})]})}function GI({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,H.jsx)(`nav`,{className:U(`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,H.jsx)(`button`,{onClick:()=>KM(e.action,r),className:U(`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 KI=(0,V.createContext)(void 0),qI=(0,V.createContext)(null),JI={getState:()=>CF().getState(),setState:(e,t)=>{let n=CF();typeof e==`function`?n.setState(e(n.getState()),t):n.setState(e,t)},subscribe:e=>CF().subscribe(e)},YI=({factory:e,children:t})=>{let[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null),u=(0,V.useRef)(e);u.current=e;let d=(0,V.useRef)(null),f=(0,V.useRef)(null),p=(0,V.useRef)(!1),m=(0,V.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),JI.getState().setSubscriptionManager(null);let e=d.current;if(d.current=null,e)try{u.current.disposeRuntime(e)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime:`,e)}r(null),l(null)},[]),h=(0,V.useCallback)(e=>{if(!p.current){p.current=!0,s(!0),l(null);try{f.current&&=(f.current.dispose(),null);let t=d.current;if(d.current=null,t)try{u.current.disposeRuntime(t)}catch(e){console.error(`[RuntimeProvider] Error disposing existing runtime:`,e)}let n=u.current.createRuntime(e);if(d.current=n,r(n),n){let e=new vf(n);e.add(new _f({id:`local`})),f.current=e,a(e),JI.getState().setSubscriptionManager(e)}else f.current=null,a(null),JI.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,V.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,H.jsx)(KI.Provider,{value:g,children:(0,H.jsx)(qI.Provider,{value:i,children:t})})};function XI({factory:e,children:t}){return(0,H.jsx)(YI,{factory:e,children:t})}var ZI=`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`,QI=`flex flex-col flex-1 min-w-0 xl:max-w-[984px] 2xl:max-w-none min-h-screen lg:rounded-[2.5rem]`;function $I({id:e,title:t,subtitle:n,titleAccessory:r,actions:i,queryBar:a,subheader:o,titleTestId:s,className:c}){return(0,H.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:U(`max-lg:hidden lg:sticky lg:top-0 z-30 bg-background/80 backdrop-blur-md border-b border-border/50 transition-colors`,c),children:[(0,H.jsxs)(`div`,{className:`flex items-start justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,children:[t&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[(0,H.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`h1`,{"data-testid":s,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:t}),n&&(0,H.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:n})]}),r]})]}),a&&(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:a}),i&&(0,H.jsx)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:i})]}),o&&(0,H.jsx)(`div`,{className:`bg-background/40`,children:o})]})}function eL({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,V.useRef)(``),u=(0,V.useRef)(i),d=(0,V.useRef)(a),f=(0,V.useRef)(null),p=(0,V.useRef)(1);(0,V.useEffect)(()=>{u.current=i},[i]),(0,V.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,V.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,V.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,V.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,V.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 tL({title:e,titleAccessory:t,actions:n,subheader:r,children:i,index:a=[],activeSectionId:o,hero:s,sections:c,className:l}){let u=!!(c&&c.length>0)&&!e,[,d]=Gt(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,V.useState)(c?.[0]?.id??``);if(eL({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}),eL({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,H.jsxs)(`div`,{className:U(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,H.jsx)(GI,{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,H.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,H.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,H.jsx)(XI,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,H.jsx)(`div`,{className:U(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,H.jsxs)(`div`,{className:U(QI,ZI),children:[(0,H.jsx)($I,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,H.jsx)(`div`,{className:`flex-1`,children:i})]})})}var nL=`[data-page-sticky-boundary="true"]`,rL=0;function iL(e,t=rL){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(nL)).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 aL(e,t=rL){let[n,r]=(0,V.useState)(e);return(0,V.useEffect)(()=>{let n=0,i=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>r(iL(e,t)))};return i(),window.addEventListener(`scroll`,i,{passive:!0}),window.addEventListener(`resize`,i),()=>{cancelAnimationFrame(n),window.removeEventListener(`scroll`,i),window.removeEventListener(`resize`,i)}},[e,t]),n}function oL({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,H.jsxs)(`div`,{"data-testid":a,className:U(`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,H.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,H.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var sL=(0,V.createContext)(null),cL=(0,V.createContext)(null);function lL({children:e}){let[t,n]=(0,V.useState)(null);return(0,H.jsx)(cL.Provider,{value:n,children:(0,H.jsx)(sL.Provider,{value:t,children:e})})}function uL({className:e}){let t=(0,V.useContext)(cL);return(0,H.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function dL(){return(0,V.useContext)(sL)}function fL({editor:e,title:t,subtitle:n,titleTestId:r,actions:i,timerOverlay:a,reviewOverlay:o,isTimerOpen:s=!1,isReviewOpen:c=!1,onCloseTimer:l,onCloseReview:u,className:d}){return(0,H.jsxs)(`div`,{className:U(`relative flex w-full min-h-screen justify-start items-start`,d),children:[(0,H.jsxs)(`div`,{className:U(QI,ZI),children:[(0,H.jsx)($I,{title:t,subtitle:n,titleTestId:r,actions:i}),(0,H.jsx)(`main`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),s&&a&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,H.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,H.jsx)(`button`,{onClick:l,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:a})]})}),c&&o&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,H.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,H.jsx)(`button`,{onClick:u,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:o})]})})]})}function pL(e){return e.map(e=>{let t=e.action,n=e.secondaryAction?.action,r={kind:`link`,id:e.id,label:e.label,muted:e.level===3&&!!e.secondaryAction};return n&&n.type===`call`&&(r.onRun=n.handler,r.runIcon=e.secondaryRunIcon??`play`),t.type===`route`?{...r,to:t.to}:t.type===`scroll`?{...r,sectionId:t.sectionId}:t.type===`call`?{...r,onRun:t.handler}:r})}var mL=V.createContext(null);function hL(){let e=V.useContext(mL);if(!e)throw Error(`DropdownMenu components must be used inside a DropdownMenu`);return e}var gL=({children:e,open:t,onOpenChange:n})=>{let r=V.useContext(mL),i=V.useId(),a=r?`${r.portalChain}/${i}`:i,[o,s]=V.useState(t??!1),c=V.useRef(null),[l,u]=V.useState(-1),d=V.useRef(new Map),[,f]=V.useReducer(e=>e+1,0);V.useEffect(()=>{t!==void 0&&s(t)},[t]);let p=V.useCallback(e=>{s(e),u(-1),n?.(e)},[n]),m=V.useCallback((e,t)=>{d.current.set(e,t),f()},[]),h=V.useCallback(e=>{d.current.delete(e),f()},[]),g=V.useCallback(e=>Array.from(d.current.keys()).indexOf(e),[]),_=d.current.size,v=V.useMemo(()=>({isOpen:o,setIsOpen:p,triggerRef:c,registerItem:m,unregisterItem:h,getItemIndex:g,activeIndex:l,setActiveIndex:u,itemCount:_,menuId:i,portalChain:a}),[o,p,m,h,g,l,_,i,a]);return(0,H.jsx)(mL.Provider,{value:v,children:(0,H.jsx)(`div`,{ref:c,className:`relative inline-block`,children:e})})},_L=V.forwardRef(({className:e,children:t,asChild:n,...r},i)=>{let{isOpen:a,setIsOpen:o}=hL(),s=e=>{e.stopPropagation(),o(!a)};return n&&V.isValidElement(t)?V.cloneElement(t,{...r,onClick:s}):(0,H.jsx)(`button`,{ref:i,className:e,onClick:s,...r,children:t})});_L.displayName=`DropdownMenuTrigger`;var vL=V.forwardRef(({className:e,children:t,align:n=`center`,side:r=`bottom`,...i},a)=>{let{isOpen:o,setIsOpen:s,triggerRef:c,setActiveIndex:l,itemCount:u,menuId:d,portalChain:f}=hL(),p=V.useRef(null),m=a||p,[h,g]=V.useState({top:0,bottom:0,left:0,width:0});V.useEffect(()=>{if(!o||!c.current)return;let e=c.current.getBoundingClientRect();g({top:e.bottom+8,bottom:window.innerHeight-e.top+8,left:e.left,width:e.width})},[o,c]),V.useEffect(()=>{if(!o||u===0)return;let e=setTimeout(()=>{l(0)},0);return()=>clearTimeout(e)},[o,u,l]),V.useEffect(()=>{if(!o)return;let e=e=>{let t=e.target;if(m.current&&m.current.contains(t)||c.current&&c.current.contains(t))return;let n=t.closest?.(`[data-dropdown-chain]`)?.getAttribute(`data-dropdown-chain`);n&&n.split(`/`).includes(d)||s(!1)},t=setTimeout(()=>{document.addEventListener(`mousedown`,e)},0);return()=>{clearTimeout(t),document.removeEventListener(`mousedown`,e)}},[o,s,m,c,d]);let _=e=>{if(u!==0)switch(e.key){case`ArrowDown`:e.preventDefault(),l(e=>e<u-1?e+1:0);break;case`ArrowUp`:e.preventDefault(),l(e=>e>0?e-1:u-1);break;case`Home`:e.preventDefault(),l(0);break;case`End`:e.preventDefault(),l(u-1);break;case`Escape`:e.preventDefault(),s(!1),c.current?.querySelector(`button`)?.focus();break;case`Tab`:s(!1)}};if(!o)return null;let v={position:`fixed`,zIndex:9999};return r===`top`?v.bottom=h.bottom:v.top=h.top,n===`end`?v.right=window.innerWidth-h.left-h.width:n===`start`?v.left=h.left:(v.left=h.left+h.width/2,v.transform=`translateX(-50%)`),aS.createPortal((0,H.jsx)(`div`,{ref:m,role:`menu`,"data-dropdown-chain":f,className:U(`min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95`,e),style:v,onKeyDown:_,...i,children:t}),document.body)});vL.displayName=`DropdownMenuContent`;var yL=V.forwardRef(({className:e,disabled:t,inset:n,onClick:r,onKeyDown:i,...a},o)=>{let{setIsOpen:s,registerItem:c,unregisterItem:l,getItemIndex:u,activeIndex:d}=hL(),f=V.useId(),p=V.useRef(null),m=V.useCallback(e=>{p.current=e,typeof o==`function`?o(e):o&&(o.current=e)},[o]);V.useEffect(()=>(c(f,p),()=>l(f)),[f,c,l]);let h=u(f)===d;return V.useEffect(()=>{h&&p.current?.focus()},[h]),(0,H.jsx)(`div`,{ref:m,role:`menuitem`,tabIndex:t?-1:h?0:-1,"aria-disabled":t,"data-active":h?`true`:void 0,className:U(`relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors`,`focus:bg-accent focus:text-accent-foreground`,`data-[active]:bg-accent data-[active]:text-accent-foreground`,n&&`pl-8`,t&&`pointer-events-none opacity-50`,e),onClick:e=>{t||(r?.(e),s(!1))},onKeyDown:e=>{t||(i?.(e),(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r?.(e),s(!1)))},...a})});yL.displayName=`DropdownMenuItem`;var bL=V.forwardRef(({className:e,inset:t,...n},r)=>(0,H.jsx)(`div`,{ref:r,className:U(`px-2 py-1.5 text-sm font-semibold`,t&&`pl-8`,e),...n}));bL.displayName=`DropdownMenuLabel`;var xL=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`-mx-1 my-1 h-px bg-muted`,e),...t}));xL.displayName=`DropdownMenuSeparator`;function SL({className:e,children:t,...n}){return(0,H.jsx)(`div`,{className:U(`px-2 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,e),...n,children:t})}var CL=[{label:`Past 1 week`,value:`last 1w`},{label:`Past 2 weeks`,value:`last 2w`},{label:`Past 4 weeks`,value:`last 4w`},{label:`Past 8 weeks`,value:`last 8w`},{label:`Past 12 weeks`,value:`last 12w`},{label:`Past 1 year`,value:`last 52w`},{label:`All time`,value:`all`}],wL=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function TL(e,t){return new Date(e,t+1,0).getDate()}function EL(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function DL(e,t){let n=Y(e);if(n.error)return e;if(!t||t===`all`)return Km({...n,window:void 0});let r=Y(`:note ${t}`);return r.error||r.family!==`find`||!r.window?e:Km({...n,window:r.window})}function OL(e){let t=Y(e);return t.error||t.family===`pipeline`?null:`window`in t?t.window??null:null}function kL({query:e,onQueryChange:t,highlightDates:n=new Set,className:r}){let i=(0,V.useMemo)(()=>OL(e),[e]),[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(()=>new Date),l=s.getFullYear(),u=s.getMonth(),d=(0,V.useMemo)(()=>i?i.kind===`relative`?`last ${i.size}${i.unit}`:i.end?`from ${i.start} to ${i.end}`:`from ${i.start}`:`All time`,[i]),f=(0,V.useMemo)(()=>{if(!i)return null;if(i.kind===`range`)return{start:i.start,end:i.end??i.start};let e=new Date,t=new Date;return i.unit===`d`?t.setDate(e.getDate()-i.size):t.setDate(e.getDate()-i.size*7),{start:Bj(t),end:Bj(e)}},[i]),p=(0,V.useMemo)(()=>{let e=TL(l,u),t=EL(l,u),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[l,u]),m=n=>{if(!a)o(n),t(DL(e,`from ${n} to ${n}`));else{let[r,i]=a<=n?[a,n]:[n,a];o(null),t(DL(e,`from ${r} to ${i}`))}},h=e=>{e.stopPropagation(),c(new Date(l,u-1,1))},g=e=>{e.stopPropagation(),c(new Date(l,u+1,1))},_=s.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),v=Bj(new Date);return(0,H.jsxs)(`div`,{className:U(`relative inline-flex items-center`,r),children:[(0,H.jsxs)(gL,{children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`wql-window-picker-trigger`,className:`flex h-9 items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,H.jsx)(qt,{className:`size-3.5 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`font-mono text-xs`,children:d}),(0,H.jsx)(un,{className:`size-3 text-muted-foreground`,"aria-hidden":`true`})]})}),(0,H.jsxs)(vL,{align:`end`,className:`w-72 p-3`,children:[(0,H.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-1 border-b border-border/60 pb-2`,children:CL.map(n=>{let r=n.value===`all`?!i:i?.kind===`relative`&&`last ${i.size}${i.unit}`===n.value;return(0,H.jsx)(`button`,{type:`button`,"data-testid":`wql-window-preset-${n.value}`,onClick:()=>{o(null),t(DL(e,n.value))},className:U(`rounded-md px-2 py-1 text-[11px] font-medium transition-colors`,r?`bg-primary text-primary-foreground`:`bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground`),children:n.label},n.value)})}),(0,H.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:h,"data-testid":`wql-calendar-prev-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,H.jsx)(Tt,{className:`size-4`})}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:_}),(0,H.jsx)(`button`,{type:`button`,onClick:g,"data-testid":`wql-calendar-next-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,H.jsx)(Vn,{className:`size-4`})})]}),(0,H.jsx)(`div`,{className:`mb-1 grid grid-cols-7 gap-1`,children:wL.map(e=>(0,H.jsx)(`div`,{className:`text-center text-[10px] font-medium text-muted-foreground`,children:e},e))}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-1`,"data-testid":`wql-calendar-grid`,children:p.map((e,t)=>{if(e===null)return(0,H.jsx)(`div`,{className:`size-8`},`empty-${t}`);let r=`${l}-${String(u+1).padStart(2,`0`)}-${String(e).padStart(2,`0`)}`,i=f&&r>=f.start&&r<=f.end,o=f&&r===f.start||a===r,s=f&&r===f.end,c=r===v,d=n.has(r);return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`wql-calendar-day-${r}`,onClick:()=>m(r),className:U(`relative flex size-8 items-center justify-center rounded-md text-xs transition-colors`,o||s?`bg-primary font-bold text-primary-foreground`:i?`bg-primary/15 font-semibold text-primary`:c?`border border-primary font-semibold text-primary`:`text-foreground hover:bg-muted`),children:[(0,H.jsx)(`span`,{children:e}),d&&!o&&!s&&(0,H.jsx)(`span`,{className:`absolute bottom-0.5 size-1 rounded-full bg-primary`})]},r)})}),a&&(0,H.jsxs)(`div`,{className:`mt-2 text-center text-[10px] text-muted-foreground`,children:[`Select second date to complete range (starting from `,a,`)`]})]})]}),i&&(0,H.jsx)(`button`,{type:`button`,"data-testid":`wql-window-picker-clear`,onClick:()=>{o(null),t(DL(e,null))},title:`Clear time window`,"aria-label":`Clear time window`,className:`ml-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3.5`})})]})}function AL(e){switch(e.kind){case`note`:case`post`:return`note`;case`session`:return`session`;case`result`:return`result`;case`segment`:case`event`:return`segment`;case`effort`:return`effort`;default:return`note`}}var jL=[{id:`title`,label:`Title`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`tags`,label:`Tags`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.tags??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)},{id:`excerpt`,label:`Text Excerpt`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.preview?.join(` `)||e.detail||``,formatValue:e=>String(e??``)},{id:`catalog`,label:`Catalog Source`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.sourceCatalog,formatValue:e=>String(e??``)},{id:`date`,label:`Date`,level:`note`,defaultVisible:!0,align:`right`,getValue:e=>e.date,formatValue:e=>String(e??``)}],ML={note:jL,session:[{id:`title`,label:`Title`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`protocol`,label:`Protocol`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.dataType||e.subtitle||``,formatValue:e=>String(e??``)},{id:`movements`,label:`Movements`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.detail||``,formatValue:e=>String(e??``)},{id:`targetDuration`,label:`Target Duration`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`sessionLoad`,label:`Session Load`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``}],result:[{id:`title`,label:`Title`,level:`result`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`elapsedTime`,label:`Elapsed Time`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`totalTonnage`,label:`Total Tonnage`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`tis`,label:`TIS Score`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.tis,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`prBadges`,label:`PR Badges`,level:`result`,defaultVisible:!0,align:`center`,getValue:e=>e.detail&&/\bPR\b/.test(e.detail)?`PR`:``,formatValue:e=>String(e??``)}],segment:[{id:`splitDuration`,label:`Split Duration`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:_I(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`roundIndex`,label:`Round/Lap Index`,level:`segment`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`reps`,label:`Reps`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.reps,formatValue:e=>e==null?``:String(e)},{id:`load`,label:`Load`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`pacingTier`,label:`Pacing / HR Tier`,level:`segment`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier||e.execution?.effortSlug||``,formatValue:e=>String(e??``)}],effort:[{id:`label`,label:`Label`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.label||e.title,formatValue:e=>String(e??``)},{id:`canonicalSlug`,label:`Canonical Slug`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.slug||e.id,formatValue:e=>String(e??``)},{id:`discipline`,label:`Discipline`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.discipline??``,formatValue:e=>String(e??``)},{id:`met`,label:`MET Score`,level:`effort`,defaultVisible:!0,align:`right`,getValue:e=>e.effort?.met,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`intensityTier`,label:`Intensity Tier`,level:`effort`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier??``,formatValue:e=>String(e??``)},{id:`aliases`,label:`Aliases`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.aliases??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)}]};function NL(e){return ML[e]??jL}function PL(e){return NL(e).filter(e=>e.defaultVisible).map(e=>e.id)}var FL=[{id:`cards`,label:`Cards`,icon:s},{id:`rows`,label:`Rows`,icon:oe},{id:`feed`,label:`Feed`,icon:Rt}];function IL({streamControls:e}){return(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`l3-stream-controls`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date window`}),(0,H.jsx)(kL,{query:e.query,onQueryChange:e.onQueryChange,className:`w-full justify-between`})]}),e.availableGroupDims.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Group by`}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-groupby-options`,children:e.availableGroupDims.map(t=>{let n=e.groupDims.some(e=>e.toLowerCase()===t.id.toLowerCase());return(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-groupby-${t.id}`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleGroupDim(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,H.jsx)(`span`,{children:t.label})]},t.id)})})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Layout`}),(0,H.jsx)(`div`,{className:`grid grid-cols-3 gap-1`,"data-testid":`l3-layout-options`,children:FL.map(t=>{let n=t.icon,r=e.settings.layout===t.id;return(0,H.jsxs)(`button`,{type:`button`,"aria-pressed":r,onClick:()=>e.onLayoutChange(t.id),"data-testid":`l3-layout-${t.id}`,className:`flex min-h-8 items-center justify-center gap-1 rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors ${r?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[(0,H.jsx)(n,{"aria-hidden":!0,className:`size-3`}),t.label]},t.id)})})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Fields`}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-field-options`,children:NL(e.level).map(t=>{let n=e.settings.visibleFields.includes(t.id);return(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-field-${t.id}`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleField(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,H.jsx)(`span`,{children:t.label})]},t.id)})})]})]})}function LL({spec:e,pageAction:t}){let{l3Items:n,streamControls:r}=hA(),i=MI(e),a=(0,V.useMemo)(()=>pL(n),[n]),o=NI();return i.length===0&&a.length===0&&!r&&!t?null:(0,H.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[r&&(0,H.jsx)(`div`,{className:`pb-3 border-b border-border/50`,children:(0,H.jsx)(IL,{streamControls:r})}),i.length>0&&(0,H.jsx)(FI,{entries:i,activeId:o}),a.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col`,children:[(0,H.jsx)(`div`,{className:`px-2 pb-1 pt-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,H.jsx)(FI,{entries:a,activeId:o})]}),t&&(0,H.jsx)(`div`,{className:`pt-2 border-t border-border/50`,children:t})]})}var RL=1023;function zL(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function BL(e,t){if(e===`query:new`)return``;let n=e=>{let n=`/${e}`;for(let r of Object.keys(t))if(r===e||r.endsWith(n))return r;return null},r=e=>{let r=n(e);return r===null?null:Db(t[r])};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i=e;if(e.startsWith(`wods/examples/`))i=`markdown/canvas/`+e.replace(/^wods\/examples\//,``);else if(e.startsWith(`wods/`))i=`markdown/canvas/`+e.replace(/^wods\//,``);else if(e.startsWith(`collections/`))i=`markdown/collections/`+e.replace(/^collections\//,``);else if(e.startsWith(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;let n=r(`markdown/collections/`+e);if(n!==null)return n;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function VL(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function HL(e){let t=new Map,n=null;for(let r of e)VL(r)&&(n=r),t.set(r.id,n);return t}function UL(){let[e,t]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${RL}px)`).matches);return(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${RL}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var WL=`wodwiki:fabAlignment`,GL=[{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 KL(){try{return qL(localStorage.getItem(WL))}catch{return}}function qL(e){return e===`right`||e===`left`?e:void 0}var JL=typeof window>`u`?void 0:KL();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===WL&&(JL=qL(e.newValue))});function YL(e){JL=e;try{e===`right`?localStorage.removeItem(WL):localStorage.setItem(WL,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:WL,newValue:e}))}function XL(){let[e,t]=(0,V.useState)(()=>JL??`right`);return(0,V.useEffect)(()=>{let e=e=>{e.key===WL&&t(qL(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,YL]}function ZL({onOpen:e}){return(0,H.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,"data-testid":`search-fab`,className:U(`size-14 rounded-full flex items-center justify-center`,`bg-primary text-primary-foreground shadow-lg`,`hover:bg-primary/90 active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:(0,H.jsx)(en,{className:`size-6`})})}var QL=(0,V.createContext)(null),$L=(0,V.createContext)(!1),eR=(0,V.createContext)(null);function tR(){return(0,V.useContext)(QL)!==null}function nR({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,V.useContext)(QL),o=(0,V.useContext)($L),s=UL(),c=(0,V.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=(0,H.jsx)($L.Provider,{value:!0,children:n});return(0,V.useEffect)(()=>{if(!(!l&&!u))return a.register({id:c,primary:e,navbar:t,children:d,label:r??`Page options`,fallback:i}),()=>a.unregister(c)},[l,u,a,c,e,d,r,i]),i||a&&s&&!o?null:(0,H.jsx)($L.Provider,{value:!0,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function rR({onSearch:e,children:t}){let[n,r]=(0,V.useState)([]),i=(0,V.useCallback)(e=>r(t=>[...t.filter(t=>t.id!==e.id),e]),[]),a=(0,V.useCallback)(e=>r(t=>t.filter(t=>t.id!==e)),[]),o=(0,V.useMemo)(()=>({register:i,unregister:a}),[i,a]),s=(0,V.useMemo)(()=>{for(let e=n.length-1;e>=0;--e)if(!n[e].fallback)return n[e].navbar??null;return null},[n]);return(0,H.jsx)(QL.Provider,{value:o,children:(0,H.jsxs)(eR.Provider,{value:s,children:[t,(0,H.jsx)(aR,{registrations:n,onSearch:e})]})})}function iR(){let e=(0,V.useContext)(eR);return e?(0,H.jsx)(H.Fragment,{children:e}):null}function aR({registrations:e,onSearch:t}){let n=UL(),[r]=XL(),i=sS(),[a,o]=(0,V.useState)(!1),s=(0,V.useRef)(null),c=mt(),[l,u]=(0,V.useState)(!1),d=(0,V.useRef)(0),f=i.offsetBottom>0,p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),g=(0,V.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]);(0,V.useEffect)(()=>{o(!1),u(!1),d.current=window.scrollY},[c.pathname]),(0,V.useEffect)(()=>{if(!n)return;let e=()=>{let e=window.scrollY;if(e<=0||f||a){d.current=e,u(!1);return}let t=e-d.current;Math.abs(t)<8||(d.current=e,u(t>0))};return window.addEventListener(`scroll`,e,{passive:!0}),()=>window.removeEventListener(`scroll`,e)},[n,f,a]),(0,V.useLayoutEffect)(()=>{a&&s.current?.focus()},[a]);let[_,v]=(0,V.useState)({active:0,global:0});(0,V.useLayoutEffect)(()=>{let e=p.current?.childElementCount??0,t=m.current?.childElementCount??0;v(n=>n.active===e&&n.global===t?n:{active:e,global:t})},[h,g]);let y=_.active>0||_.global>0;return!n||!t&&!h&&!g?null:(0,H.jsxs)(`div`,{"data-testid":`actions-dock`,className:U(`lg:hidden fixed z-40 flex flex-col items-center gap-2`,`transition-[transform,visibility] duration-200 ease-out`,r===`left`?`left-4 items-start`:`right-4 items-end`,l&&!a&&!f&&`translate-y-[calc(100%+2rem)] invisible pointer-events-none`),style:{bottom:`calc(1rem + var(--thumb-dock-lift, 0px) + ${i.offsetBottom}px + env(safe-area-inset-bottom))`},children:[(0,H.jsxs)(`div`,{className:`relative z-40 flex flex-col items-center gap-2`,children:[h?.primary&&(0,H.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:h.primary}),t&&(0,H.jsx)(ZL,{onOpen:()=>{o(!1),t()}})]}),a&&y&&(0,H.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 cursor-default`,onClick:()=>o(!1)}),(0,H.jsxs)(`div`,{ref:s,role:`dialog`,"aria-label":h?.label??g?.label??`Page options`,tabIndex:-1,hidden:!a||!y,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),o(!1))},className:U(`relative z-40 flex w-60 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/5 outline-none`,`[&_button]:min-h-11 [&_button]:min-w-11`),style:{maxHeight:`calc(${i.height===null?`100dvh`:`${i.height}px`} - 6rem - env(safe-area-inset-bottom))`},children:[(0,H.jsx)(`div`,{ref:p,className:`contents`,children:h?.children}),_.active>0&&_.global>0&&(0,H.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,H.jsx)(`div`,{ref:m,className:`contents`,children:g?.children})]}),y&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-label":h?.label??g?.label??`Page options`,"aria-expanded":a,"data-testid":`actions-overflow`,className:U(`relative z-40 flex size-12 items-center justify-center rounded-full`,`bg-card text-foreground shadow-lg ring-1 ring-foreground/10`,`hover:bg-muted active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:a?(0,H.jsx)(Re,{className:`size-6`}):(0,H.jsx)(ge,{className:`size-6`})})]})}function oR(){return(0,H.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,H.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 sR(){return(0,H.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,H.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 cR(){let{tree:e,navState:t,contextNav:n}=hA(),r=mt(),i=Qj();return!e.find(e=>e.id===t.activeL1Id)?.applyFooter||n?.pathname===r.pathname?null:(0,H.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:i,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})}function lR({open:e,close:t,onSearch:n,onCreate:r,children:i}){return(0,H.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,H.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,H.jsx)(A,{transition:!0,className:`fixed inset-y-0 left-0 w-full transition duration-300 ease-out data-closed:-translate-x-full`,children:(0,H.jsx)(Zj,{close:t,children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,H.jsx)(`div`,{className:`flex h-full w-14 shrink-0 flex-col items-center border-r border-zinc-950/5 bg-background/72 py-3 dark:border-white/5 [&_a]:size-11 [&_button]:size-11`,children:(0,H.jsx)(WI,{onSearch:()=>{t(),n?.()},onCreate:r?()=>{t(),r()}:void 0})}),(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,H.jsx)(`div`,{className:`flex items-center px-4 pt-3`,children:(0,H.jsx)(rt,{as:PP,"aria-label":`Close navigation`,children:(0,H.jsx)(sR,{})})}),(0,H.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i}),(0,H.jsx)(cR,{})]})]})})})]})}function uR({open:e,close:t,children:n}){return(0,H.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,H.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,H.jsx)(A,{transition:!0,className:`fixed inset-y-0 right-0 w-full transition duration-300 ease-out data-closed:translate-x-full`,children:(0,H.jsx)(Zj,{close:t,children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-card`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-end px-4 pt-3`,children:(0,H.jsx)(rt,{as:PP,"aria-label":`Close page options`,children:(0,H.jsx)(sR,{})})}),(0,H.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:n}),(0,H.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})]})})})]})}function dR({navbar:e,sidebar:t,onSearch:n,onCreate:r,secondary:i,pageAction:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,V.useState)(!1),[u,d]=(0,V.useState)(!1),f=(0,V.useRef)(null),[p,m]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>m(t=>{let n=e.childElementCount>0;return t===n?t:n}),n=new MutationObserver(t);return n.observe(e,{childList:!0,subtree:!0}),t(),()=>n.disconnect()},[]);let{streamControls:h}=hA(),g=(0,V.useMemo)(()=>{let e=Y(h?.query??``);return!e.error&&tm(e)&&e.filters.length>0},[h?.query]);return(0,H.jsx)(lL,{children:(0,H.jsx)(rR,{onSearch:n,children:(0,H.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,H.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,H.jsxs)(`nav`,{"aria-label":`Main`,className:`hidden lg:flex`,children:[(0,H.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,H.jsx)(WI,{onSearch:n??(()=>{}),onCreate:r})}),(0,H.jsx)(`div`,{className:U(`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,H.jsx)(lR,{open:c,close:()=>l(!1),onSearch:n,onCreate:r,children:t}),(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col min-w-0 xl:max-w-[984px] 2xl:max-w-none`,children:[(0,H.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 border-b border-border/50`,children:[(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:()=>l(!0),"aria-label":`Open navigation`,children:(0,H.jsx)(oR,{})})}),(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),r&&(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:r,"aria-label":`New journal note`,children:(0,H.jsx)(Ut,{className:`size-5`})})}),p&&(0,H.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,H.jsx)(PP,{onClick:()=>d(!0),"aria-label":`Open page options`,children:(0,H.jsxs)(`span`,{className:`relative inline-flex`,children:[(0,H.jsx)(Zt,{className:`size-5`}),g&&(0,H.jsx)(`span`,{"data-testid":`drawer-filters-active`,className:`absolute -top-1 -right-1 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`})]})})})]}),(0,H.jsxs)(`main`,{className:`flex flex-1 flex-col lg:min-w-0`,children:[(0,H.jsx)(`div`,{className:`grow w-full max-lg:pb-48 lg:overflow-visible`,children:s}),(0,H.jsx)(fR,{})]})]}),(0,H.jsx)(`aside`,{className:`hidden 2xl:flex w-60 shrink-0 sticky top-0 h-svh flex-col overflow-y-auto bg-background/72 backdrop-blur-sm`,children:(0,H.jsx)(`div`,{ref:f,className:`contents`,children:(0,H.jsx)(LL,{spec:i,pageAction:a})})}),(0,H.jsx)(uR,{open:u,close:()=>d(!1),children:(0,H.jsx)(LL,{spec:i,pageAction:a})})]})})})})}function fR(){let e=(0,V.useRef)(null),[t,n]=(0,V.useState)(0);return(0,V.useEffect)(()=>{let t=e.current;if(!t)return;let r=new ResizeObserver(e=>{let t=Math.round(e[0]?.contentRect.height??0);n(e=>e===t?e:t)});r.observe(t,{box:`content-box`});let i=Math.round(t.getBoundingClientRect().height);return n(e=>e===i?e:i),()=>r.disconnect()},[]),(0,V.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${t}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[t]),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`lg:hidden fixed inset-x-0 bottom-0 z-30`,t>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,H.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,H.jsx)(uL,{className:`flex w-full min-w-0`})})}),(0,H.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:t}})]})}function pR(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function mR(e){return String(Ob(Sb(e).meta,`search`)??``).toLowerCase()===`hidden`}function hR(e){let t=Ob(Sb(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 gR(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=Ob(Sb(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():zE(r),category:pR(n),content:i,date:hR(i),searchHidden:mR(i)}})}function _R(){let e=sD();return(0,V.useMemo)(()=>e?gR(e):[],[e])}var vR={};function yR(e){if(!(`payload`in e))return;let t=e.payload;if(!t||typeof t!=`object`)return;let n=t;return n.targetDate??n.updatedAt}function bR(e,t){let{canvasPage:n,workoutItems:r,recentResults:i,selectWorkout:a}=t;if(n){let t=/^\/(?:c|collections)\//.test(e),i=t?e.split(`/`).pop()??null:null;if(e===`/`)return[];let o=[],s=e.startsWith(`/guide/`);return n.sections.filter(e=>e.level>1).forEach(e=>{if(o.push({id:e.id,label:e.heading,type:`heading`}),!s){let t=nP(e).split(`
101
101
  `),n=0;t.forEach((t,r)=>{let i=t.trim().match(/^```(time|log)(:\w+)?\s*$/);if(i){let t=i[1];n++,o.push({id:`${e.id}-${t}-${r+1}`,label:`Workout ${n}`,type:t})}})}}),t&&i&&(o.push({id:`collection-workouts`,label:`Explore`,type:`heading`}),r.filter(e=>e.category===i&&e.name.toLowerCase()!==`readme`).forEach(e=>{o.push({id:`workout-${e.id}`,label:e.name,type:`time`,onRun:()=>a(e),runIcon:`link`})})),o}if(e===`/journal`){let e=new Set;return i.forEach(t=>{let n=new Date(t.createdAt).getTime();Number.isFinite(n)&&e.add(Bj(new Date(n)))}),r.forEach(t=>{let n=yR(t);n&&Number.isFinite(new Date(n).getTime())&&e.add(Bj(new Date(n)))}),Array.from(e).sort().reverse().slice(0,10).map(e=>({id:e,label:UP(new Date(e+`T00:00:00`)),type:`heading`}))}return[]}var xR=/^[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 SR(e){return xR.test(e)}function CR(e){try{return decodeURIComponent(e)}catch{return null}}function wR(e){if(!Uj(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 TR(e){let t=e.length>1?e.replace(/\/+$/,``):e;if(t===`/journal`)return{kind:`index`};if(!t.startsWith(`/journal/`))return{kind:`invalid`};let n=t.slice(9).split(`/`).map(CR);if(n.some(e=>e==null))return{kind:`invalid`};let r=n;if(r.length===1){let e=r[0];return wR(e)?{kind:`date`,journalDate:e}:xR.test(e)?{kind:`uuid-alias`,noteId:e}:e?{kind:`slug-alias`,slug:e}:{kind:`invalid`}}if(r.length===2){let[e,t]=r;if(wR(e)&&xR.test(t))return{kind:`note`,journalDate:e,noteId:t}}return{kind:`invalid`}}var ER=`# My Workout Notebook
102
102
 
103
103
  Welcome to the **WOD.WIKI** playground.
@@ -127,7 +127,7 @@ Timer 12:00
127
127
  `;function DR(e,t){let{name:n,id:r}=t,i=uj(e),a=r||(e.startsWith(`/note/playground/`)?n:void 0),o=TR(e),s=![`index`,`invalid`].includes(o.kind),c=o.kind===`date`?o.journalDate:o.kind===`note`||o.kind===`uuid-alias`?o.noteId:o.kind===`slug-alias`?o.slug:void 0,l=pj(e),u=l?null:mj(e),d=e.match(/^\/(?:notes|note)\/([^/]+)$/),f=d!=null,p=d?decodeURIComponent(d[1]):void 0,m=null,h=e.match(/^\/(?:c|collections)\/([^/]+)\/([^/]+)$/);if(h){let e=decodeURIComponent(h[1]),t=decodeURIComponent(h[2]);if(SR(t)){if(!f)return{isPlaygroundRoute:i,effectivePlaygroundId:a,isJournalEntryRoute:s,journalEntryId:c,isNoteByIdRoute:!0,noteById:t,collectionDate:null,feedItemMatch:l,feedDetailMatch:u}}else{let n=Uj(t);n&&(m={slug:e,date:n.dateKey})}}return{isPlaygroundRoute:i,effectivePlaygroundId:a,isJournalEntryRoute:s,journalEntryId:c,isNoteByIdRoute:f,noteById:p,collectionDate:m,feedItemMatch:l,feedDetailMatch:u}}function OR(e,t,n,r,i){let{category:a,name:o,collection:s,workout:c}=n;if(e.isPlaygroundRoute)return{name:`Playground`,content:``,category:`playground`};if(e.isNoteByIdRoute&&e.noteById)return{name:`Note`,content:``,category:`note`};if(e.collectionDate)return{name:e.collectionDate.date,content:``,category:e.collectionDate.slug};if(e.isJournalEntryRoute&&e.journalEntryId)return{name:e.journalEntryId,content:``,category:`journal`};if(t.startsWith(`/effort/`)||t.startsWith(`/e/`)){let e=t.startsWith(`/e/`)?`/e/`:`/effort/`;return{name:decodeURIComponent(t.slice(e.length).split(`/`)[0]??`Effort`),content:``,category:`effort`}}if(t.startsWith(`/equipment/`))return{name:decodeURIComponent(t.slice(11).split(`/`)[0]??`Equipment`),content:``,category:`equipment`};if(e.feedItemMatch)return{name:decodeURIComponent(e.feedItemMatch[2]),content:``,category:`feed`};if(e.feedDetailMatch)return{name:decodeURIComponent(e.feedDetailMatch),content:``,category:`feed`};if(t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)){let e=t.startsWith(`/d/`)?t.slice(3):t.split(`/`)[2];return{name:decodeURIComponent(e??`Dashboard`),content:``,category:`dashboard`}}if(t.startsWith(`/session/`))return{name:decodeURIComponent(t.split(`/`)[2]??`Sessions`),content:``,category:`sessions`};if(i)return{name:i.sections[0]?.heading??`Canvas`,content:``,category:`canvas`};let l={"/":`Home`,"/results":`Results`,"/results/segments":`Segments`,"/dashboard":`Dashboards`,"/dashboards":`Dashboards`,"/analytics/dashboard":`Analytics Dashboard`,"/analytics/explorer":`Metric Explorer`},u=DA(t),d=HA(u)??l[t]??l[u];if(d)return{name:d,content:``,category:`General`};if(u.startsWith(`/results/`))return{name:`Result`,content:ER,category:`Results`};if(u===`/settings`||u.startsWith(`/settings/`))return{name:`Settings`,content:ER,category:`Settings`};let f=c||o;if(!f)return{name:`Home`,content:ER,category:`General`};let p=decodeURIComponent(f),m=s||a?decodeURIComponent(s||a):`General`,h=r.find(e=>e.name===p&&e.category===m);return h?{name:h.name,content:h.content,category:h.category}:{name:p,content:ER,category:m}}function kR(e,t,n){let r=DA(t);return UA(r)?`library`:e.feedDetailMatch?`feedDetail`:e.feedItemMatch?`feedItem`:t.startsWith(`/effort/`)||t.startsWith(`/e/`)?`effortDetail`:t.startsWith(`/equipment/`)?`equipmentDetail`:t===`/analytics/explorer`?`analyticsExplorer`:t===`/dashboard`||t===`/dashboards`?`dashboardExplorer`:t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)?`dashboardView`:r===`/settings`||r.startsWith(`/settings/`)?`settings`:n?`canvas`:e.isPlaygroundRoute&&e.effectivePlaygroundId?`playground`:e.isNoteByIdRoute&&e.noteById?`note`:e.collectionDate?`collectionDate`:e.isJournalEntryRoute&&e.journalEntryId?`journalEntry`:`workout`}function AR(e,t,n){switch(e){case`canvas`:return{wrap:`canvas`,title:n.name,subheader:/^\/(?:c|collections)\//.test(t)?`filter-collection-workouts`:void 0,actionsMode:`collection-readonly`,withIndex:!0};default:return{wrap:`bare`}}}function jR(e,t,n){let r=DR(e,t);if(!n.canvasPage&&!r.noteById){let t=e.match(/^\/p\/([^/]+)$/);t&&(r.isNoteByIdRoute=!0,r.noteById=decodeURIComponent(t[1]))}let i=OR(r,e,t,n.workoutItems,n.canvasPage),a=bR(e,n),o=kR(r,e,n.canvasPage),s=AR(o,e,i);return{...r,canvasPage:n.canvasPage,workout:i,nav:a,page:o,shell:s}}function MR(e=20){let[t,n]=(0,V.useState)([]),{pathname:r}=mt(),i=(0,V.useCallback)(()=>{X.getRecentSessions(e).then(n).catch(()=>{})},[e]);return(0,V.useEffect)(()=>{i()},[r,i]),t}function NR(){let e=Sn();return(0,V.useCallback)(t=>{t.name===`Home`?e(Q.home):e(ZA(t.category??`General`,t.name))},[e])}function PR(){let e=zn(),{pathname:t}=mt(),n=_R(),r=MP(t),i=MR(),a=NR();return(0,V.useMemo)(()=>jR(t,e,{workoutItems:n,canvasPage:r,recentResults:i,selectWorkout:a}),[t,e,n,r,i,a])}function FR(e,t,n){let r=e===`upload`?`Uploading`:`Downloading`,i=n??`data`;return t>1?`${r} ${i} (${t} syncs)`:`${r} ${i}`}function IR(){let e=(0,V.useSyncExternalStore)(hb,mb);return e.uploading===0&&e.downloading===0?null:(0,H.jsxs)(`div`,{role:`status`,"data-testid":`sync-activity-indicators`,className:`flex items-center gap-1 text-muted-foreground`,children:[e.downloading>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,"aria-label":FR(`download`,e.downloading,e.label),title:FR(`download`,e.downloading,e.label),children:[(0,H.jsx)(jn,{className:`size-3.5 motion-safe:animate-spin`,"aria-hidden":`true`}),e.downloading>1&&(0,H.jsx)(`span`,{className:`text-[10px] tabular-nums`,children:e.downloading})]}),e.uploading>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,"aria-label":FR(`upload`,e.uploading,e.label),title:FR(`upload`,e.uploading,e.label),children:[(0,H.jsx)(qe,{className:`size-3.5 motion-safe:animate-spin`,"aria-hidden":`true`}),e.uploading>1&&(0,H.jsx)(`span`,{className:`text-[10px] tabular-nums`,children:e.uploading})]})]})}var LR=0,RR=null,zR=0;function BR(e,t){let n=[];e.added>0&&n.push(`${e.added.toLocaleString()} new ${e.added===1?`record`:`records`}`),e.updated>0&&n.push(`${e.updated.toLocaleString()} updated`),Z({title:`${e.source} sync complete`,description:n.length>0?`${n.join(`, `)} — feeds can be refreshed anytime.`:`Nothing new — feeds can be refreshed anytime.`,action:(0,H.jsx)(Yk,{altText:`Open notebooks`,onClick:()=>t(`/catalogs`),children:`Open notebooks`})})}function VR(){let e=Sn();return(0,V.useEffect)(()=>{let t=()=>{let t=Sk();!t||t.id<=zR||(zR=t.id,t.updates.length&&Z({title:`Notebook updates`,description:t.updates.map(e=>`${e.label}: ${e.state===`updated`?`updated`:e.state===`error`?`sync failed`:`update available`}`).join(`; `),action:(0,H.jsx)(Yk,{altText:`Manage notebook updates`,onClick:()=>e(`${Q.catalogs}?manage=1`),children:`Review updates`})}))};return t(),Ck(t)},[e]),(0,V.useEffect)(()=>{let t=t=>{if(t.error||(RR=null),t.result&&t.result.id>LR&&(LR=t.result.id,BR(t.result,e)),t.error&&t.error!==RR){RR=t.error;let n=t.error.toLowerCase(),r=/turso|database|token|libsql/.test(n)?Q.settingsStorage:/seed|feed|source|manifest|chunk/.test(n)?Q.settingsSync:Q.settings;Z({title:`Sync failed`,description:t.error,variant:`destructive`,action:(0,H.jsx)(Yk,{altText:`Open settings`,onClick:()=>e(r),children:`Settings`})})}};return t(mb()),hb(()=>t(mb()))},[e]),null}var HR=t({usePaletteStore:()=>UR}),UR=It((e,t)=>({isOpen:!1,request:null,_resolve:null,open(n){let{_resolve:r}=t();return r&&e({_resolve:null}),new Promise(t=>{e({isOpen:!0,request:n,_resolve:t})})},_select(n){let{_resolve:r}=t();e({_resolve:null}),r?.({dismissed:!1,item:n}),setTimeout(()=>{t()._resolve||e({isOpen:!1,request:null})},0)},_dismiss(){let{_resolve:n}=t();e({isOpen:!1,request:null,_resolve:null}),n?.({dismissed:!0})}}));function WR(e,t){if(!t)return!0;let n=t.toLowerCase();return!!(e.label.toLowerCase().includes(n)||e.subtitle?.toLowerCase().includes(n)||e.keywords?.some(e=>e.toLowerCase().includes(n)))}function GR(e){let{items:t,defaultActiveId:n,multi:r=!1,onSelect:i}=e,[a,o]=(0,V.useState)(n??null),[s,c]=(0,V.useState)(new Set),[l,u]=(0,V.useState)(``),d=(0,V.useRef)(null);(0,V.useEffect)(()=>{n!==void 0&&o(n)},[n]);let f=(0,V.useMemo)(()=>l?t.filter(e=>WR(e,l)):t,[t,l]),p=(0,V.useMemo)(()=>{let e=new Map;for(let t of f){let n=t.group??``;e.has(n)||e.set(n,[]),e.get(n).push(t)}return e},[f]),m=(0,V.useCallback)((e,t)=>{c(n=>{let i=new Set(n);if(r&&t?.shift&&d.current){let t=f.findIndex(e=>e.id===d.current),n=f.findIndex(t=>t.id===e);if(t!==-1&&n!==-1){let[e,r]=t<n?[t,n]:[n,t];f.slice(e,r+1).forEach(e=>i.add(e.id))}}else r&&t?.ctrl?i.has(e)?i.delete(e):i.add(e):(i.clear(),i.add(e));return i}),d.current=e},[r,f]),h=(0,V.useCallback)(()=>{c(new Set),d.current=null},[]),g=(0,V.useCallback)(e=>{o(e.id),m(e.id),i?.(e)},[i,m]);return{visibleItems:f,groups:p,activeId:a,setActiveId:o,selectedIds:s,toggleSelected:m,clearSelection:h,query:l,setQuery:u,onKeyDown:(0,V.useCallback)(e=>{if(!f.length)return;let t=f.findIndex(e=>e.id===a);if(e.key===`ArrowDown`){e.preventDefault();let n=f[Math.min(t+1,f.length-1)];o(n.id)}else if(e.key===`ArrowUp`){e.preventDefault();let n=f[Math.max(t-1,0)];o(n.id)}else if(e.key===`Enter`){e.preventDefault();let t=f.find(e=>e.id===a);t&&g(t)}else e.key===`Escape`&&h()},[f,a,g,h]),selectItem:g}}function KR(e){return e===`meta`?`⌘`:e===`shift`?`⇧`:e===`alt`?`⌥`:e}function qR({tokens:e,delimiter:t}){return(0,H.jsx)(`span`,{className:`flex items-center gap-0.5 ml-auto shrink-0`,children:e.map((e,n)=>(0,H.jsxs)(`span`,{className:`contents`,children:[n>0&&t?(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`px-0.5 text-[10px] font-mono text-zinc-400 dark:text-zinc-500`,children:t}):null,(0,H.jsx)(`kbd`,{className:`inline-flex items-center rounded border border-zinc-300 bg-zinc-100 px-1 py-0.5 text-[10px] font-mono text-zinc-500 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:KR(e)})]},`shortcut-${n}-${e}`))})}function JR({item:e,ctx:t}){let n=t.actions.find(e=>e.isPrimary),r=t.actions.filter(e=>!e.isPrimary);return(0,H.jsxs)(`div`,{role:`option`,"aria-selected":t.isSelected,className:U(`flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer select-none`,`text-sm transition-colors`,t.isActive||t.isSelected?`bg-primary/10 text-primary`:`hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-700 dark:text-zinc-300`,e.isDisabled&&`opacity-40 pointer-events-none`,e.depth&&e.depth>0?`pl-${Math.min(e.depth*4+3,16)}`:``),onClick:e.isDisabled?void 0:t.onSelect,children:[e.icon&&(0,H.jsx)(`span`,{className:`shrink-0 text-zinc-400 dark:text-zinc-500 w-4 h-4 flex items-center justify-center`,children:e.icon}),(0,H.jsxs)(`span`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:e.label}),e.subtitle&&(0,H.jsx)(`span`,{className:`truncate text-xs text-zinc-500 dark:text-zinc-400 leading-tight mt-0.5`,children:e.subtitle})]}),e.badge!==void 0&&(0,H.jsx)(`span`,{className:`shrink-0 rounded-full bg-zinc-200 dark:bg-zinc-700 px-1.5 py-0.5 text-[10px] font-medium text-zinc-600 dark:text-zinc-300`,children:e.badge}),e.shortcut&&e.shortcut.length>0&&(0,H.jsx)(qR,{tokens:e.shortcut}),r.length>0&&(0,H.jsx)(`span`,{className:`flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-1`,children:r.map(e=>(0,H.jsx)(`button`,{title:e.label,className:`rounded p-0.5 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-400 hover:text-zinc-600`,onClick:n=>{n.stopPropagation(),t.executeAction(e.action)},children:e.icon??e.label},e.id))}),n&&(0,H.jsx)(`button`,{title:n.label,className:`shrink-0 rounded px-2 py-1 text-xs bg-primary text-primary-foreground hover:bg-primary/90 transition-colors`,onClick:e=>{e.stopPropagation(),t.executeAction(n.action)},children:n.icon??n.label})]})}function YR({items:e,query:t,onQueryChange:n,onSelect:r,isOpen:i,onClose:a,header:o,searchRow:s,footer:c,filterResults:l=!0,placeholder:u=`Search…`,actions:d,renderItem:f,mobileClose:p,emptyState:m,className:h}){let g=(0,V.useRef)(null),_=(0,V.useRef)(null),v=Sn(),[y,b]=Ct(),x=(0,V.useMemo)(()=>({navigate:(e,t)=>v(e,t),setQueryParam:(e,t)=>{let n=new URLSearchParams(y);Object.entries(e).forEach(([e,t])=>{t===null?n.delete(e):n.set(e,t)}),b(n,{replace:t})}}),[v,y,b]),S=(0,V.useCallback)(e=>KM(e,x),[x]),C=(0,V.useCallback)(e=>{let t=[...e.actions??[],...d?.(e)??[]].find(e=>e.isPrimary);t?S(t.action):r(e)},[d,r,S]),w=GR({items:e,onSelect:C});return(0,V.useEffect)(()=>{i&&!s&&setTimeout(()=>g.current?.focus(),0)},[i,s]),(0,V.useEffect)(()=>{w.setQuery(l?t:``)},[t,l]),(0,V.useEffect)(()=>{if(w.activeId){for(let e of _.current?.querySelectorAll(`[data-item-id]`)??[])if(e.dataset.itemId===w.activeId){e.scrollIntoView?.({block:`nearest`});break}}},[w.activeId]),i?(0,H.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:U(`flex flex-col overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-700 dark:bg-zinc-900`,h),onKeyDown:e=>{e.key===`Escape`&&a()},children:[(0,H.jsx)(`div`,{onKeyDown:e=>{if(e.key===`Escape`){a();return}if(e.key===`Enter`&&!e.defaultPrevented&&w.visibleItems.length>0){e.preventDefault();let t=w.visibleItems.find(e=>e.id===w.activeId)??w.visibleItems[0];C(t);return}e.key===`ArrowDown`&&!e.defaultPrevented&&w.visibleItems.length>0&&(e.preventDefault(),w.setActiveId(w.visibleItems[0].id),_.current?.focus())},children:s??(0,H.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 dark:border-zinc-700`,children:[(0,H.jsx)(Xn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,H.jsx)(`input`,{ref:g,type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:u,className:`flex-1 bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground`}),p&&(0,H.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close`,"data-testid":`palette-cancel`,className:`-mr-1 rounded-md p-1.5 text-muted-foreground hover:text-foreground sm:hidden`,children:(0,H.jsx)(Te,{className:`h-4 w-4`})}),(0,H.jsx)(`kbd`,{className:`hidden rounded border border-zinc-200 px-1.5 py-0.5 text-[10px] text-zinc-400 sm:inline dark:border-zinc-600`,children:`esc`})]})}),o,(0,H.jsx)(`div`,{ref:_,role:`listbox`,"aria-label":`Results`,"aria-activedescendant":w.activeId??void 0,tabIndex:-1,onKeyDown:e=>{if(e.key===`Escape`){a();return}w.onKeyDown(e)},className:`min-h-0 flex-1 overflow-y-auto p-1 outline-none`,children:w.visibleItems.length===0?m??(t?(0,H.jsxs)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:[`No results found for`,` `,(0,H.jsxs)(`span`,{className:`font-medium text-zinc-600 dark:text-zinc-300`,children:[`“`,t,`”`]})]}):(0,H.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`No results`})):Array.from(w.groups.entries()).map(([e,t])=>(0,H.jsxs)(`div`,{className:`mb-1`,children:[e&&(0,H.jsx)(`div`,{className:`px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500`,children:e}),t.map(e=>{let t=[...e.actions??[],...d?.(e)??[]],n={isSelected:w.selectedIds.has(e.id),isActive:w.activeId===e.id,depth:e.depth??0,actions:t,onSelect:()=>w.selectItem(e),executeAction:S};return(0,H.jsx)(`div`,{id:e.id,"data-item-id":e.id,className:`group`,onMouseEnter:()=>w.setActiveId(e.id),children:f?f(e,n):(0,H.jsx)(JR,{item:e,ctx:n})},e.id)})]},e))}),c]}):null}var XR=150,ZR=.66,QR=.92;function $R(){let[e,t]=(0,V.useState)(()=>typeof window>`u`||window.matchMedia(`(min-width: 1024px)`).matches);return(0,V.useEffect)(()=>{let e=window.matchMedia(`(min-width: 1024px)`),n=()=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function ez(e){let t=e.trim();return t?!Y(t).error||t.startsWith(`:`)&&!/^:\w+\{text:[^}]*\}$/.test(t):!1}function tz(e){return{id:e.id,label:e.label,subtitle:e.sublabel,group:e.category,keywords:[e.label,e.category??``],payload:e}}var nz=()=>{let{isOpen:e,request:t,_select:n,_dismiss:r}=UR(),[i,a]=(0,V.useState)(``),o=(0,V.useRef)(``),s=(0,V.useRef)(),[c,l]=(0,V.useState)({valid:!0}),u=(0,V.useRef)(c),d=$R(),[f,p]=(0,V.useState)(),m=f?f===`wql`:ez(i),h=(0,V.useCallback)(e=>{o.current=e,a(e);let t=Y(e);!t.error&&tm(t)&&(s.current=e)},[]),g=(0,V.useCallback)(e=>{u.current=e,l(e)},[]),[_,v]=(0,V.useState)([]),[y,b]=(0,V.useState)(!1),x=(0,V.useRef)(0),S=(0,V.useRef)(t),C=(0,V.useRef)(0);S.current!==t&&(S.current=t,C.current+=1);let w=Sn();(0,V.useEffect)(()=>{if(!e)return;w(window.location.pathname+window.location.search+window.location.hash,{state:{...history.state?.usr??{},paletteClose:!0}});let t=()=>r();return window.addEventListener(`popstate`,t),()=>{window.removeEventListener(`popstate`,t),history.state?.usr?.paletteClose&&w(-1)}},[e,r,w]);let T=t?.wql,E=sS(),D=E.height?`${Math.round(E.height*ZR)}px`:`66dvh`,O=E.height?`${Math.round(E.height*QR)}px`:`92dvh`;(0,V.useEffect)(()=>{if(e&&t){let e=t.wql?t.wql.initialQuery??``:t.initialQuery??``;o.current=e,a(e);let n=Y(e);s.current=!n.error&&tm(n)?e:void 0;let r=t.wql?n.error:void 0,i=r?{valid:!1,error:r}:{valid:!0};u.current=i,l(i),p(void 0),v([]),b(!1)}},[e,t]),(0,V.useEffect)(()=>{if(!e||!t)return;if(t.wql&&m&&!c.valid){x.current+=1,b(!1);return}let n=++x.current;b(!0);let r=setTimeout(()=>{(async()=>{try{let e=await Promise.all(t.sources.map(e=>Promise.resolve(s.current?e.search(i,{scopeWql:s.current}):e.search(i)).then(t=>t.map(t=>({...tz(t),group:t.category??e.label})))));if(n!==x.current)return;v(e.flat())}catch(e){console.error(`[PaletteShell] search error`,e),n===x.current&&v([])}finally{n===x.current&&b(!1)}})()},XR);return()=>clearTimeout(r)},[i,c.valid,m,e,t]);let k=(0,V.useCallback)(e=>{n(e.payload)},[n]),A=(0,V.useCallback)(e=>{if(!T?.onApply)return;let t=e??o.current;Y(t).error||(T.onApply(t),r())},[T,r]),j=y?(0,H.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`Searching…`}):i?(0,H.jsxs)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:[`No results for `,(0,H.jsxs)(`span`,{className:`font-medium text-foreground/60`,children:[`“`,i,`”`]})]}):(0,H.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`Start typing to search`}),M=T?(0,H.jsxs)(`div`,{className:`border-b border-border/80 px-3 py-2`,children:[(0,H.jsx)(`button`,{type:`button`,"data-testid":`palette-mode`,"aria-pressed":m,"aria-label":m?`WQL mode. Press to switch to Find`:`Find mode. Press to switch to WQL`,onClick:()=>p(m?`find`:`wql`),className:`mb-2 rounded-full border px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wider transition-colors ${m?`border-primary/40 bg-primary/10 text-primary`:`border-border bg-muted text-muted-foreground hover:text-foreground`}`,children:m?`WQL`:`Find`}),(0,H.jsx)(`div`,{className:m?void 0:`[&_[role=alert]]:hidden [&_[data-testid=wql-composer-pending]]:hidden`,children:(0,H.jsx)(EC,{query:i,onQueryChange:h,onValidationChange:g,showDiagnostics:m&&(T.showDiagnostics??!0),execute:T.execute,preferredChoices:T.preferredChoices,customSlots:T.customSlots,diagnosticsPosition:`top`,onSubmit:T.onApply?A:void 0,autoFocus:d,placeholder:`Search or edit WQL…`},C.current)})]}):void 0,N=T?(0,H.jsxs)(`div`,{className:`flex items-center gap-2 border-t border-border/80 px-3 pt-2`,style:{paddingBottom:`max(0.5rem, env(safe-area-inset-bottom))`},children:[m&&!c.valid&&(0,H.jsx)(`span`,{"data-testid":`palette-stale`,className:`text-[11px] font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400`,children:`Stale — fix the query`}),(0,H.jsx)(`div`,{className:`flex-1`}),(0,H.jsx)(`button`,{type:`button`,onClick:r,"data-testid":`palette-cancel`,className:`min-h-12 rounded-md border border-border bg-background px-4 py-2 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:`Cancel`}),T.onApply&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>A(),disabled:!c.valid,"data-testid":`palette-apply-query`,className:`min-h-12 rounded-md bg-primary px-4 py-2 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,children:`Apply query`})]}):void 0,P=(0,V.useCallback)(e=>{e||r()},[r]);return(0,H.jsx)(pt,{open:e,onOpenChange:P,children:(0,H.jsxs)(Jn,{children:[(0,H.jsx)(sn,{className:`fixed inset-0 z-50 bg-black/50 backdrop-blur-sm`}),(0,H.jsxs)(Rn,{className:`fixed inset-x-0 z-50 mx-auto flex w-full flex-col outline-none max-lg:bottom-0 max-lg:top-auto max-lg:rounded-t-2xl max-lg:max-h-[var(--palette-max-h)] max-lg:min-h-[var(--palette-min-h)] lg:top-[10%] lg:max-h-[80vh] lg:rounded-xl ${T?`max-w-2xl`:`max-w-xl`}`,style:{"--palette-min-h":D,"--palette-max-h":O},children:[(0,H.jsx)(Dt,{className:`sr-only`,children:`Command Palette`}),(0,H.jsx)(St,{className:`sr-only`,children:`Search and navigate. Press Escape to close.`}),(0,H.jsx)(YR,{className:`min-h-0 flex-1 border-border bg-card dark:bg-card`,items:_,query:i,onQueryChange:h,onSelect:k,isOpen:!0,onClose:r,mobileClose:!0,placeholder:t?.placeholder??`Search…`,searchRow:M,footer:N,filterResults:!T,header:t?.header,emptyState:j})]})]})})},rz=[{id:`amrap`,label:`AMRAP`,terms:[`amrap`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=amrap`},{id:`emom`,label:`EMOM`,terms:[`emom`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=emom`},{id:`tabata`,label:`Tabata`,terms:[`tabata`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=tabata-intervals`},{id:`rest`,label:`Rest`,terms:[`rest`,`:*`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=required-rest`},{id:`duration`,label:`Duration`,terms:[`duration`,`5:00`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=countdown-countup`},{id:`ladder`,label:`Ladder`,terms:[`ladder`,`21-15-9`],route:`/guide/structure`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=rep-schemes`},{id:`rounds`,label:`Rounds`,terms:[`rounds`],route:`/guide/structure?h=rounds`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=rounds`},{id:`supersets`,label:`Supersets`,terms:[`supersets`],route:`/guide/structure?h=nesting`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=nesting`},{id:`actual`,label:`Actual result`,terms:[`actual`,`:?`],route:`/guide/metrics`,sublabel:`Capture & feedback`,gridRoute:`/guide/metrics?h=capture`},{id:`load-prompt`,label:`Load prompt`,terms:[`load prompt`,`?lb`,`225lb`,`load`],route:`/guide/metrics`,sublabel:`Capture & feedback`,gridRoute:`/guide/metrics?h=capture`},{id:`metrics`,label:`Metrics`,terms:[`metrics`,`reps`,`effort`,`discipline`],route:`/guide/metrics?h=planned-vs-recorded`,sublabel:`Planned vs recorded`,gridRoute:`/guide/metrics?h=planned-vs-recorded`},{id:`palette`,label:`Command palette`,terms:[`palette`,`⌘/`],route:`/guide/start?h=reference`,sublabel:`Syntax reference`,gridRoute:`/guide/start?h=reference`}];Object.fromEntries(rz.map(e=>[e.id,e]));function iz(){return{id:`constructs`,label:`Reference`,search:e=>{let t=e.toLowerCase().trim();return t?rz.filter(e=>{let n=e.label.toLowerCase();return n.includes(t)||t.includes(n)?!0:e.terms.some(e=>{let n=e.toLowerCase();return n.includes(t)||t.includes(n)})}).map(e=>({id:`construct:${e.id}`,label:e.label,sublabel:e.sublabel,category:`Reference`,type:`route`,payload:{route:e.route}})):[]}}}function az(e,t){return`${e}/${t}`}function oz(e){let t=e.indexOf(`/`);return t<0?e:e.slice(0,t)}function sz(e){return e.slug??e.id}function cz(e){let t=sz(e);return{id:e.id,slug:e.slug,category:oz(t),name:e.title||t,content:e.rawContent??``,noteBlocks:e.blocks,sourceRevision:e.sourceRevision,updatedAt:e.updatedAt??Date.now(),type:e.type,sourceId:e.sourceId}}var lz=new ID,uz={pageId:az,async getPage(e){let t=await lz.getEntry(e);return t?cz(t):void 0},async savePage(e){let t=await lz.getEntry(e.id);return t?(await lz.updateEntry(t.id,{rawContent:e.content,expectedSourceRevision:e.sourceRevision,blocks:e.noteBlocks,title:e.name,slug:e.slug}),t.id):(await lz.saveEntry({id:e.id,slug:e.slug,title:e.name,rawContent:e.content,blocks:e.noteBlocks,tags:[],targetDate:e.updatedAt,type:`playground`})).id},async addPage(e){if(await lz.getEntry(e.id))throw new DOMException(`Page already exists: ${e.id}`,`ConstraintError`);return this.savePage(e)},async getAllPages(){return(await lz.getEntries()).map(cz)},async getPagesByCategory(e){return(await lz.getEntries()).filter(t=>oz(sz(t))===e).map(cz)},async deletePage(e){await lz.deleteEntry(e)},async clearAll(){let e=await lz.getEntries();await Promise.all(e.filter(e=>e.id.includes(`/`)).map(e=>lz.deleteEntry(e.id)))}};function dz(e){return{id:`canvas-routes`,label:`Pages`,search:t=>{let n=t.toLowerCase();return e.filter(e=>{let t=e.page.sections[0]?.heading??e.route;return!n||t.toLowerCase().includes(n)||e.route.toLowerCase().includes(n)}).slice(0,5).map(e=>{let t=e.page.sections[0]?.heading??e.route;return{id:`route:${e.route}`,label:t,sublabel:e.route,category:`Pages`,type:`route`,payload:{route:e.route}}})}}}function fz(e){let t=[],n=/```(time|log)(:\w+)?\r?\n([\s\S]*?)```/gi,r,i=0;for(;(r=n.exec(e))!==null;){let e=r[1].toLowerCase(),n=r[3],a=n.split(`
128
128
  `).find(e=>e.trim())?.trim()??`(empty block)`;t.push({index:i++,script:n,preview:a,dialect:e})}return t}function pz(e){return BE(`feeds`,e).map(e=>({id:e.id,name:e.name,readme:e.readme,categories:e.categories,items:e.items.map(({id:e,name:t,content:n,path:r,date:i})=>({id:e,name:t,content:n,feedDate:i??``,path:r})).sort((e,t)=>t.feedDate.localeCompare(e.feedDate))})).sort((e,t)=>e.name.localeCompare(t.name))}var mz=null,hz=[];async function gz(){let e=await rD();return mz!==e&&(mz=e,hz=pz(e)),hz}function _z(){return new Date().toISOString().slice(0,10)}function vz(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(Date.UTC(t,n-1,r)).toLocaleDateString(`en`,{year:`numeric`,month:`short`,day:`numeric`,timeZone:`UTC`})}var yz=[{value:`blank`,label:`Blank`},{value:`template`,label:`Template`},{value:`source`,label:`Source`}],bz=`h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`;function xz({open:e,onOpenChange:t,defaultDate:n,defaultMode:r=`blank`,onCreated:i}){let[a,o]=(0,V.useState)(r),[s,c]=(0,V.useState)(()=>Vj()),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(null),[y,b]=(0,V.useState)(null),[x,S]=(0,V.useState)(null),C=(0,V.useRef)(0),w=(0,V.useRef)(0),T=(0,V.useRef)(!1),[E,D]=(0,V.useState)(``),[O,k]=(0,V.useState)(``),[A,j]=(0,V.useState)(``);(0,V.useEffect)(()=>{e&&(C.current++,w.current++,o(r),c(n&&Uj(n)?n:Vj()),f(!1),m(null),D(``),k(``),j(``),g(null),v(null),b(null),S(null))},[e,n]);let M=()=>{let e=++C.current;g(null),v(null),Nj.listNotes({kind:`template`}).then(t=>{C.current===e&&g(t)}).catch(()=>{C.current===e&&v(`Could not load templates.`)})},N=()=>{let e=++w.current;b(null),S(null),Promise.all([WE(),gz(),X.getAllNotes()]).then(([t,n,r])=>{if(w.current!==e)return;let i={};for(let e of r)e.sourcePath&&(i[e.sourcePath]=e.id);b({collections:t,feeds:n,sourceIdByPath:i})}).catch(()=>{w.current===e&&S(`Could not load collections and feeds.`)})};(0,V.useEffect)(()=>{e&&(a===`template`&&h===null&&!_&&M(),a===`source`&&y===null&&!x&&N())},[e,a,h,_,y,x]);let P=(0,V.useMemo)(()=>h?.find(e=>e.id===E)??null,[h,E]),F=(0,V.useMemo)(()=>{if(!y||!O)return null;let e=O.indexOf(`:`);if(e<0)return null;let t=O.slice(0,e),n=O.slice(e+1);if(t===`collection`){let e=y.collections.find(e=>e.id===n);return e?{kind:`collection`,group:e}:null}if(t===`feed`){let e=y.feeds.find(e=>e.id===n);return e?{kind:`feed`,group:e}:null}return null},[y,O]),I=F?F.group.items.find(e=>e.path===A)??null:null,ee=Uj(s),te=s!==``&&!ee,ne=`Journal — ${vz(ee?.dateKey??Vj())}`,re=a===`template`?P===null:a===`source`&&I===null;return(0,H.jsx)(lS,{open:e,onClose:()=>{T.current||t(!1)},title:`New journal note`,description:`Add a note to a day in your journal.`,presentation:`sheet`,footer:(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(W,{type:`button`,variant:`outline`,size:`lg`,onClick:()=>t(!1),disabled:d,children:`Cancel`}),(0,H.jsx)(W,{type:`submit`,form:`create-journal-note-form`,size:`lg`,disabled:!ee||re||d,children:d?`Creating…`:`Create`})]}),children:(0,H.jsxs)(`form`,{id:`create-journal-note-form`,onSubmit:async e=>{e.preventDefault();let n=Uj(s);if(!n||T.current||re)return;let r;if(a===`template`&&P)r={journalDate:n.dateKey,title:l.trim()||P.title||ne,rawContent:P.rawContent,tags:P.tags,sourceId:P.id,type:`journal`};else if(a===`source`&&I&&F&&y){let e=y.sourceIdByPath[I.path];if(!e){m(`No stored source note matches this item. Your input is kept — pick another item or use Blank.`);return}r={journalDate:n.dateKey,title:l.trim()||I.name,rawContent:I.content,tags:[],sourceId:e,type:`journal`}}else r={journalDate:n.dateKey,title:l.trim()||ne,rawContent:``,tags:[],type:`journal`};T.current=!0,f(!0),m(null);try{let e=await Kj.create(r);i?.(e),t(!1)}catch{m(`Could not create the note. Your input is kept — try again.`)}finally{T.current=!1,f(!1)}},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,H.jsx)(`div`,{role:`group`,"aria-label":`Start from`,className:`grid grid-cols-3 gap-1.5`,children:yz.map(e=>(0,H.jsx)(`button`,{type:`button`,"aria-pressed":a===e.value,onClick:()=>o(e.value),disabled:d,className:`min-h-11 rounded-md border px-2 text-sm font-medium transition-colors `+(a===e.value?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:bg-muted/60`),children:e.label},e.value))}),a===`template`&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`journal-create-template`,className:`text-sm font-medium`,children:`Template`}),_?(0,H.jsxs)(`div`,{className:`flex min-h-11 items-center justify-between gap-2`,children:[(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),(0,H.jsx)(W,{type:`button`,variant:`ghost`,size:`sm`,onClick:M,children:`Retry`})]}):h===null?(0,H.jsx)(`p`,{className:`flex min-h-11 items-center text-sm text-muted-foreground`,children:`Loading templates…`}):h.length===0?(0,H.jsx)(`p`,{className:`flex min-h-11 items-center text-sm text-muted-foreground`,children:`No templates available. Choose Blank or Source.`}):(0,H.jsxs)(`select`,{id:`journal-create-template`,value:E,onChange:e=>D(e.target.value),disabled:d,className:bz,children:[(0,H.jsx)(`option`,{value:``,children:`Choose a template…`}),h.map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.title||e.id},e.id))]})]}),a===`source`&&(0,H.jsx)(`div`,{className:`flex flex-col gap-3`,children:x?(0,H.jsxs)(`div`,{className:`flex min-h-11 items-center justify-between gap-2`,children:[(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:x}),(0,H.jsx)(W,{type:`button`,variant:`ghost`,size:`sm`,onClick:N,children:`Retry`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`journal-create-source-group`,className:`text-sm font-medium`,children:`Feed`}),(0,H.jsxs)(`select`,{id:`journal-create-source-group`,value:O,onChange:e=>{k(e.target.value),j(``)},disabled:y===null||d,className:bz,children:[(0,H.jsx)(`option`,{value:``,children:y===null?`Loading…`:`Choose a feed…`}),y&&y.collections.length>0&&(0,H.jsx)(`optgroup`,{label:`Feeds`,children:y.collections.map(e=>(0,H.jsx)(`option`,{value:`collection:${e.id}`,children:e.name},e.id))}),y&&y.feeds.length>0&&(0,H.jsx)(`optgroup`,{label:`Feeds`,children:y.feeds.map(e=>(0,H.jsx)(`option`,{value:`feed:${e.id}`,children:e.name},e.id))})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`journal-create-source-item`,className:`text-sm font-medium`,children:`Item`}),(0,H.jsxs)(`select`,{id:`journal-create-source-item`,value:A,onChange:e=>j(e.target.value),disabled:!F||d,className:bz,children:[(0,H.jsx)(`option`,{value:``,children:F?`Choose an item…`:`Choose a feed first`}),F?.group.items.map(e=>(0,H.jsx)(`option`,{value:e.path,children:`feedDate`in e?`${e.name} — ${e.feedDate}`:e.name},e.path))]})]})]})}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`journal-create-date`,className:`text-sm font-medium`,children:`Date`}),(0,H.jsx)(`input`,{id:`journal-create-date`,type:`date`,value:s,onChange:e=>c(e.target.value),disabled:d,"aria-invalid":te||void 0,className:bz}),te&&(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:`Enter a valid date (YYYY-MM-DD).`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsxs)(`label`,{htmlFor:`journal-create-title`,className:`text-sm font-medium`,children:[`Title `,(0,H.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:`(optional)`})]}),(0,H.jsx)(`input`,{id:`journal-create-title`,type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:ne,disabled:d,className:bz})]}),p&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p})]})})}function Sz(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Cz(e){let t=(()=>{switch(e.kind){case`note`:{if(e.sourceCatalog===`guides`)return e.pageSlug?`/p/${Sz(e.pageSlug)}`:`/${Sz(e.sourceItem.replace(/^\//,``))}`;if(e.sourceCatalog===`playground`)return`/playground/${encodeURIComponent(e.sourceItem)}`;let t=/^markdown\/dashboards\/(.+)\.md$/.exec(e.sourcePath??``);if(t?.[1])return`/d/${Sz(t[1])}`;let n=/^markdown\/efforts\/[^/]+\/(.+)\.md$/.exec(e.sourcePath??``);return n?.[1]?`/e/${Sz(n[1])}`:e.pageSlug?`/p/${Sz(e.pageSlug)}`:qA(e.id)}case`session`:return e.sourceItem?`/c/${encodeURIComponent(e.sourceCatalog)}/${encodeURIComponent(e.sourceItem)}`:`/c/${encodeURIComponent(e.sourceCatalog)}`;case`dashboard`:return e.sourceCatalog===`dashboards`&&e.sourceItem?`/d/${Sz(e.sourceItem)}`:qA(e.id);case`equipment`:{let t=e.sourceItem??e.id,n=t.startsWith(`equipment/`)?t.slice(10):t,r=/^(?:uuid-|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)/i.test(n);return n&&!r?`/equipment/${Sz(n)}`:qA(e.id)}case`post`:{let t=e.date??``;return`/feeds/${encodeURIComponent(e.sourceCatalog)}/${encodeURIComponent(t)}/${encodeURIComponent(e.sourceItem)}`}case`effort`:return`/e/${encodeURIComponent(e.effort?.slug??e.id)}`;case`result`:return ej(e.id);case`segment`:case`event`:return ej(e.execution?.resultId??(e.sourceCatalog===`results`?e.sourceItem:e.id));default:return`/`}})();return e.block?`${t}#${encodeURIComponent(e.block.blockId)}`:t}function wz(e){return e.sourceCatalog===`playground`||e.sourceId===`playground`}function Tz(e){return e.kind===`session`&&!e.sourceItem?`/feeds?q=${encodeURIComponent(`:notebook{notebook:${e.sourceCatalog}}`)}`:null}function Ez(e){return e.blockContentId?aj({q:e.blockContentId}):null}function Dz(e){return!!(e.kind===`note`||e.kind===`post`||(e.kind===`result`||e.kind===`segment`)&&e.execution?.noteId)}var Oz=20,kz={note:`Journal`,session:`Feeds`,post:`Feeds`,effort:`Efforts`,result:`Results`,segment:`Segments`,event:`Events`,dashboard:`Dashboards`,equipment:`Equipment`};function Az(e){return{id:`entry:${e.id}`,label:e.title,sublabel:e.subtitle??e.date??void 0,category:kz[e.kind],type:`entry`,payload:e}}function jz(e,t){let n=e.filters.filter(e=>!(e.key===`text`&&!e.negate));return t&&n.push({key:`text`,negate:!1,values:[{value:t,wildcard:!1}]}),Km({...e,filters:n})}function Mz(){return{id:`wql-search`,label:`Search`,search:async(e,t)=>{if(!Y(e).error)return(await kI(e)).slice(0,Oz).map(Az);if(e.trimStart().startsWith(`:`))return[];let n=e.trim(),r=(n.startsWith(`"`)&&n.endsWith(`"`)&&n.length>1?n.slice(1,-1):n).replaceAll(`"`,``),i=Y(t?.scopeWql??Fz());return i.error||!tm(i)?[]:(await kI(jz(i,r))).slice(0,Oz).map(Az)}}}function Nz(e){let t=Y(e);return tm(t)&&!t.error?t.filters.filter(e=>e.key===`text`&&!e.negate).flatMap(e=>e.values.map(e=>e.value)).join(` `):e.replace(/^:\w+/,` `).replace(/\bin\s+\w+/g,` `).replace(/\blast\s+\w+/g,` `).replace(/\bwhere\b/g,` `).replace(/[{()}]/g,` `).replace(/\b\w+:/g,` `).replace(/\s+/g,` `).trim()}function Pz(e){return{id:`${e.id}:wql-text`,label:e.label,search:t=>e.search(Nz(t))}}function Fz(){return HM(`/palette`).defaultWql??`:note{source:journal,feeds} by {date}`}function Iz(){return HM(`/palette`).typeOptions??[]}var Lz=e=>tm(e)?XF.runFind(e):XF.runQuery(e.raw);function Rz(e,t){if(e.type===`route`){let n=e.payload;t(n.route)}else if(e.type===`entry`){let n=e.payload;t(Cz(n))}}var zz=new Set([`syntax`]),Bz=new Set([`journal`,`playground`,`canvas`,`syntax`]),Vz=`$CURSOR`;function Hz(e){let t=e.indexOf(Vz);return t===-1?{content:e,cursorOffset:e.length}:{content:e.slice(0,t)+e.slice(t+7),cursorOffset:t}}function Uz(){let e=typeof window<`u`?window.history.state?.idx:void 0;return typeof e==`number`&&e>0}function Wz(e){let t=e.split(`
129
129
  `),n=[],r=0,i=0,a=new Map,o=e=>{let t=(a.get(e)??0)+1;return a.set(e,t),t===1?e:`${e}-${t}`},s=e=>{for(let n=e+1;n<t.length;n++){let e=t[n];if(e.trim()==="```")break;let r=e.match(/^title:\s*(.+)$/);if(r)return r[1].trim().replace(/^["']|["']$/g,``)}};for(let e=0;e<t.length;e++){let a=t[e],c=a.match(/^(#{1,6})\s+(.*)$/);if(c){let e=c[2].trim(),t,r=e.match(/(\d{1,2}:\d{2})/);r&&(t=r[1],e=e.replace(t,``).replace(/\s+/g,` `).trim(),e||=t);let i=o(e.toLowerCase().replace(/[^\w]+/g,`-`));n.push({id:i,label:e,type:`heading`,timestamp:t});continue}let l=a.trim().match(/^```(time|log|query|widget)(:[-\w]+)?\s*$/);if(l){let t=l[1];t===`query`?(i++,n.push({id:`query-line-${e+1}`,label:s(e)??`Query ${i}`,type:`query`})):t===`widget`?n.push({id:`widget-line-${e+1}`,label:(l[2]??``).slice(1)||`Widget`,type:`widget`}):(r++,n.push({id:`${t}-line-${e+1}`,label:`Workout ${r}`,type:t}))}}return n}function Gz(e){return e.map(e=>({id:e.id,label:e.label,level:3,action:e.onRun&&e.runIcon===`link`?{type:`call`,handler:e.onRun}:{type:`scroll`,sectionId:e.id},secondaryAction:e.onRun?{id:e.id+(e.runIcon===`edit`?`-edit`:`-run`),label:e.runIcon===`edit`?`Edit`:`Run`,icon:e.runIcon===`edit`?o:e.runIcon===`link`?l:rn,action:{type:`call`,handler:e.onRun}}:void 0,secondaryRunIcon:e.runIcon}))}function Kz(e){let{setL3Items:t,registerScrollFn:n,dispatch:r}=hA(),i=(0,V.useRef)(null),a=(0,V.useCallback)(e=>{i.current=e},[]),o=(0,V.useCallback)(e=>{if(!e)return;let t=(e=>{let t=document.getElementById(e);if(t||(t=document.querySelector(`[data-section-id="${e}"]`),t))return t;let n=e.split(`:`);for(let e of n)if(e&&(t=document.getElementById(e)??document.querySelector(`[data-section-id="${e}"]`),t))return t;return null})(e);if(t){let e=t.style.scrollMarginTop,n=window.innerWidth<1024,r=!!document.querySelector(`.lg\\:hidden.sticky`),i=`96px`;n&&(i=r?`calc(50vh + 40px)`:`75px`),t.style.scrollMarginTop=i,t.scrollIntoView({behavior:`smooth`,block:`start`}),requestAnimationFrame(()=>{t.style.scrollMarginTop=e});return}if(i.current){let t=i.current,n=t.state.doc.toString().split(`
130
- `),r=-1,a=e.match(/^(?:workout|time|log|query|widget)-line-(\d+)$/);if(a)r=Number(a[1])-1;else{let i=(t.state.field(ZC,!1)?.sections??[]).find(t=>!!(t.id===e||e.includes(`:${t.id}:`)||e.endsWith(`:${t.id}`)));r=i?i.startLine:n.findIndex(t=>{let n=t.match(/^(#{1,6})\s+(.*)$/);if(n){let t=n[2].trim(),r=t.match(/(\d{1,2}:\d{2})/);if(r){let e=r[1];t=t.replace(e,``).replace(/\s+/g,` `).trim(),t||=e}return t.toLowerCase().replace(/[^\w]+/g,`-`)===e}return!1})}if(r>=0&&r<n.length){let e=t.state.doc.line(r+1).from;t.dispatch({selection:{anchor:e,head:e},effects:[Er.scrollIntoView(e,{y:`start`,yMargin:20})]});let n=t.dom.parentElement;if(n&&window.innerWidth>=1024){let e=n.getBoundingClientRect().top+window.scrollY-120;window.scrollTo({top:e,behavior:`smooth`})}}}},[]);return(0,V.useEffect)(()=>{n(o)},[o,n]),(0,V.useEffect)(()=>{if(e.length===0)return;let t=new IntersectionObserver(e=>{let t=null,n=-1;e.forEach(e=>{e.isIntersecting&&e.intersectionRatio>n&&(n=e.intersectionRatio,t=e.target.id)}),t&&r({type:`SET_ACTIVE_L3`,id:t})},{rootMargin:`-10% 0px -50% 0px`,threshold:[0,.25,.5,1]});return e.forEach(e=>{let n=document.getElementById(e.id);n&&t.observe(n)}),()=>t.disconnect()},[e,r]),(0,V.useEffect)(()=>{e.length!==0&&t(Gz(e))},[e,t]),{handleViewCreated:a,scrollToSection:o}}var qz=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0),Jz=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/60),i=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},Yz=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},Xz=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/60),i=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},Zz=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},Qz=e=>e==null||!Number.isFinite(e)?`--:--`:Math.floor(Math.abs(e)/1e3)>=3600?Yz(e):Jz(e),$z=500,eB=900,tB=560;function nB(e,t){let n=e<$z,r=e>=eB,i=!n;return{width:e,height:t,isCompact:n,isWide:i,isFull:r,isShort:t>0&&t<tB,mode:r?`full`:i?`wide`:`compact`}}var rB=nB(800,600),iB=(0,V.createContext)(rB);function aB(){return(0,V.useContext)(iB)}var oB=({children:e})=>{let t=(0,V.useRef)(null),[n,r]=(0,V.useState)(rB),i=(0,V.useCallback)(e=>{let t=e[0];if(!t)return;let n=t.contentRect.width,i=t.contentRect.height;r(e=>{let t=nB(n,i);return e.mode===t.mode&&Math.abs(e.width-n)<2&&Math.abs(e.height-i)<2?e:t})},[]);return(0,V.useEffect)(()=>{let e=t.current;if(!e)return;let n=new ResizeObserver(i);return n.observe(e),()=>n.disconnect()},[i]),(0,H.jsx)(`div`,{ref:t,className:`h-full w-full`,children:(0,H.jsx)(iB.Provider,{value:n,children:e})})},sB={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`,FOCUSED_DIALOG_CLOSE:`focused-dialog-close`,REVIEW_PANEL:`review-panel`,REVIEW_RESULTS_TABLE:`review-results-table`,REVIEW_METRIC_ROW:`review-metric-row`,REVIEW_TOTAL_TIME:`review-total-time`,EDITOR_PANEL:`editor-panel`,EDITOR_CONTENT:`editor-content`,EDITOR_START_WORKOUT:`editor-start-workout`,TESTBENCH_ROOT:`testbench-root`,TESTBENCH_NEXT_BUTTON:`testbench-next`,TESTBENCH_RUNTIME_STACK:`testbench-runtime-stack`,TESTBENCH_MEMORY:`testbench-memory`,TESTBENCH_SCRIPT_EDITOR:`testbench-script-editor`,EFFORTS_CATALOG_ROOT:`efforts-catalog-root`,EFFORTS_CATALOG_SEARCH:`efforts-catalog-search`,EFFORTS_CATALOG_CREATE_BTN:`efforts-catalog-create-btn`,EFFORTS_CATALOG_EMPTY_STATE:`efforts-catalog-empty-state`,EFFORTS_LOADING:`efforts-loading`,EFFORT_DETAIL_ROOT:`effort-detail-root`,EFFORT_DETAIL_LABEL:`effort-detail-label`,EFFORT_DETAIL_ALIASES:`effort-detail-aliases`,EFFORT_DETAIL_ATTRIBUTES:`effort-detail-attributes`,EFFORT_DETAIL_SOURCE:`effort-detail-source`,EFFORT_DETAIL_EDIT_BTN:`effort-detail-edit-btn`,EFFORT_DETAIL_CLONE_BTN:`effort-detail-clone-btn`,EFFORT_DETAIL_SAVE_BTN:`effort-detail-save-btn`,EFFORT_DETAIL_CANCEL_BTN:`effort-detail-cancel-btn`,EFFORT_DETAIL_DELETE_BTN:`effort-detail-delete-btn`,EFFORT_DETAIL_NOTEBOOK_EDITOR:`effort-detail-notebook-editor`,EFFORT_DETAIL_ANALYTICS_PLACEHOLDER:`effort-detail-analytics-placeholder`,EFFORT_NOT_FOUND:`effort-not-found`,EFFORT_NOT_FOUND_CREATE_BTN:`effort-not-found-create-btn`,EFFORT_NOT_FOUND_ALIAS_BTN:`effort-not-found-alias-btn`,EFFORT_NOT_FOUND_ALIAS_SELECT:`effort-not-found-alias-select`,EFFORT_NOT_FOUND_ALIAS_CONFIRM:`effort-not-found-alias-confirm`,EFFORTS_NAV_ORIGIN_FILTER:`efforts-nav-origin-filter`,EFFORTS_NAV_DISCIPLINE_FILTER:`efforts-nav-discipline-filter`,EFFORTS_NAV_RECENT_WORKOUTS:`efforts-nav-recent-workouts`,EFFORTS_NAV_RECENT_WORKOUT_ITEM:`efforts-nav-recent-workout-item`,EQUIPMENT_DETAIL_ROOT:`equipment-detail-root`,EQUIPMENT_DETAIL_LABEL:`equipment-detail-label`,EQUIPMENT_DETAIL_SOURCE:`equipment-detail-source`,EQUIPMENT_DETAIL_CLONE_BTN:`equipment-detail-clone-btn`,EQUIPMENT_DETAIL_NOTEBOOK_EDITOR:`equipment-detail-notebook-editor`,EQUIPMENT_NOT_FOUND:`equipment-not-found`,EQUIPMENT_NOT_FOUND_CREATE_BTN:`equipment-not-found-create-btn`,EQUIPMENT_CREATE_BTN:`equipment-create-btn`,EQUIPMENT_LOAD_ERROR:`equipment-load-error`,COMMAND_PALETTE_TRIGGER:`command-palette-trigger`,COMMAND_PALETTE_INPUT:`command-palette-input`,COMMAND_PALETTE_RESULTS:`command-palette-results`},cB=Jz;function lB(e,t,n=0){let r=e>0?e:800,i=t?Math.min(Math.max(r*.14,56),72,r*.3):Math.min(Math.max(r*.18,128),320,r*.3);return Math.round(n>0?Math.min(i,Math.max(44,n-(t?180:n<560?240:400))):i)}var uB=({children:e})=>{let t=(0,V.useRef)(null),n=(0,V.useRef)(null),[r,i]=(0,V.useState)(1);return(0,V.useLayoutEffect)(()=>{let e=t.current,r=n.current;if(!e||!r)return;let a=()=>{let t=Math.min(1,e.clientWidth/Math.max(r.scrollWidth,1),e.clientHeight/Math.max(r.scrollHeight,1));i(Number.isFinite(t)?Math.max(0,t):0)};a();let o=new ResizeObserver(a);return o.observe(e),o.observe(r),()=>o.disconnect()},[]),(0,H.jsx)(`div`,{ref:t,className:`flex h-full min-h-0 w-full items-center justify-center`,children:(0,H.jsx)(`div`,{ref:n,className:`shrink-0 text-center`,style:{transform:`scale(${r})`,transformOrigin:`center center`},children:e})})},dB=({onStart:e,onPause:t,onStop:n,onNext:r,isRunning:i,isPaused:a=!1,disableNext:o,primaryTimer:s,compact:c=!1,subLabel:l,subLabels:u,secondaryTimers:d,timerStates:f,getFocusProps:p,enableGestures:m=!0,skipFlash:h=!1,skipFlashKey:g=0})=>{let{width:_,height:v,isShort:y}=aB(),b=null;try{b=tk()}catch{}let x=v>0&&v<200,S=c||y||x,C=(0,V.useMemo)(()=>lB(_,c,v),[_,v,c]),w=(0,V.useCallback)(()=>{b?.playClick(),e()},[b,e]),T=(0,V.useCallback)(()=>{b?.playClick(),t()},[b,t]),E=(0,V.useCallback)(()=>{b?.playClick(),n()},[b,n]),D=o??a,O=a?`Continue`:i?`Pause`:`Start`,k=(0,V.useCallback)(()=>{D||(b?.playClick(),r())},[b,D,r]),A=(0,V.useRef)(null),j=(0,V.useRef)(null),M=e=>{j.current=null,A.current=e.targetTouches[0].clientX},N=e=>{j.current=e.targetTouches[0].clientX},P=(0,V.useCallback)(()=>{if(!m||!A.current||!j.current)return;let e=A.current-j.current,t=e>50,n=e<-50,r=document.activeElement;if(!(r&&(r.tagName===`INPUT`||r.tagName===`TEXTAREA`||r.isContentEditable))){if(t){if(D)return;console.log(`Swipe Left -> Next`),k()}else n&&(console.log(`Swipe Right -> Stop`),E())}A.current=null,j.current=null},[m,k,E,D]),F=s,I=(0,V.useMemo)(()=>{if(F)return f&&f.has(F.ownerId)?f.get(F.ownerId):{elapsed:F.accumulatedMs||0,duration:F.durationMs,format:F.format}},[F,f]),ee=(0,V.useMemo)(()=>I?I.format===`down`&&I.duration?Math.max(0,I.duration-I.elapsed):I.elapsed:0,[I]),te=(0,V.useMemo)(()=>!d||d.length===0?[]:d.map(e=>{let t=f?.get(e.ownerId),n=t?.elapsed??e.accumulatedMs??0,r=t?.duration??e.durationMs,i=t?.format??e.format??`up`,a=i===`down`&&r?Math.max(0,r-n):n;return{id:e.id,ownerId:e.ownerId,label:e.label||`Timer`,displayMs:a,format:i}}),[d,f]);return(0,H.jsxs)(`div`,{className:`flex w-full flex-1 ${x?`flex-row items-stretch gap-2 min-h-[80px]`:`flex-col ${S?c?`min-h-[136px]`:`min-h-[112px]`:`min-h-[192px]`} ${c?``:S?`gap-2`:`gap-4`}`}`,onTouchStart:M,onTouchMove:N,onTouchEnd:P,children:[(0,H.jsx)(`style`,{children:`
130
+ `),r=-1,a=e.match(/^(?:workout|time|log|query|widget)-line-(\d+)$/);if(a)r=Number(a[1])-1;else{let i=(t.state.field(ZC,!1)?.sections??[]).find(t=>!!(t.id===e||e.includes(`:${t.id}:`)||e.endsWith(`:${t.id}`)));r=i?i.startLine:n.findIndex(t=>{let n=t.match(/^(#{1,6})\s+(.*)$/);if(n){let t=n[2].trim(),r=t.match(/(\d{1,2}:\d{2})/);if(r){let e=r[1];t=t.replace(e,``).replace(/\s+/g,` `).trim(),t||=e}return t.toLowerCase().replace(/[^\w]+/g,`-`)===e}return!1})}if(r>=0&&r<n.length){let e=t.state.doc.line(r+1).from;t.dispatch({selection:{anchor:e,head:e},effects:[Er.scrollIntoView(e,{y:`start`,yMargin:20})]});let n=t.dom.parentElement;if(n&&window.innerWidth>=1024){let e=n.getBoundingClientRect().top+window.scrollY-120;window.scrollTo({top:e,behavior:`smooth`})}}}},[]);return(0,V.useEffect)(()=>{n(o)},[o,n]),(0,V.useEffect)(()=>{if(e.length===0)return;let t=new IntersectionObserver(e=>{let t=null,n=-1;e.forEach(e=>{e.isIntersecting&&e.intersectionRatio>n&&(n=e.intersectionRatio,t=e.target.id)}),t&&r({type:`SET_ACTIVE_L3`,id:t})},{rootMargin:`-10% 0px -50% 0px`,threshold:[0,.25,.5,1]});return e.forEach(e=>{let n=document.getElementById(e.id);n&&t.observe(n)}),()=>t.disconnect()},[e,r]),(0,V.useEffect)(()=>{e.length!==0&&t(Gz(e))},[e,t]),{handleViewCreated:a,scrollToSection:o}}var qz=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0),Jz=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/60),i=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},Yz=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},Xz=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/60),i=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},Zz=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},Qz=e=>e==null||!Number.isFinite(e)?`--:--`:Math.floor(Math.abs(e)/1e3)>=3600?Yz(e):Jz(e),$z=500,eB=900,tB=560;function nB(e,t){let n=e<$z,r=e>=eB,i=!n;return{width:e,height:t,isCompact:n,isWide:i,isFull:r,isShort:t>0&&t<tB,mode:r?`full`:i?`wide`:`compact`}}var rB=nB(800,600),iB=(0,V.createContext)(rB);function aB(){return(0,V.useContext)(iB)}var oB=({children:e})=>{let t=(0,V.useRef)(null),[n,r]=(0,V.useState)(rB),i=(0,V.useCallback)(e=>{let t=e[0];if(!t)return;let n=t.contentRect.width,i=t.contentRect.height;r(e=>{let t=nB(n,i);return e.mode===t.mode&&Math.abs(e.width-n)<2&&Math.abs(e.height-i)<2?e:t})},[]);return(0,V.useEffect)(()=>{let e=t.current;if(!e)return;let n=new ResizeObserver(i);return n.observe(e),()=>n.disconnect()},[i]),(0,H.jsx)(`div`,{ref:t,className:`h-full w-full`,children:(0,H.jsx)(iB.Provider,{value:n,children:e})})},sB={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_SURFACE_GENERAL_STRIP:`timer-surface-general-strip`,TIMER_METRIC_PROMPTS:`timer-metric-prompts`,FOCUSED_DIALOG_CLOSE:`focused-dialog-close`,REVIEW_PANEL:`review-panel`,REVIEW_RESULTS_TABLE:`review-results-table`,REVIEW_METRIC_ROW:`review-metric-row`,REVIEW_TOTAL_TIME:`review-total-time`,EDITOR_PANEL:`editor-panel`,EDITOR_CONTENT:`editor-content`,EDITOR_START_WORKOUT:`editor-start-workout`,TESTBENCH_ROOT:`testbench-root`,TESTBENCH_NEXT_BUTTON:`testbench-next`,TESTBENCH_RUNTIME_STACK:`testbench-runtime-stack`,TESTBENCH_MEMORY:`testbench-memory`,TESTBENCH_SCRIPT_EDITOR:`testbench-script-editor`,EFFORTS_CATALOG_ROOT:`efforts-catalog-root`,EFFORTS_CATALOG_SEARCH:`efforts-catalog-search`,EFFORTS_CATALOG_CREATE_BTN:`efforts-catalog-create-btn`,EFFORTS_CATALOG_EMPTY_STATE:`efforts-catalog-empty-state`,EFFORTS_LOADING:`efforts-loading`,EFFORT_DETAIL_ROOT:`effort-detail-root`,EFFORT_DETAIL_LABEL:`effort-detail-label`,EFFORT_DETAIL_ALIASES:`effort-detail-aliases`,EFFORT_DETAIL_ATTRIBUTES:`effort-detail-attributes`,EFFORT_DETAIL_SOURCE:`effort-detail-source`,EFFORT_DETAIL_EDIT_BTN:`effort-detail-edit-btn`,EFFORT_DETAIL_CLONE_BTN:`effort-detail-clone-btn`,EFFORT_DETAIL_SAVE_BTN:`effort-detail-save-btn`,EFFORT_DETAIL_CANCEL_BTN:`effort-detail-cancel-btn`,EFFORT_DETAIL_DELETE_BTN:`effort-detail-delete-btn`,EFFORT_DETAIL_NOTEBOOK_EDITOR:`effort-detail-notebook-editor`,EFFORT_DETAIL_ANALYTICS_PLACEHOLDER:`effort-detail-analytics-placeholder`,EFFORT_NOT_FOUND:`effort-not-found`,EFFORT_NOT_FOUND_CREATE_BTN:`effort-not-found-create-btn`,EFFORT_NOT_FOUND_ALIAS_BTN:`effort-not-found-alias-btn`,EFFORT_NOT_FOUND_ALIAS_SELECT:`effort-not-found-alias-select`,EFFORT_NOT_FOUND_ALIAS_CONFIRM:`effort-not-found-alias-confirm`,EFFORTS_NAV_ORIGIN_FILTER:`efforts-nav-origin-filter`,EFFORTS_NAV_DISCIPLINE_FILTER:`efforts-nav-discipline-filter`,EFFORTS_NAV_RECENT_WORKOUTS:`efforts-nav-recent-workouts`,EFFORTS_NAV_RECENT_WORKOUT_ITEM:`efforts-nav-recent-workout-item`,EQUIPMENT_DETAIL_ROOT:`equipment-detail-root`,EQUIPMENT_DETAIL_LABEL:`equipment-detail-label`,EQUIPMENT_DETAIL_SOURCE:`equipment-detail-source`,EQUIPMENT_DETAIL_CLONE_BTN:`equipment-detail-clone-btn`,EQUIPMENT_DETAIL_NOTEBOOK_EDITOR:`equipment-detail-notebook-editor`,EQUIPMENT_NOT_FOUND:`equipment-not-found`,EQUIPMENT_NOT_FOUND_CREATE_BTN:`equipment-not-found-create-btn`,EQUIPMENT_CREATE_BTN:`equipment-create-btn`,EQUIPMENT_LOAD_ERROR:`equipment-load-error`,COMMAND_PALETTE_TRIGGER:`command-palette-trigger`,COMMAND_PALETTE_INPUT:`command-palette-input`,COMMAND_PALETTE_RESULTS:`command-palette-results`},cB=Jz;function lB(e,t,n=0){let r=e>0?e:800,i=t?Math.min(Math.max(r*.14,56),72,r*.3):Math.min(Math.max(r*.18,128),320,r*.3);return Math.round(n>0?Math.min(i,Math.max(44,n-(t?180:n<560?240:400))):i)}var uB=({children:e})=>{let t=(0,V.useRef)(null),n=(0,V.useRef)(null),[r,i]=(0,V.useState)(1);return(0,V.useLayoutEffect)(()=>{let e=t.current,r=n.current;if(!e||!r)return;let a=()=>{let t=Math.min(1,e.clientWidth/Math.max(r.scrollWidth,1),e.clientHeight/Math.max(r.scrollHeight,1));i(Number.isFinite(t)?Math.max(0,t):0)};a();let o=new ResizeObserver(a);return o.observe(e),o.observe(r),()=>o.disconnect()},[]),(0,H.jsx)(`div`,{ref:t,className:`flex h-full min-h-0 w-full items-center justify-center`,children:(0,H.jsx)(`div`,{ref:n,className:`shrink-0 text-center`,style:{transform:`scale(${r})`,transformOrigin:`center center`},children:e})})},dB=({onStart:e,onPause:t,onStop:n,onNext:r,isRunning:i,isPaused:a=!1,disableNext:o,primaryTimer:s,compact:c=!1,subLabel:l,subLabels:u,secondaryTimers:d,timerStates:f,getFocusProps:p,enableGestures:m=!0,skipFlash:h=!1,skipFlashKey:g=0})=>{let{width:_,height:v,isShort:y}=aB(),b=null;try{b=tk()}catch{}let x=v>0&&v<200,S=c||y||x,C=(0,V.useMemo)(()=>lB(_,c,v),[_,v,c]),w=(0,V.useCallback)(()=>{b?.playClick(),e()},[b,e]),T=(0,V.useCallback)(()=>{b?.playClick(),t()},[b,t]),E=(0,V.useCallback)(()=>{b?.playClick(),n()},[b,n]),D=o??a,O=a?`Continue`:i?`Pause`:`Start`,k=(0,V.useCallback)(()=>{D||(b?.playClick(),r())},[b,D,r]),A=(0,V.useRef)(null),j=(0,V.useRef)(null),M=e=>{j.current=null,A.current=e.targetTouches[0].clientX},N=e=>{j.current=e.targetTouches[0].clientX},P=(0,V.useCallback)(()=>{if(!m||!A.current||!j.current)return;let e=A.current-j.current,t=e>50,n=e<-50,r=document.activeElement;if(!(r&&(r.tagName===`INPUT`||r.tagName===`TEXTAREA`||r.isContentEditable))){if(t){if(D)return;console.log(`Swipe Left -> Next`),k()}else n&&(console.log(`Swipe Right -> Stop`),E())}A.current=null,j.current=null},[m,k,E,D]),F=s,I=(0,V.useMemo)(()=>{if(F)return f&&f.has(F.ownerId)?f.get(F.ownerId):{elapsed:F.accumulatedMs||0,duration:F.durationMs,format:F.format}},[F,f]),ee=(0,V.useMemo)(()=>I?I.format===`down`&&I.duration?Math.max(0,I.duration-I.elapsed):I.elapsed:0,[I]),te=(0,V.useMemo)(()=>!d||d.length===0?[]:d.map(e=>{let t=f?.get(e.ownerId),n=t?.elapsed??e.accumulatedMs??0,r=t?.duration??e.durationMs,i=t?.format??e.format??`up`,a=i===`down`&&r?Math.max(0,r-n):n;return{id:e.id,ownerId:e.ownerId,label:e.label||`Timer`,displayMs:a,format:i}}),[d,f]);return(0,H.jsxs)(`div`,{className:`flex w-full flex-1 ${x?`flex-row items-stretch gap-2 min-h-[80px]`:`flex-col ${S?c?`min-h-[136px]`:`min-h-[112px]`:`min-h-[192px]`} ${c?``:S?`gap-2`:`gap-4`}`}`,onTouchStart:M,onTouchMove:N,onTouchEnd:P,children:[(0,H.jsx)(`style`,{children:`
131
131
  @keyframes skip-flash-fade {
132
132
  0% { opacity: 1; transform: translateY(0); }
133
133
  70% { opacity: 1; transform: translateY(-4px); }
@@ -135,39 +135,51 @@ Timer 12:00
135
135
  }
136
136
  .animate-skip-flash {
137
137
  }
138
- `}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col items-center justify-center overflow-hidden ${S?`px-4 py-1`:`p-4`} ${x?`min-w-0`:``}`,children:(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full relative w-full`,children:[h&&(0,H.jsx)(`div`,{className:`animate-skip-flash absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap bg-signal-caution text-white dark:text-white text-sm font-semibold px-4 py-1.5 rounded-full shadow-lg pointer-events-none z-20`,role:`status`,"aria-live":`polite`,children:`Timer can't be skipped!`},g),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`h-8 min-h-0 shrink mb-1`:`h-24 mb-6 shrink-0`}`,children:(0,H.jsxs)(uB,{children:[s?.label&&(0,H.jsx)(`h2`,{className:`font-semibold text-foreground tracking-tight ${S?`text-lg`:`text-3xl lg:text-4xl`}`,children:s.label}),u&&u.length>0&&(0,H.jsx)(`div`,{className:`${S?`mt-1 space-y-0.5`:`mt-2 space-y-1`}`,children:u.map((e,t)=>(0,H.jsx)(`p`,{className:`text-muted-foreground ${S?`text-xs`:`text-lg lg:text-xl`}`,children:e},t))}),u===void 0&&l&&(0,H.jsx)(`p`,{className:`text-muted-foreground ${S?`mt-1 text-xs`:`mt-2 text-lg lg:text-xl`}`,children:l})]})}),(0,H.jsx)(`div`,{className:`relative flex min-h-12 w-full flex-1 items-center justify-center`,children:(0,H.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`timer-main`):{},className:`tv-focusable relative z-10 flex h-full max-h-full min-h-[48px] w-full items-center justify-center focus:outline-none focus-visible:outline-2 focus-visible:outline-ring group ${S?`py-1`:`py-8`}`,title:O,children:(0,H.jsx)(uB,{children:(0,H.jsx)(`span`,{className:`block font-mono font-bold tracking-tighter text-foreground tabular-nums leading-none`,style:{fontSize:`${C}px`},role:`timer`,"aria-live":`polite`,"aria-atomic":`true`,children:cB(ee)})})})}),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`mt-1 h-6 min-h-0 shrink`:`mt-6 h-[60px] shrink-0`}`,children:(0,H.jsx)(`div`,{className:`flex items-center justify-center gap-2 ${S?`flex-wrap`:`gap-4`}`,children:te.map((e,t)=>(0,H.jsxs)(`div`,{...p?p(`secondary-timer-${t}`):{},className:`tv-focusable flex items-center gap-2 rounded-lg border bg-muted/40 text-muted-foreground ${S?`px-2.5 py-1.5 text-xs`:`px-4 py-2 text-sm`}`,title:e.label,role:`timer`,"aria-label":`${e.label} ${cB(e.displayMs)}`,"aria-atomic":`true`,children:[(0,H.jsx)(le,{className:`shrink-0 ${S?`w-3 h-3`:`w-4 h-4`}`}),(0,H.jsx)(`span`,{className:`font-medium truncate max-w-[120px]`,children:e.label}),(0,H.jsx)(`span`,{className:`font-mono font-semibold tabular-nums`,children:cB(e.displayMs)})]},e.id))})})]})}),(0,H.jsxs)(`div`,{className:`flex flex-shrink-0 items-center justify-center flex-wrap ${x?`gap-3 px-2 py-1`:c?`px-4 py-3 bg-background border-t border-border gap-3`:S?`gap-6 px-2 py-1`:`gap-8 px-2 pb-8`}`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,H.jsx)(`button`,{onClick:E,...p?p(`btn-stop`):{},className:`tv-focusable group flex items-center justify-center rounded-full border transition-all active:scale-95 ${S?`w-12 h-12 bg-muted border-border`:`w-16 h-16 bg-surface-container-low border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:`Stop Session`,"data-testid":sB.TIMER_STOP_SESSION,children:(0,H.jsx)(ke,{className:`${S?`w-5 h-5`:`w-7 h-7`} text-foreground group-hover:text-destructive transition-colors`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:`Stop`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,H.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`btn-pause`):{},className:`tv-focusable group flex items-center justify-center rounded-full transition-all active:scale-95 ${S?`w-12 h-12 bg-primary text-primary-foreground shadow-lg shadow-primary/20`:`w-20 h-20 bg-surface-container-low border border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:O,"data-testid":sB.TIMER_PLAY_PAUSE,children:a?(0,H.jsx)(Ht,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`}):i?(0,H.jsx)(fr,{className:`${S?`w-6 h-6 text-primary-foreground`:`w-8 h-8 text-foreground`}`}):(0,H.jsx)(Ht,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:O})]}),c?(0,H.jsxs)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable ${x?`h-12 flex-none px-3`:`flex-1 h-14`} rounded-2xl flex items-center justify-center gap-2 transition-transform shadow-lg ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary text-primary-foreground shadow-primary/20 active:scale-[0.98]`}`,title:`Next Block`,"data-testid":sB.TIMER_NEXT_BLOCK,children:[(0,H.jsx)(`span`,{className:`text-base font-bold tracking-widest uppercase`,children:`Next`}),(0,H.jsx)(ht,{className:`w-5 h-5`})]}):(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,H.jsx)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable flex items-center justify-center rounded-full transition-all shadow-xl ${S?`w-12 h-12`:`w-24 h-24`} ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary-container text-on-primary-container hover:bg-primary hover:text-primary-foreground active:scale-90`}`,title:`Next Block`,"data-testid":sB.TIMER_NEXT_BLOCK,children:(0,H.jsx)(ht,{className:`font-bold ${S?`w-6 h-6`:`w-10 h-10`}`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-bold uppercase tracking-widest text-on-primary-container`,children:`Next`})]})]})]})},fB={time:`bg-metric-time/15 border-metric-time/40 text-metric-time`,rep:`bg-metric-rep/15 border-metric-rep/40 text-metric-rep`,effort:`bg-metric-effort/15 border-metric-effort/40 text-metric-effort`,distance:`bg-metric-distance/15 border-metric-distance/40 text-metric-distance`,rounds:`bg-metric-rounds/15 border-metric-rounds/40 text-metric-rounds`,action:`bg-metric-action/15 border-metric-action/40 text-metric-action`,increment:`bg-metric-rounds/10 border-metric-rounds/35 text-metric-rounds`,lap:`bg-metric-rep/10 border-metric-rep/35 text-metric-rep`,text:`bg-muted border-border text-muted-foreground`,resistance:`bg-metric-resistance/15 border-metric-resistance/40 text-metric-resistance`,duration:`bg-metric-time/10 border-metric-time/30 text-metric-time`,spans:`bg-metric-distance/10 border-metric-distance/30 text-metric-distance`,elapsed:`bg-metric-time/12 border-metric-time/28 text-metric-time`,total:`bg-muted border-border text-foreground`,"system-time":`bg-muted/60 border-border/60 text-muted-foreground`,metric:`bg-metric-effort/10 border-metric-effort/30 text-metric-effort`,custom:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,calculated:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rest:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,volume:`bg-metric-rep/12 border-metric-rep/35 text-metric-rep`,load:`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,"session-load":`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,intensity:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,work:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rir:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"session-rpe":`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"met-score":`bg-metric-distance/12 border-metric-distance/35 text-metric-distance`,tis:`bg-metric-action/12 border-metric-action/35 text-metric-action`,"current-round":`bg-metric-rounds/10 border-metric-rounds/30 text-metric-rounds`,label:`bg-muted border-border text-muted-foreground`,system:`bg-muted/60 border-border/60 text-muted-foreground`,sound:`bg-muted/50 border-border/50 text-muted-foreground`,group:`bg-muted/50 border-border/50 text-muted-foreground`};function pB(e,t){return e.toLowerCase()!==`effort`||!t?!1:t.trim().toLowerCase()===`rest`}function mB(e,t){let n=`bg-gray-200 border-gray-300 text-gray-800 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100`;return pB(e,t)?fB.rest??n:fB[e.toLowerCase()]??n}var hB={time:`⏱️`,duration:`⏱️`,rounds:`🔄`,resistance:`💪`,weight:`💪`,distance:`📏`,action:`▶️`,rest:`⏸️`,effort:`🏃`,increment:`↕️`,text:`📝`,elapsed:`⏱️`,spans:`📊`,total:`🕐`,"system-time":`🖥️`,metric:`📈`,volume:`🏋️`,intensity:`⚡`,load:`⚖️`,work:`🔥`,rir:`🔋`,"session-rpe":`😓`,"session-load":`📊`,"met-score":`🫀`,tis:`📈`,calculated:`🧮`,custom:`✳️`,"current-round":`🔄`,label:`🏷️`,system:`⚙️`,sound:`🔊`,group:`🔀`,lap:`🏁`};function gB(e,t){return pB(e,t)?hB.rest:hB[e.toLowerCase()]||null}var _B=new Set([`duration`,`time`,`elapsed`,`total`,`spans`]);function vB(e,t){let n=e.toLowerCase().replace(/[^a-z0-9]/g,``),r={reps:`rep`,rep:`rep`,distance:`distance`,rounds:`rounds`,round:`rounds`,currentround:`current-round`,action:`action`,increment:`increment`,lap:`lap`,text:`text`,resistance:`resistance`,weight:`resistance`,duration:`duration`,spans:`spans`,elapsed:`elapsed`,total:`total`,totaltime:`total`,systemtime:`system-time`,label:`label`,system:`system`,sound:`sound`,group:`group`};if(r[n])return r[n];if(n.includes(`rir`))return`rir`;if(n.includes(`sessionrpe`)||n===`rpe`)return`session-rpe`;if(n.includes(`sessionload`))return`session-load`;if(n.includes(`metscore`)||n===`met`)return`met-score`;if(n===`tis`)return`tis`;if(n.includes(`calculated`)||n.includes(`calc`))return`calculated`;if(n.includes(`custom`))return`custom`;if(n.includes(`volume`))return`volume`;if(n.includes(`intensity`))return`intensity`;if(n.includes(`load`))return`load`;if(n.includes(`work`)||n.includes(`energy`)||n.includes(`calorie`))return`work`;if(n.includes(`set`))return`metric`;if(t){let e=t.toLowerCase();if(e===`reps`||e===`rep`)return`rep`;if(e===`km`||e===`m`||e===`mi`||e===`ft`||e===`yd`)return`distance`;if(e===`lb`||e===`kg`||e===`lbs`||e===`pood`)return`resistance`;if(e===`min`||e===`sec`||e===`ms`||e===`h`)return`duration`;if(e===`kcal`||e===`cal`)return`work`;if(e===`round`||e===`rounds`)return`rounds`;if(e===`sets`||e===`set`)return`metric`}return`metric`}function yB(e,t,n){if(e==null)return`—`;if(typeof e==`string`)return e;if(typeof e!=`number`||!Number.isFinite(e))return String(e);if(_B.has(t)){let t=n?.toLowerCase();return Qz(t===`sec`||t===`s`?e*1e3:t===`min`||t===`m`?e*60*1e3:t===`h`||t===`hr`?e*60*60*1e3:e)}return Number.isInteger(e)?String(e):e.toFixed(1)}var bB=({className:e})=>{let t=Jf(),n={};for(let e of t){let t=e.metrics;for(let e=0;e+1<t.length;e+=2){let r=t[e],i=t[e+1];if(r&&i){let e=r.image??String(r.value);n[e]={value:i.value,unit:i.unit}}}}let r=Object.entries(n);return r.length>0?(0,H.jsxs)(`div`,{className:U(`flex h-14 flex-shrink-0 flex-wrap items-center justify-center gap-2 overflow-hidden px-4`,e),children:[r.map(([e,t])=>{let n=vB(e,t.unit),r=mB(n),i=gB(n),a=yB(t.value,n,t.unit);return(0,H.jsxs)(`div`,{className:U(`flex flex-col items-center backdrop-blur-md border rounded-xl px-3 py-1.5 shadow-sm ring-1 ring-black/5 dark:ring-white/5 group transition-colors`,r),children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 opacity-70`,children:[i&&(0,H.jsx)(`span`,{className:`text-[10px] leading-none`,"aria-hidden":`true`,children:i}),(0,H.jsx)(`span`,{className:`text-[8px] font-black uppercase tracking-tighter group-hover:opacity-100 transition-opacity`,children:po(e)})]}),(0,H.jsxs)(`div`,{className:`flex items-baseline gap-0.5`,children:[(0,H.jsx)(`span`,{className:`text-sm font-black tabular-nums tracking-tight`,children:a}),t.unit&&!_B.has(n)&&(0,H.jsx)(`span`,{className:`text-[9px] font-bold opacity-60 uppercase`,children:t.unit})]})]},`bubble-${e}`)}),(0,H.jsx)(`div`,{className:`self-center bg-primary/10 border border-primary/20 rounded-full p-1.5 shadow-inner opacity-40 hover:opacity-100 transition-opacity cursor-help`,title:`Session Aggregates`,children:(0,H.jsx)(Cn,{className:`h-3 w-3 text-primary`})})]}):(0,H.jsx)(`div`,{className:U(`h-14 shrink-0`,e),"aria-hidden":`true`})},xB=e=>{let t=Kf(),n=wF(e=>e.viewMode),r=wF(e=>e.execution.status),[i,a]=V.useState(0),[o,s]=V.useState(!1),c=V.useRef(null);V.useEffect(()=>{if(!t)return;let e=t.eventBus.on(`timer:skip-attempt`,()=>{a(e=>e+1),s(!0),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>s(!1),3e3)},`ui-flash`);return()=>{e(),c.current&&clearTimeout(c.current)}},[t]);let l=$f(),u=ep(),d=Qf(),f=tp(),p=np(),m=p?.find(e=>e.block.blockType===`Rounds`),h=Uf(m?.block),[g,_]=V.useState(hl()),v=(0,V.useMemo)(()=>d.some(e=>e.timer.spans.some(e=>e.ended===void 0)),[d]);V.useEffect(()=>{if(!v)return;let e,t=()=>{_(hl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[v]);let y=(0,V.useMemo)(()=>l?qz(l.timer.spans,g):0,[l,g]),b=(0,V.useMemo)(()=>{let e=new Map;for(let t of d){let n=t.block.key.toString(),r=qz(t.timer.spans,g);e.set(n,{elapsed:r,duration:t.timer.durationMs,format:t.timer.direction})}return e},[d,g]),x=(0,V.useMemo)(()=>{if(!l)return;let e=l.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:l.timer.label,format:l.timer.direction,durationMs:l.timer.durationMs,role:l.isPinned?`primary`:`auto`}},[l]),S=(0,V.useMemo)(()=>u.map(e=>{let t=e.block.key.toString();return{id:`timer-${t}`,ownerId:t,timerMemoryId:``,label:e.timer.label,format:e.timer.direction,durationMs:e.timer.durationMs,role:e.isPinned?`primary`:`auto`}}),[u]),C=(0,V.useMemo)(()=>f.filter(e=>e.visible&&e.enabled&&e.eventName).map(e=>({id:e.id,name:e.label,eventName:e.eventName,ownerId:``,displayLabel:e.label,isPinned:e.isPinned})),[f]),w=l?l.block.key.toString():void 0,{mainLabel:T,subLabel:E,activeTimerEntry:D,activeElapsed:O}=(0,V.useMemo)(()=>{let e=p?.find(e=>e.isLeaf),t=e?.label,n=p?.find(e=>e.block.blockType===`Rounds`),r=h?.label??n?.label,i=e?d.find(t=>t.block.key.toString()===e.block.key.toString()):void 0,a=i?qz(i.timer.spans,g):0;if(l&&l.isPinned){let e=qz(l.timer.spans,g),n=r||l.timer.label;return{mainLabel:n,subLabel:n===t?void 0:t,activeTimerEntry:l,activeElapsed:e}}return r&&r!==t?{mainLabel:r,subLabel:t,activeTimerEntry:i||l,activeElapsed:i?a:y}:{mainLabel:t||l?.timer.label||`Timer`,subLabel:void 0,activeTimerEntry:i||l,activeElapsed:i?a:y}},[l,p,d,g,y,h]),k=(0,V.useMemo)(()=>{let e=p?.find(e=>e.isLeaf);if(!e)return E?[E]:void 0;if(e.displayRows&&e.displayRows.length>1){let t=e.displayRows.map(e=>_o.presentGroup([...e],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()).filter(Boolean);if(t.length>0)return t}return E?[E]:void 0},[p,E]),A=(0,V.useMemo)(()=>{if(D){let e=D.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:T,format:D.timer.direction,durationMs:D.timer.durationMs,role:D.isPinned?`primary`:`auto`,accumulatedMs:O}}if(x)return{...x,label:T,accumulatedMs:O}},[x,D,T,O]);return(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2`,children:[(0,H.jsx)(`div`,{className:`min-h-0 shrink overflow-y-auto pb-2`,children:(0,H.jsx)(bB,{})}),(0,H.jsx)(dB,{elapsedMs:O,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,actions:C.length>0?C:void 0,skipFlash:o,skipFlashKey:i,onAction:(n,r)=>{switch(t.handle({name:n,timestamp:new Date,data:r}),n){case`timer:pause`:e.onPause?.();break;case`timer:resume`:case`timer:start`:e.onStart?.();break;case`workout:stop`:e.onStop?.()}},isRunning:v||r===`running`,isPaused:r===`paused`,disableNext:r===`paused`,primaryTimer:A,subLabel:E,subLabels:k,secondaryTimers:S,stackItems:p,compact:e.compact,focusedBlockId:w,timerStates:b,enableGestures:n===`track`,getFocusProps:e.getFocusProps})]})},SB=e=>{let t=wF(e=>e.viewMode),{onNext:n,disableNext:r,isPaused:i}=e;return(0,V.useEffect)(()=>{if(t!==`track`)return;let e=e=>{if(e.key===`AudioVolumeUp`||e.key===`Enter`||e.keyCode===13){let t=document.activeElement;!(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))&&!r&&!i&&(e.preventDefault(),n())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,r,i,t]),e.enableDisplayStack?(0,H.jsx)(xB,{...e}):(0,H.jsx)(dB,{elapsedMs:e.elapsedMs,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isRunning:e.isRunning,isPaused:e.isPaused,disableNext:e.disableNext,compact:e.compact,enableGestures:t===`track`,getFocusProps:e.getFocusProps})};function CB(e){let t=e.metric.image??String(e.metric.value??``);return{...e,colorClasses:mB(e.metric.type,t),icon:gB(e.metric.type,t),originClasses:e.userEntered?`border-dashed italic ring-1 ring-offset-1 ring-primary/30`:``}}function wB(e,t){return _o.presentGroup(e,t).map(CB)}var TB=V.memo(({metrics:e,error:t,className:n=``,size:r=`normal`,filter:i})=>{let a=(0,V.useMemo)(()=>i?e.filter(e=>{let t=String(e.value||``).toLowerCase(),n=e.type.toLowerCase();if(i.nameOverrides){if(t in i.nameOverrides)return i.nameOverrides[t];if(n in i.nameOverrides)return i.nameOverrides[n]}return i.typeOverrides&&n in i.typeOverrides?i.typeOverrides[n]:!i.allowedOrigins||i.allowedOrigins.includes(e.origin||`parser`)}):e,[e,i]);if(t)return(0,H.jsx)(`div`,{className:`border border-destructive/50 rounded-lg p-4 bg-destructive/10 ${n}`,children:(0,H.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-destructive font-bold text-lg`,children:`⚠️`}),(0,H.jsxs)(`div`,{className:`flex-1`,children:[(0,H.jsx)(`div`,{className:`font-semibold text-destructive mb-1`,children:`Parse Error`}),(0,H.jsx)(`div`,{className:`text-destructive/90 text-sm`,children:t.message}),(t.line!==void 0||t.column!==void 0)&&(0,H.jsxs)(`div`,{className:`text-destructive/80 text-xs mt-2`,children:[t.line!==void 0&&(0,H.jsxs)(`span`,{children:[`Line `,t.line]}),t.line!==void 0&&t.column!==void 0&&(0,H.jsx)(`span`,{children:`, `}),t.column!==void 0&&(0,H.jsxs)(`span`,{children:[`Column `,t.column]})]}),t.excerpt&&(0,H.jsx)(`pre`,{className:`mt-2 p-2 bg-background border border-destructive/20 rounded text-xs overflow-x-auto text-foreground`,children:t.excerpt})]})]})});if(!a||a.length===0)return(0,H.jsx)(`div`,{className:`border border-border rounded-lg p-4 bg-muted/20 text-center text-muted-foreground text-sm ${n}`,children:`No metrics to display`});let o={compact:{padding:`px-1 py-0`,text:`text-[10px] leading-tight`,icon:`text-xs`},normal:{padding:`px-2 py-0.5`,text:`text-sm`,icon:`text-base leading-none`},focused:{padding:`px-2.5 py-1`,text:`text-base`,icon:`text-lg leading-none`}}[r];return(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1 ${n}`,children:wB(a,`runtime-badge`).filter(e=>e.visible).map((e,t)=>e.renderKind===`comment`?(0,H.jsx)(`span`,{className:U(`italic text-muted-foreground select-text`,o.text),title:`COMMENT: ${e.label}`,"data-metric-type":`comment`,children:e.label},t):(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1 rounded font-mono border ${e.colorClasses} bg-opacity-60 shadow-sm cursor-help transition-colors hover:bg-opacity-80`,o.padding,o.text),title:e.tooltip,children:[e.icon&&(0,H.jsx)(`span`,{className:o.icon,children:e.icon}),(0,H.jsx)(`span`,{children:e.label})]},t))})});TB.displayName=`MetricVisualizer`;function EB(e){if(!e||e<0)return``;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}`:`${r}s`}var DB=({source:e,metrics:t,status:n=`pending`,depth:r=0,size:i=`normal`,filter:a,isSelected:o=!1,isHighlighted:s=!1,isLeaf:c=!1,isHeader:l=!1,label:u,showDuration:d=!1,duration:f,actions:p,metricGroups:m,onClick:h,onDoubleClick:g,onHover:_,className:v})=>{let y={compact:{indent:12,baseIndent:8,fontSize:`text-xs md:text-sm`},normal:{indent:16,baseIndent:12,fontSize:`text-sm md:text-base`},focused:{indent:20,baseIndent:16,fontSize:`text-base md:text-lg`}}[i],b=r*y.indent,x=K.from(t??(e?.getDisplayMetrics(a?{origins:a.allowedOrigins}:void 0)||[])).toArray(),S=t=>{h?.(e,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},C=t=>{t.preventDefault(),g?.(e)},w=()=>{_?.(e)},T=()=>{_?.(null)},E=u??(x.length===0?e?`Block ${e.id}`:`Block`:void 0);return(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 transition-all px-2`,l&&`font-semibold bg-muted/30`,h&&`cursor-pointer hover:bg-muted/50`,o&&`bg-primary/10`,s&&`bg-muted/40`,c&&`font-bold`,v),style:{paddingLeft:`${b+y.baseIndent}px`,minHeight:`var(--wod-preview-statement-height)`,paddingTop:`var(--wod-preview-statement-gap)`,paddingBottom:`var(--wod-preview-statement-gap)`},onClick:S,onDoubleClick:C,onMouseEnter:w,onMouseLeave:T,role:h?`button`:void 0,tabIndex:h?0:void 0,children:[(0,H.jsx)(`div`,{className:`flex-1 min-w-0`,children:m&&m.length>1?(0,H.jsx)(`div`,{className:`flex flex-col`,children:m.map(e=>_o.presentGroup([...e],`runtime-badge`).filter(e=>e.visible).map(e=>e.metric)).filter(e=>e.length>0).map((e,t,n)=>(0,H.jsx)(`div`,{className:U(t<n.length-1&&`border-b border-border/20 pb-0.5 mb-0.5`),children:(0,H.jsx)(TB,{metrics:e,size:i,filter:a,className:U(`inline-flex`,y.fontSize)})},t))}):x.length>0?(0,H.jsx)(TB,{metrics:x,size:i,filter:a,className:U(`inline-flex`,y.fontSize)}):E?(0,H.jsx)(`span`,{className:U(`text-muted-foreground`,y.fontSize),children:E}):(0,H.jsx)(`span`,{className:`text-muted-foreground/50 italic text-xs`,children:`No data`})}),d&&f!==void 0&&f>0&&(0,H.jsx)(`div`,{className:`flex-shrink-0 text-muted-foreground tabular-nums text-right min-w-[40px]`,style:{fontSize:i===`compact`?`10px`:`12px`},children:EB(f)}),p&&(0,H.jsx)(`div`,{className:`flex-shrink-0 flex items-center gap-1`,children:p})]})},OB={display:Ye,promote:Qt,private:ze,result:yn},kB={display:`text-green-500 dark:text-green-400`,promote:`text-blue-500 dark:text-blue-400`,private:`text-amber-500 dark:text-amber-400`,result:`text-purple-500 dark:text-purple-400`},AB={display:`bg-green-500/10 dark:bg-green-900/30`,promote:`bg-blue-500/10 dark:bg-blue-900/30`,private:`bg-amber-500/10 dark:bg-amber-900/30`,result:`bg-purple-500/10 dark:bg-purple-900/30`},jB=({visibility:e})=>{let t=OB[e];return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1 text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded`,kB[e],AB[e]),title:fl[e],children:[(0,H.jsx)(t,{className:`h-3 w-3`}),fl[e]]})},MB=({open:e,onOpenChange:t,children:n})=>(0,H.jsx)(L,{appear:!0,show:e,as:V.Fragment,children:(0,H.jsx)(He,{as:`div`,className:`relative z-[200]`,onClose:()=>t?.(!1),children:n})}),NB=V.forwardRef(({className:e,children:t,...n},r)=>(0,H.jsx)(Mn,{as:V.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0 scale-95`,enterTo:`opacity-100 scale-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100 scale-100`,leaveTo:`opacity-0 scale-95`,children:(0,H.jsx)(`div`,{className:`fixed inset-0 overflow-y-auto`,children:(0,H.jsxs)(`div`,{className:`flex min-h-full items-center justify-center p-4 text-center`,children:[(0,H.jsx)(Mn,{as:V.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0`,enterTo:`opacity-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100`,leaveTo:`opacity-0`,children:(0,H.jsx)(`div`,{className:`fixed inset-0 bg-black/25 dark:bg-black/25`})}),(0,H.jsx)(A,{ref:r,className:U(`relative w-full max-w-md transform overflow-hidden rounded-2xl bg-popover text-popover-foreground p-6 text-left align-middle shadow-xl transition-all border border-border`,e),...n,children:t})]})})}));NB.displayName=`DialogContent`;var PB=({className:e,...t})=>(0,H.jsx)(`div`,{className:U(`flex flex-col space-y-1.5 text-center sm:text-left mb-4`,e),...t});PB.displayName=`DialogHeader`;var FB=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(P,{ref:n,as:`h3`,className:U(`text-lg font-medium leading-6 text-foreground`,e),...t}));FB.displayName=`DialogTitle`;var IB=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(Xe,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t}));IB.displayName=`DialogDescription`;var LB=[`Statements`,`Behaviors`,`Memory`],RB=({open:e,onOpenChange:t,block:n,runtime:r})=>{let[i,a]=(0,V.useState)(0),o=(0,V.useMemo)(()=>!r.script||!n.sourceIds.length?[]:r.script.getIds(n.sourceIds),[r.script,n.sourceIds]),s=(0,V.useMemo)(()=>n.behaviors.map(e=>e.constructor.name),[n.behaviors]),l=(0,V.useMemo)(()=>n.getAllMemory(),[n]);return(0,H.jsx)(MB,{open:e,onOpenChange:t,children:(0,H.jsxs)(NB,{className:`max-w-2xl max-h-[80vh] flex flex-col overflow-hidden`,children:[(0,H.jsxs)(PB,{children:[(0,H.jsx)(FB,{children:(0,H.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{children:n.label}),n.blockType&&(0,H.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/10 text-primary/70 font-bold tracking-wider`,children:n.blockType})]})}),(0,H.jsxs)(`div`,{className:`text-[10px] font-mono text-muted-foreground`,children:[`Key: `,n.key.toString()]})]}),(0,H.jsxs)(c,{selectedIndex:i,onChange:a,children:[(0,H.jsx)(he,{className:`flex border-b border-border gap-0`,children:LB.map(e=>(0,H.jsx)(ve,{className:({selected:e})=>U(`px-4 py-2 text-sm font-medium transition-colors outline-none`,`border-b-2 -mb-px`,e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground hover:border-border`),children:e},e))}),(0,H.jsxs)(we,{className:`flex-1 min-h-0 overflow-y-auto mt-2`,children:[(0,H.jsx)(nn,{children:(0,H.jsx)(zB,{statements:o})}),(0,H.jsx)(nn,{children:(0,H.jsx)(BB,{names:s})}),(0,H.jsx)(nn,{children:(0,H.jsx)(VB,{block:n,locations:l})})]})]})]})})},zB=({statements:e})=>e.length===0?(0,H.jsx)(HB,{text:`No source statements`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`ID`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map(e=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:e.id}),(0,H.jsx)(`div`,{className:`py-0.5`,children:(0,H.jsx)(DB,{metrics:e.metrics,size:`compact`})})]},e.id))]}),BB=({names:e})=>e.length===0?(0,H.jsx)(HB,{text:`No behaviors attached`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`#`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Behavior`})]}),e.map((e,t)=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:t+1}),(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-sm font-mono`,children:e})]},t))]}),VB=({locations:e})=>e.length===0?(0,H.jsx)(HB,{text:`No memory locations`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Tag`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map((e,t)=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:e.tag})}),(0,H.jsx)(`div`,{className:`py-0.5`,children:(0,H.jsx)(DB,{metrics:e.metrics,size:`compact`})})]},`${e.tag}-${t}`))]}),HB=({text:e})=>(0,H.jsx)(`div`,{className:`flex items-center justify-center py-8 text-sm text-muted-foreground italic`,children:e}),UB=({block:e,isLeaf:t,debug:n})=>{let{isDebugMode:r}=ty(),i=n??r,a=Kf(),{elapsed:o,isRunning:s,timeSpans:c}=rp(e.key.toString()),l=Uf(e),[u,d]=(0,V.useState)([]),[f,p]=(0,V.useState)([]),[m,h]=(0,V.useState)([]),[g,_]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let t=()=>{let t=e.getMetricMemoryByVisibility(`display`);if(d(t.map(e=>e.metrics)),i){let t=e.getMetricMemoryByVisibility(`promote`);p(t.map(e=>e.metrics));let n=e.getMetricMemoryByVisibility(`private`);h(n.map(e=>e.metrics))}};t();let n=(i?[...e.getMetricMemoryByVisibility(`display`),...e.getMetricMemoryByVisibility(`promote`),...e.getMetricMemoryByVisibility(`private`)]:e.getMetricMemoryByVisibility(`display`)).map(e=>e.subscribe(()=>t()));return()=>n.forEach(e=>e())},[e,i]);let v=c.length>0,y=(e,t,n,r)=>e.length===0?null:(0,H.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[n&&(0,H.jsx)(jB,{visibility:t}),e.map((e,n)=>(0,H.jsx)(DB,{metrics:e,size:r?`normal`:`compact`,isLeaf:r},`${t}-${n}`))]});return(0,H.jsxs)(`div`,{className:U(`relative w-full`,t?`animate-in fade-in slide-in-from-left-1 duration-300`:``),children:[(0,H.jsxs)(`div`,{className:U(`rounded-md border text-sm transition-all`,t?`bg-card shadow-sm border-primary/40 ring-1 ring-primary/10`:`bg-muted/30 border-transparent text-muted-foreground hover:bg-muted/50 hover:border-border/50`),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-3 p-3`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[!t&&(0,H.jsx)(`span`,{className:`text-xs font-medium tracking-tight text-muted-foreground/70`,children:e.blockType!==`SessionRoot`&&l?l.label:e.label}),t&&u.length>0&&(0,H.jsx)(`div`,{className:`flex items-center flex-wrap gap-0.5 min-w-0 font-bold text-foreground text-base`,children:y(u,`display`,!1,t)}),t&&u.length===0&&e.label&&(0,H.jsx)(`span`,{className:`text-base font-bold tracking-tight text-foreground`,children:e.label}),e.blockType&&i&&(0,H.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/5 text-primary/70 font-bold tracking-wider`,children:e.blockType})]}),i&&(0,H.jsx)(`div`,{className:`text-[10px] font-mono text-muted-foreground/60 truncate max-w-[200px] mt-0.5`,children:e.key.toString()})]}),v&&(0,H.jsxs)(`div`,{className:U(`flex items-center gap-1.5 px-2 py-1 rounded font-mono text-xs font-bold shrink-0`,s?`bg-primary/10 text-primary animate-pulse`:`bg-muted text-muted-foreground`),children:[(0,H.jsx)(le,{className:`h-3 w-3`}),Jz(o)]}),i&&(0,H.jsx)(`button`,{onClick:()=>_(!0),className:`h-9 w-9 rounded-md flex items-center justify-center hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0`,title:`Inspect block`,children:(0,H.jsx)(it,{className:`h-4 w-4`})})]}),!t&&u.length>0&&(0,H.jsx)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:y(u,`display`,i,t)}),i&&(f.length>0||m.length>0)&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:[y(f,`promote`,!0,t),y(m,`private`,!0,t)]})]}),i&&(0,H.jsx)(RB,{open:g,onOpenChange:_,block:e,runtime:a})]})};function WB(e,t,n){return e.filter(e=>e.outputType===`segment`&&t===Math.min(e.stackLevel-1,n-1))}var GB=({runtime:e,outputs:t,debug:n=!1})=>{let r=e.stack.blocks;if(r.length===0)return(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center p-8 text-muted-foreground border-2 border-dashed rounded-lg bg-muted/10`,children:[(0,H.jsx)(x,{className:`h-8 w-8 mb-2 opacity-20`}),(0,H.jsx)(`span`,{className:`text-sm`,children:`No Active Blocks`})]});let i=(e,n)=>{let r=WB(t,e,n);if(r.length===0)return null;let i=r.reduce((e,t)=>e+(t.getMetric(G.Elapsed)?.value??0),0);return(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground py-2 pl-4 border-l-2 border-muted ml-3 my-1 bg-muted/5 rounded-r-md`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(yn,{className:`h-3.5 w-3.5`}),(0,H.jsxs)(`span`,{className:`font-medium`,children:[r.length,` Completed`]})]}),(0,H.jsx)(`div`,{className:`w-px h-3 bg-border/50`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(De,{className:`h-3.5 w-3.5`}),(0,H.jsx)(`span`,{className:`font-mono`,children:(e=>{let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`})(i)})]})]})},a=[...r].reverse();return(0,H.jsx)(`div`,{className:`flex flex-col gap-1 relative`,children:a.map((e,t)=>{let r=t===a.length-1;return(0,H.jsxs)(V.Fragment,{children:[(0,H.jsx)(UB,{block:e,isLeaf:r,debug:n}),i(t,a.length)]},e.key.toString())})})},KB=()=>{let e=Zf();return e?(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:(0,H.jsx)(`div`,{className:U(`rounded-md border text-sm transition-all`,`bg-card/50 border-border/60 hover:bg-card/80`),children:(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5 p-3`,children:(0,H.jsx)(DB,{metrics:e.metrics,size:`compact`,isLeaf:!1})})})}):(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-sm p-3 border border-dashed rounded-lg text-muted-foreground bg-muted/10`,children:[(0,H.jsx)(yn,{className:`h-4 w-4`}),(0,H.jsx)(`span`,{className:`italic`,children:`End of section`})]})},qB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`rounded-lg border bg-card text-card-foreground shadow-sm`,e),...t})));qB.displayName=`Card`;var JB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`flex flex-col space-y-1.5 p-6`,e),...t})));JB.displayName=`CardHeader`;var YB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`h3`,{ref:n,className:U(`text-2xl font-semibold leading-none tracking-tight`,e),...t})));YB.displayName=`CardTitle`;var XB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`p`,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t})));XB.displayName=`CardDescription`;var ZB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`p-6 pt-0`,e),...t})));ZB.displayName=`CardContent`;var QB=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`flex items-center p-6 pt-0`,e),...t})));QB.displayName=`CardFooter`;var $B=()=>{let e=Kf(),{outputs:t}=qf(e),{isDebugMode:n}=ty(),{isCompact:r}=aB();return e?(0,H.jsxs)(`div`,{className:U(`h-full flex flex-col overflow-hidden bg-slate-50/50 dark:bg-slate-900/50`,r?`gap-2 p-2`:`gap-4 p-4`),children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col overflow-y-auto`,children:(0,H.jsx)(GB,{runtime:e,outputs:t,debug:n})}),(0,H.jsxs)(qB,{className:`shrink-0 bg-muted/30 border-dashed`,children:[(0,H.jsx)(JB,{className:U(r?`p-2 pb-0`:`p-3 pb-0`),children:(0,H.jsx)(YB,{className:U(`font-medium text-muted-foreground uppercase tracking-wider`,r?`text-xs`:`text-sm`),children:`Up Next`})}),(0,H.jsx)(ZB,{className:U(r?`p-2`:`p-3`),children:(0,H.jsx)(KB,{runtime:e})})]})]}):null},eV=`38F01E0E`,tV=(e=>!!e&&e!==`CC1AD845`)(eV),nV=``;function rV(){return`chromecast`}var iV=nV===`chromecast`||nV===`local`?nV:rV(),aV=((typeof __LOCAL_RECEIVER_URL__<`u`?__LOCAL_RECEIVER_URL__:void 0)||``).trim(),oV=new class{state=`not-loaded`;listeners=new Map;loadPromise=null;appId=null;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){let n=this.listeners.get(e)??[];this.listeners.set(e,n.filter(e=>e!==t))}emit(e,...t){this.listeners.get(e)?.forEach(e=>e(...t))}getState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit(`state-changed`,e))}load(e){return this.loadPromise&&this.appId===e?this.loadPromise:(this.appId=e,this.loadPromise=this._load(e).catch(t=>{throw this.appId===e&&(this.loadPromise=null,this.appId=null),t}),this.loadPromise)}_load(e){return this.setState(`loading`),new Promise((t,n)=>{window.__onGCastApiAvailable=(r,i)=>{if(!r){console.warn(`[Cast SDK] Not available:`,i),this.setState(`unavailable`),n(Error(`Cast SDK unavailable`));return}try{this._initFramework(e),t()}catch(e){this.setState(`unavailable`),n(e)}};let r=`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`;if(!document.querySelector(`script[src="${r}"]`)){let e=document.createElement(`script`);e.src=r,e.onerror=()=>{this.setState(`unavailable`),n(Error(`Failed to load cast_sender.js`))},document.head.appendChild(e)}})}_initFramework(e){let{cast:t,chrome:n}=window;if(!t?.framework)throw Error(`cast.framework not found after SDK load`);let r=t.framework.CastContext.getInstance();r.setOptions({receiverApplicationId:e,autoJoinPolicy:n.cast.AutoJoinPolicy.ORIGIN_SCOPED,resumeSavedSession:!0}),r.addEventListener(t.framework.CastContextEventType.SESSION_STATE_CHANGED,e=>{let n=t.framework.SessionState;switch(e.sessionState){case n.SESSION_STARTED:case n.SESSION_RESUMED:this.setState(`session-active`),this.emit(`session-started`,r.getCurrentSession());break;case n.SESSION_ENDED:case n.NO_SESSION:this.setState(`ready`),this.emit(`session-ended`)}}),this.setState(`ready`),console.log(`[Cast SDK] Initialised with App ID:`,e)}async requestSession(){let{cast:e}=window;if(!e?.framework)throw Error(`Cast SDK not loaded`);let t=e.framework.CastContext.getInstance(),n=await t.requestSession();if(n)throw n===`cancel`?Error(`cancel`):(console.error(`[Cast SDK] requestSession() error code:`,n),Error(`Cast session request failed: ${n}`));let r=t.getCurrentSession();console.log(`[Cast SDK] requestSession() succeeded — sessionId:`,r?.getSessionId?.())}endSession(){window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}isSessionActive(){return this.state===`session-active`}getSession(){return window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()??null}},sV=`urn:x-cast:com.wodwiki`,cV=class{session;listeners=new Set;boundListener=null;constructor(e){this.session=e,this.boundListener=(e,t)=>{try{console.log(`[SenderCastSignaling] RAW incoming:`,typeof t,typeof t==`string`?t.substring(0,120):JSON.stringify(t).substring(0,120));let e=typeof t==`string`?JSON.parse(t):t;console.log(`[SenderCastSignaling] Parsed signal type:`,e.type);for(let t of this.listeners)t(e)}catch(e){console.error(`[SenderCastSignaling] Failed to parse incoming signal`,e)}},this.session.addMessageListener(sV,this.boundListener),console.log(`[SenderCastSignaling] Listening on ${sV}`),console.log(`[SenderCastSignaling] Session state: ${this.session.getSessionState?.()}`)}send(e){console.log(`[SenderCastSignaling] Sending: ${e.type}`),this.session.sendMessage(sV,e).then(()=>console.log(`[SenderCastSignaling] sendMessage(${e.type}) OK`)).catch(t=>console.error(`[SenderCastSignaling] sendMessage(${e.type}) FAILED`,t))}onSignal(e){return this.listeners.add(e),()=>this.listeners.delete(e)}dispose(){if(this.boundListener){try{this.session.removeMessageListener(sV,this.boundListener)}catch{}this.boundListener=null}this.listeners.clear()}},lV=class{role;signaling;pc;dc=null;signalUnsub=null;disposed=!1;messageHandlers=new Set;connectedHandlers=new Set;disconnectedHandlers=new Set;signalQueue=Promise.resolve();pendingIceCandidates=[];constructor(e,t){this.role=e,this.signaling=t,console.log(`[WebRtcRpcTransport:${e}] Initializing transport`),this.pc=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]}),this.pc.onicecandidate=t=>{t.candidate?(console.log(`[WebRtcRpcTransport:${e}] ICE candidate (local):`,t.candidate.candidate.substring(0,60)+`...`),this.signaling.send({type:`webrtc-ice`,candidate:t.candidate.toJSON()})):console.log(`[WebRtcRpcTransport:${e}] ICE gathering complete`)},this.pc.onconnectionstatechange=()=>{let t=this.pc.connectionState;console.log(`[WebRtcRpcTransport:${e}] Connection state: ${t}`),(t===`disconnected`||t===`failed`||t===`closed`)&&this.notifyDisconnected()},this.pc.oniceconnectionstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] ICE connection state: ${this.pc.iceConnectionState}`)},this.pc.onsignalingstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] Signaling state: ${this.pc.signalingState}`)},this.signalUnsub=this.signaling.onSignal(t=>{console.log(`[WebRtcRpcTransport:${e}] Incoming signal: ${t.type}`),this.signalQueue=this.signalQueue.then(()=>this.handleSignal(t))})}get connected(){return this.dc?.readyState===`open`}get needsClockSync(){return!0}send(e){if(!this.dc||this.dc.readyState!==`open`){console.warn(`[WebRtcRpcTransport] DataChannel not open — dropping message`);return}this.dc.send(JSON.stringify(e))}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onConnected(e){return this.connectedHandlers.add(e),()=>this.connectedHandlers.delete(e)}onDisconnected(e){return this.disconnectedHandlers.add(e),()=>this.disconnectedHandlers.delete(e)}dispose(){if(this.disposed)return;this.disposed=!0,this.signalUnsub?.(),this.signalUnsub=null;let e=this.dc?.readyState===`open`,t=[...this.disconnectedHandlers];if(this.messageHandlers.clear(),this.connectedHandlers.clear(),this.disconnectedHandlers.clear(),this.dc?.close(),this.pc.close(),this.signaling.dispose(),e)for(let e of t)e()}connect(e=15e3){return console.log(`[WebRtcRpcTransport:${this.role}] connect() starting, timeout=${e}ms`),this.connected?(console.log(`[WebRtcRpcTransport:${this.role}] Already connected — short-circuiting`),Promise.resolve()):new Promise((t,n)=>{let r=Date.now(),i=setTimeout(()=>{let t=`pcState=${this.pc.connectionState}, iceState=${this.pc.iceConnectionState}, sigState=${this.pc.signalingState}, dcState=${this.dc?.readyState??`null`}`;console.error(`[WebRtcRpcTransport:${this.role}] TIMEOUT after ${e}ms — ${t}`),n(Error(`WebRTC connect timed out after ${e}ms`))},e),a=()=>{clearTimeout(i),console.log(`[WebRtcRpcTransport:${this.role}] DataChannel OPEN in ${Date.now()-r}ms`),this.notifyConnected(),t()};this.role===`offerer`?(console.log(`[WebRtcRpcTransport:offerer] Creating DataChannel…`),this.dc=this.pc.createDataChannel(`wod-wiki-rpc`,{ordered:!0}),this.wireDataChannel(this.dc,a),console.log(`[WebRtcRpcTransport:offerer] Creating offer…`),this.pc.createOffer().then(e=>(console.log(`[WebRtcRpcTransport:offerer] Offer created, SDP length=${e.sdp?.length}`),this.pc.setLocalDescription(e))).then(()=>{console.log(`[WebRtcRpcTransport:offerer] Local description set — sending offer via signaling`),this.signaling.send({type:`webrtc-offer`,sdp:this.pc.localDescription.sdp}),console.log(`[WebRtcRpcTransport:offerer] Offer sent — waiting for answer…`)}).catch(e=>{console.error(`[WebRtcRpcTransport:offerer] Failed to create/set offer`,e),n(e)})):(console.log(`[WebRtcRpcTransport:answerer] Waiting for ondatachannel…`),this.pc.ondatachannel=e=>{console.log(`[WebRtcRpcTransport:answerer] Remote DataChannel received: ${e.channel.label}`),this.dc=e.channel,this.wireDataChannel(this.dc,a)})})}wireDataChannel(e,t){e.onopen=()=>t(),e.onclose=()=>{this.disposed||this.notifyDisconnected()},e.onerror=e=>{console.error(`[WebRtcRpcTransport] DataChannel error`,e)},e.onmessage=e=>{try{let t=JSON.parse(e.data);for(let e of this.messageHandlers)e(t)}catch(e){console.error(`[WebRtcRpcTransport] Failed to parse RPC message`,e)}}}async handleSignal(e){try{switch(e.type){case`webrtc-offer`:{if(this.role!==`answerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring offer (not an answerer)`);return}console.log(`[WebRtcRpcTransport:answerer] Received offer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`offer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:answerer] Remote description set — creating answer`);let t=await this.pc.createAnswer();console.log(`[WebRtcRpcTransport:answerer] Answer created, length=${t.sdp?.length}`),await this.pc.setLocalDescription(t),console.log(`[WebRtcRpcTransport:answerer] Local description set — sending answer via signaling`),this.signaling.send({type:`webrtc-answer`,sdp:this.pc.localDescription.sdp}),await this.processPendingIceCandidates();break}case`webrtc-answer`:if(this.role!==`offerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring answer (not an offerer)`);return}console.log(`[WebRtcRpcTransport:offerer] Received answer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`answer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:offerer] Remote description set — processing pending candidates…`),await this.processPendingIceCandidates();break;case`webrtc-ice`:{let t=e.candidate;this.pc.remoteDescription?(console.log(`[WebRtcRpcTransport:${this.role}] Adding remote ICE candidate`),await this.pc.addIceCandidate(t)):(console.log(`[WebRtcRpcTransport:${this.role}] Buffering candidate until remote description is set`),this.pendingIceCandidates.push(t));break}}}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Signal handling error`,e)}}async processPendingIceCandidates(){if(this.pendingIceCandidates.length===0)return;console.log(`[WebRtcRpcTransport:${this.role}] Processing ${this.pendingIceCandidates.length} buffered ICE candidates`);let e=[...this.pendingIceCandidates];this.pendingIceCandidates=[];for(let t of e)try{await this.pc.addIceCandidate(t),console.log(`[WebRtcRpcTransport:${this.role}] Buffered ICE candidate added OK`)}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Failed to add buffered ICE candidate`,e)}}notifyConnected(){for(let e of this.connectedHandlers)e()}notifyDisconnected(){for(let e of this.disconnectedHandlers)e()}},uV={"not-loaded":`ready`,loading:`ready`,unavailable:`unavailable`,ready:`ready`,"session-active":`session-active`},dV=class{_state;stateListeners=new Set;sdkUnsubState=null;sdkUnsubEnded=null;activeTransport=null;disposed=!1;constructor(){this._state=uV[oV.getState()],this.subscribeToSdk(),tV&&typeof window<`u`&&oV.load(eV).catch(()=>{})}get state(){return this._state}onStateChanged(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}setState(e){if(this._state!==e){this._state=e;for(let t of[...this.stateListeners])t(e)}}subscribeToSdk(){this.sdkUnsubState=oV.on(`state-changed`,e=>{let t=uV[e]??`ready`;this._state!==`session-active`&&(this._state!==`connecting`||t!==`session-active`)&&this.setState(t)}),this.sdkUnsubEnded=oV.on(`session-ended`,()=>{this.activeTransport=null,this.setState(`session-ended`)})}async startSession(){if(this.disposed)throw Error(`ChromecastBackend: startSession after dispose`);if(!tV)throw this.setState(`unavailable`),Error(`ChromecastBackend: VITE_CAST_APP_ID is not configured`);this.setState(`connecting`);let e=null;try{try{await oV.load(eV)}catch(e){throw this.setState(uV[oV.getState()]),e}if(this.disposed)throw Error(`ChromecastBackend: dispose() called during SDK load`);if(oV.getState()===`unavailable`)throw this.setState(`unavailable`),Error(`ChromecastBackend: Cast not supported in this browser`);if(await oV.requestSession(),this.disposed)throw Error(`ChromecastBackend: dispose() called during requestSession`);let t=oV.getSession();if(!t)throw Error(`ChromecastBackend: no Cast session after requestSession()`);try{await t.sendMessage(`urn:x-cast:com.wodwiki`,{type:`ping`,timestamp:Date.now()})}catch(e){aF(`ChromecastBackend`,`namespace ping failed`,e)}e=new lV(`offerer`,new cV(t)),await e.connect()}catch(t){throw e?.dispose(),!this.disposed&&this._state===`connecting`&&this.setState(`ready`),t}return this.activeTransport=e,e.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),e}async resumeSession(){if(this.disposed)throw Error(`ChromecastBackend: resumeSession after dispose`);if(this.activeTransport)return this.activeTransport;await oV.load(eV);let e=oV.getSession();if(!e)throw Error(`ChromecastBackend: no Cast session to resume`);let t=new lV(`offerer`,new cV(e));try{await t.connect()}catch(e){throw t.dispose(),e}return this.activeTransport=t,t.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),t}endSession(){try{oV.endSession()}catch{}this.activeTransport&&=(this.activeTransport.dispose(),null),this._state!==`unavailable`&&this.setState(`ready`)}dispose(){this.disposed||(this.disposed=!0,this.endSession(),this.sdkUnsubState?.(),this.sdkUnsubEnded?.(),this.sdkUnsubState=null,this.sdkUnsubEnded=null,this.stateListeners.clear())}},fV=class{port;_connected=!1;messageHandlers=new Set;connectedHandlers=new Set;disconnectedHandlers=new Set;_disposed=!1;portMessageUnsub;boundHandler;constructor(e){this.port=e,this.boundHandler=e=>{let t=e.data;for(let e of[...this.messageHandlers])e(t)},this.port.addEventListener(`message`,this.boundHandler),this.portMessageUnsub=()=>this.port.removeEventListener(`message`,this.boundHandler)}start(){if(!this._disposed&&!this._connected){this._connected=!0,this.port.start();for(let e of[...this.connectedHandlers])e()}}notifyDisconnected(){if(!this._disposed&&this._connected){this._connected=!1;for(let e of[...this.disconnectedHandlers])e()}}get connected(){return this._connected}get needsClockSync(){return!1}async connect(){this._connected||this.start()}send(e){if(this._disposed)throw Error(`BroadcastChannelRpcTransport: send after dispose`);if(!this._connected)throw Error(`BroadcastChannelRpcTransport: send before connected`);this.port.postMessage(e)}onMessage(e){return this.messageHandlers.add(e),()=>{this.messageHandlers.delete(e)}}onConnected(e){return this.connectedHandlers.add(e),()=>{this.connectedHandlers.delete(e)}}onDisconnected(e){return this.disconnectedHandlers.add(e),()=>{this.disconnectedHandlers.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this.portMessageUnsub();try{this.port.close()}catch{}this.messageHandlers.clear(),this.connectedHandlers.clear(),this.disconnectedHandlers.clear(),this._connected=!1}}},pV=5e3,mV=class{_state=`ready`;stateListeners=new Set;activePopup=null;activeTransport=null;activeTimeout=null;activeSessionId=null;pendingReject=null;messageUnsub=null;disposed=!1;deps;constructor(e={}){let t=e=>(window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e));this.deps={openPopup:e.openPopup??(e=>window.open(e,`_blank`,`width=1280,height=720`)),addEventListener:e.addEventListener??t,removeEventListener:e.removeEventListener??(e=>{window.removeEventListener(`message`,e)}),postToPopup:e.postToPopup??((e,t)=>{e.postMessage(t,window.location.origin)}),generateId:e.generateId??(()=>{let e=typeof crypto<`u`?crypto:void 0;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(!e)throw Error(`LocalTabBackend: crypto API unavailable`);let t=new Uint8Array(16);return e.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}),buildReceiverUrl:e.buildReceiverUrl??((e,t)=>`${aV||`${e}/receiver-rpc.html`}?local=${t}`),MessageChannelCtor:e.MessageChannelCtor??(typeof MessageChannel<`u`?MessageChannel:void 0),getOrigin:e.getOrigin??(()=>typeof window<`u`?window.location.origin:``),setTimeoutFn:e.setTimeoutFn??((e,t)=>setTimeout(e,t)),clearTimeoutFn:e.clearTimeoutFn??(e=>clearTimeout(e))}}get state(){return this._state}onStateChanged(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}setState(e){if(this._state!==e){this._state=e;for(let t of[...this.stateListeners])t(e)}}async startSession(){if(this.disposed)throw Error(`LocalTabBackend: startSession after dispose`);if(this._state===`connecting`||this._state===`session-active`)throw Error(`LocalTabBackend: startSession while a session is already active`);this.setState(`connecting`);let e=this.deps.generateId();this.activeSessionId=e;let t=this.deps.buildReceiverUrl(this.deps.getOrigin(),e);console.log(`[LocalTabBackend] startSession: opening popup`,{url:t,sessionId:e});let n=this.deps.openPopup(t);if(!n)throw this.setState(`session-ended`),this.activeSessionId=null,Error(`LocalTabBackend: window.open returned null (popup blocked?)`);this.activePopup=n,console.log(`[LocalTabBackend] popup opened`,{sessionId:e});let r=new this.deps.MessageChannelCtor,i=r.port1,a=r.port2,{promise:o,resolve:s,reject:c}=Promise.withResolvers();this.pendingReject=c;let l=e=>{this.cleanupOnError(),this.setState(`session-ended`),this.activeSessionId=null,this.pendingReject=null,c(Error(e))};this.activeTimeout=this.deps.setTimeoutFn(()=>{l(`LocalTabBackend: receiver did not complete handshake within ${pV}ms`)},pV);let u=t=>{if(t.source!==n)return;let r=t.data;if(!(!r||typeof r!=`object`||typeof r.kind!=`string`)&&r.sessionId===e){if(r.kind===`ready`){console.log(`[LocalTabBackend] received ready`,{sessionId:e});try{this.deps.postToPopup(n,{kind:`offer`,sessionId:e}),console.log(`[LocalTabBackend] posted offer`,{sessionId:e})}catch(e){l(e instanceof Error?e.message:String(e));return}try{n.postMessage({kind:`data-port`,sessionId:e},this.deps.getOrigin(),[a]),console.log(`[LocalTabBackend] transferred data port`,{sessionId:e})}catch(e){l(e instanceof Error?e.message:String(e))}}else if(r.kind===`accept`){console.log(`[LocalTabBackend] received accept`,{sessionId:e}),this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.pendingReject=null;let t=new fV(i);t.onDisconnected(()=>{this._state===`session-active`&&this.setState(`session-ended`)}),t.start(),this.activeTransport=t,this.setState(`session-active`),s(t)}else r.kind===`goodbye`&&(this.activeTransport&&this.activeTransport.notifyDisconnected(),this.activeTransport=null,this.activePopup=null,this.activeSessionId=null,this.setState(`session-ended`))}};return this.messageUnsub=this.deps.addEventListener(u),o}cleanupOnError(){this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.messageUnsub&&=(this.messageUnsub(),null),this.activeSessionId=null}endSession(){if(this._state===`session-active`||this._state===`connecting`){if(this.pendingReject&&=(this.pendingReject(Error(`LocalTabBackend: endSession called during handshake`)),null),this.activePopup&&this.activeSessionId)try{this.deps.postToPopup(this.activePopup,{kind:`goodbye`,sessionId:this.activeSessionId})}catch{}if(this.messageUnsub&&=(this.messageUnsub(),null),this.activePopup){try{this.activePopup.close()}catch{}this.activePopup=null}this.activeSessionId=null,this.setState(`session-ended`)}}dispose(){this.disposed||(this.disposed=!0,this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.pendingReject&&=(this.pendingReject(Error(`LocalTabBackend: dispose() called during handshake`)),null),this._state!==`session-active`&&this.activeTransport===null&&(this.activePopup=null),this.endSession(),this.stateListeners.clear())}},hV=null;function gV(e){return e===`chromecast`?new dV:new mV}function _V(){return hV||(hV=gV(iV),hV)}function vV(e,t){switch(e){case`next`:t.onNext();return;case`start`:t.onStart();return;case`pause`:t.onPause();return;case`stop`:t.onStop();return}}function yV(e,t){vV(e.name,t)}var bV=new Set;function xV(e){return bV.add(e),()=>{bV.delete(e)}}function SV(e){for(let t of bV)try{t(e)}catch(e){dF(`resultRecorder`,`error in listener:`,e)}}function CV(e){return{async record({resultId:t,data:n,createdAt:r}){let i=await e.finishSession(t,n,r);return SV(i),i}}}var wV=CV(Nj);function TV(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:Jz(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:Jz(Math.round(e.elapsed*1e3))})})}return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:n,completedSegments:e.length,rows:r}}}function EV(e){return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:e.totalDurationMs,completedSegments:e.segmentCount,rows:[{label:`Total Time`,value:Jz(e.totalDurationMs)},{label:`Segments`,value:String(e.segmentCount)}]}}}function DV(e,t){let n=t.filter(e=>e.type===`time`||e.type===`log`);return n.length===0&&!e?{type:`rpc-workbench-update`,mode:`idle`}:{type:`rpc-workbench-update`,mode:`preview`,previewData:{title:(e?.content??n[0]?.content??``).split(`
138
+ `}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col items-center justify-center overflow-hidden ${S?`px-4 py-1`:`p-4`} ${x?`min-w-0`:``}`,children:(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full relative w-full`,children:[h&&(0,H.jsx)(`div`,{className:`animate-skip-flash absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap bg-signal-caution text-white dark:text-white text-sm font-semibold px-4 py-1.5 rounded-full shadow-lg pointer-events-none z-20`,role:`status`,"aria-live":`polite`,children:`Timer can't be skipped!`},g),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`h-8 min-h-0 shrink mb-1`:`h-24 mb-6 shrink-0`}`,children:(0,H.jsxs)(uB,{children:[s?.label&&(0,H.jsx)(`h2`,{className:`font-semibold text-foreground tracking-tight ${S?`text-lg`:`text-3xl lg:text-4xl`}`,children:s.label}),u&&u.length>0&&(0,H.jsx)(`div`,{className:`${S?`mt-1 space-y-0.5`:`mt-2 space-y-1`}`,children:u.map((e,t)=>(0,H.jsx)(`p`,{className:`text-muted-foreground ${S?`text-xs`:`text-lg lg:text-xl`}`,children:e},t))}),u===void 0&&l&&(0,H.jsx)(`p`,{className:`text-muted-foreground ${S?`mt-1 text-xs`:`mt-2 text-lg lg:text-xl`}`,children:l})]})}),(0,H.jsx)(`div`,{className:`relative flex min-h-12 w-full flex-1 items-center justify-center`,children:(0,H.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`timer-main`):{},className:`tv-focusable relative z-10 flex h-full max-h-full min-h-[48px] w-full items-center justify-center focus:outline-none focus-visible:outline-2 focus-visible:outline-ring group ${S?`py-1`:`py-8`}`,title:O,children:(0,H.jsx)(uB,{children:(0,H.jsx)(`span`,{className:`block font-mono font-bold tracking-tighter text-foreground tabular-nums leading-none`,style:{fontSize:`${C}px`},role:`timer`,"aria-live":`polite`,"aria-atomic":`true`,children:cB(ee)})})})}),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`mt-1 h-6 min-h-0 shrink`:`mt-6 h-[60px] shrink-0`}`,children:(0,H.jsx)(`div`,{className:`flex items-center justify-center gap-2 ${S?`flex-wrap`:`gap-4`}`,children:te.map((e,t)=>(0,H.jsxs)(`div`,{...p?p(`secondary-timer-${t}`):{},className:`tv-focusable flex items-center gap-2 rounded-lg border bg-muted/40 text-muted-foreground ${S?`px-2.5 py-1.5 text-xs`:`px-4 py-2 text-sm`}`,title:e.label,role:`timer`,"aria-label":`${e.label} ${cB(e.displayMs)}`,"aria-atomic":`true`,children:[(0,H.jsx)(le,{className:`shrink-0 ${S?`w-3 h-3`:`w-4 h-4`}`}),(0,H.jsx)(`span`,{className:`font-medium truncate max-w-[120px]`,children:e.label}),(0,H.jsx)(`span`,{className:`font-mono font-semibold tabular-nums`,children:cB(e.displayMs)})]},e.id))})})]})}),(0,H.jsxs)(`div`,{className:`flex flex-shrink-0 items-center justify-center flex-wrap ${x?`gap-3 px-2 py-1`:c?`px-4 py-3 bg-background border-t border-border gap-3`:S?`gap-6 px-2 py-1`:`gap-8 px-2 pb-8`}`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,H.jsx)(`button`,{onClick:E,...p?p(`btn-stop`):{},className:`tv-focusable group flex items-center justify-center rounded-full border transition-all active:scale-95 ${S?`w-12 h-12 bg-muted border-border`:`w-16 h-16 bg-surface-container-low border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:`Stop Session`,"data-testid":sB.TIMER_STOP_SESSION,children:(0,H.jsx)(ke,{className:`${S?`w-5 h-5`:`w-7 h-7`} text-foreground group-hover:text-destructive transition-colors`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:`Stop`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,H.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`btn-pause`):{},className:`tv-focusable group flex items-center justify-center rounded-full transition-all active:scale-95 ${S?`w-12 h-12 bg-primary text-primary-foreground shadow-lg shadow-primary/20`:`w-20 h-20 bg-surface-container-low border border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:O,"data-testid":sB.TIMER_PLAY_PAUSE,children:a?(0,H.jsx)(Ht,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`}):i?(0,H.jsx)(fr,{className:`${S?`w-6 h-6 text-primary-foreground`:`w-8 h-8 text-foreground`}`}):(0,H.jsx)(Ht,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:O})]}),c?(0,H.jsxs)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable ${x?`h-12 flex-none px-3`:`flex-1 h-14`} rounded-2xl flex items-center justify-center gap-2 transition-transform shadow-lg ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary text-primary-foreground shadow-primary/20 active:scale-[0.98]`}`,title:`Next Block`,"data-testid":sB.TIMER_NEXT_BLOCK,children:[(0,H.jsx)(`span`,{className:`text-base font-bold tracking-widest uppercase`,children:`Next`}),(0,H.jsx)(ht,{className:`w-5 h-5`})]}):(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,H.jsx)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable flex items-center justify-center rounded-full transition-all shadow-xl ${S?`w-12 h-12`:`w-24 h-24`} ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary-container text-on-primary-container hover:bg-primary hover:text-primary-foreground active:scale-90`}`,title:`Next Block`,"data-testid":sB.TIMER_NEXT_BLOCK,children:(0,H.jsx)(ht,{className:`font-bold ${S?`w-6 h-6`:`w-10 h-10`}`})}),!S&&(0,H.jsx)(`span`,{className:`font-mono text-[10px] font-bold uppercase tracking-widest text-on-primary-container`,children:`Next`})]})]})]})},fB={time:`bg-metric-time/15 border-metric-time/40 text-metric-time`,rep:`bg-metric-rep/15 border-metric-rep/40 text-metric-rep`,effort:`bg-metric-effort/15 border-metric-effort/40 text-metric-effort`,distance:`bg-metric-distance/15 border-metric-distance/40 text-metric-distance`,rounds:`bg-metric-rounds/15 border-metric-rounds/40 text-metric-rounds`,action:`bg-metric-action/15 border-metric-action/40 text-metric-action`,increment:`bg-metric-rounds/10 border-metric-rounds/35 text-metric-rounds`,lap:`bg-metric-rep/10 border-metric-rep/35 text-metric-rep`,text:`bg-muted border-border text-muted-foreground`,resistance:`bg-metric-resistance/15 border-metric-resistance/40 text-metric-resistance`,duration:`bg-metric-time/10 border-metric-time/30 text-metric-time`,spans:`bg-metric-distance/10 border-metric-distance/30 text-metric-distance`,elapsed:`bg-metric-time/12 border-metric-time/28 text-metric-time`,total:`bg-muted border-border text-foreground`,"system-time":`bg-muted/60 border-border/60 text-muted-foreground`,metric:`bg-metric-effort/10 border-metric-effort/30 text-metric-effort`,custom:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,calculated:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rest:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,volume:`bg-metric-rep/12 border-metric-rep/35 text-metric-rep`,load:`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,"session-load":`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,intensity:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,work:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rir:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"session-rpe":`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"met-score":`bg-metric-distance/12 border-metric-distance/35 text-metric-distance`,tis:`bg-metric-action/12 border-metric-action/35 text-metric-action`,"current-round":`bg-metric-rounds/10 border-metric-rounds/30 text-metric-rounds`,label:`bg-muted border-border text-muted-foreground`,system:`bg-muted/60 border-border/60 text-muted-foreground`,sound:`bg-muted/50 border-border/50 text-muted-foreground`,group:`bg-muted/50 border-border/50 text-muted-foreground`};function pB(e,t){return e.toLowerCase()!==`effort`||!t?!1:t.trim().toLowerCase()===`rest`}function mB(e,t){let n=`bg-gray-200 border-gray-300 text-gray-800 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100`;return pB(e,t)?fB.rest??n:fB[e.toLowerCase()]??n}var hB={time:`⏱️`,duration:`⏱️`,rounds:`🔄`,resistance:`💪`,weight:`💪`,distance:`📏`,action:`▶️`,rest:`⏸️`,effort:`🏃`,increment:`↕️`,text:`📝`,elapsed:`⏱️`,spans:`📊`,total:`🕐`,"system-time":`🖥️`,metric:`📈`,volume:`🏋️`,intensity:`⚡`,load:`⚖️`,work:`🔥`,rir:`🔋`,"session-rpe":`😓`,"session-load":`📊`,"met-score":`🫀`,tis:`📈`,calculated:`🧮`,custom:`✳️`,"current-round":`🔄`,label:`🏷️`,system:`⚙️`,sound:`🔊`,group:`🔀`,lap:`🏁`};function gB(e,t){return pB(e,t)?hB.rest:hB[e.toLowerCase()]||null}var _B=new Set([`duration`,`time`,`elapsed`,`total`,`spans`]);function vB(e,t){let n=e.toLowerCase().replace(/[^a-z0-9]/g,``),r={reps:`rep`,rep:`rep`,distance:`distance`,rounds:`rounds`,round:`rounds`,currentround:`current-round`,action:`action`,increment:`increment`,lap:`lap`,text:`text`,resistance:`resistance`,weight:`resistance`,duration:`duration`,spans:`spans`,elapsed:`elapsed`,total:`total`,totaltime:`total`,systemtime:`system-time`,label:`label`,system:`system`,sound:`sound`,group:`group`};if(r[n])return r[n];if(n.includes(`rir`))return`rir`;if(n.includes(`sessionrpe`)||n===`rpe`)return`session-rpe`;if(n.includes(`sessionload`))return`session-load`;if(n.includes(`metscore`)||n===`met`)return`met-score`;if(n===`tis`)return`tis`;if(n.includes(`calculated`)||n.includes(`calc`))return`calculated`;if(n.includes(`custom`))return`custom`;if(n.includes(`volume`))return`volume`;if(n.includes(`intensity`))return`intensity`;if(n.includes(`load`))return`load`;if(n.includes(`work`)||n.includes(`energy`)||n.includes(`calorie`))return`work`;if(n.includes(`set`))return`metric`;if(t){let e=t.toLowerCase();if(e===`reps`||e===`rep`)return`rep`;if(e===`km`||e===`m`||e===`mi`||e===`ft`||e===`yd`)return`distance`;if(e===`lb`||e===`kg`||e===`lbs`||e===`pood`)return`resistance`;if(e===`min`||e===`sec`||e===`ms`||e===`h`)return`duration`;if(e===`kcal`||e===`cal`)return`work`;if(e===`round`||e===`rounds`)return`rounds`;if(e===`sets`||e===`set`)return`metric`}return`metric`}function yB(e,t,n){if(e==null)return`—`;if(typeof e==`string`)return e;if(typeof e!=`number`||!Number.isFinite(e))return String(e);if(_B.has(t)){let t=n?.toLowerCase();return Qz(t===`sec`||t===`s`?e*1e3:t===`min`||t===`m`?e*60*1e3:t===`h`||t===`hr`?e*60*60*1e3:e)}return Number.isInteger(e)?String(e):e.toFixed(1)}var bB=({className:e})=>{let t=Jf(),n={};for(let e of t){let t=e.metrics;for(let e=0;e+1<t.length;e+=2){let r=t[e],i=t[e+1];if(r&&i){let e=r.image??String(r.value);n[e]={value:i.value,unit:i.unit}}}}let r=Object.entries(n);return r.length>0?(0,H.jsxs)(`div`,{className:U(`flex h-14 flex-shrink-0 flex-wrap items-center justify-center gap-2 overflow-hidden px-4`,e),children:[r.map(([e,t])=>{let n=vB(e,t.unit),r=mB(n),i=gB(n),a=yB(t.value,n,t.unit);return(0,H.jsxs)(`div`,{className:U(`flex flex-col items-center backdrop-blur-md border rounded-xl px-3 py-1.5 shadow-sm ring-1 ring-black/5 dark:ring-white/5 group transition-colors`,r),children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 opacity-70`,children:[i&&(0,H.jsx)(`span`,{className:`text-[10px] leading-none`,"aria-hidden":`true`,children:i}),(0,H.jsx)(`span`,{className:`text-[8px] font-black uppercase tracking-tighter group-hover:opacity-100 transition-opacity`,children:po(e)})]}),(0,H.jsxs)(`div`,{className:`flex items-baseline gap-0.5`,children:[(0,H.jsx)(`span`,{className:`text-sm font-black tabular-nums tracking-tight`,children:a}),t.unit&&!_B.has(n)&&(0,H.jsx)(`span`,{className:`text-[9px] font-bold opacity-60 uppercase`,children:t.unit})]})]},`bubble-${e}`)}),(0,H.jsx)(`div`,{className:`self-center bg-primary/10 border border-primary/20 rounded-full p-1.5 shadow-inner opacity-40 hover:opacity-100 transition-opacity cursor-help`,title:`Session Aggregates`,children:(0,H.jsx)(Cn,{className:`h-3 w-3 text-primary`})})]}):(0,H.jsx)(`div`,{className:U(`h-14 shrink-0`,e),"aria-hidden":`true`})},xB=e=>{let t=Kf(),n=wF(e=>e.viewMode),r=wF(e=>e.execution.status),[i,a]=V.useState(0),[o,s]=V.useState(!1),c=V.useRef(null);V.useEffect(()=>{if(!t)return;let e=t.eventBus.on(`timer:skip-attempt`,()=>{a(e=>e+1),s(!0),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>s(!1),3e3)},`ui-flash`);return()=>{e(),c.current&&clearTimeout(c.current)}},[t]);let l=$f(),u=ep(),d=Qf(),f=tp(),p=np(),m=p?.find(e=>e.block.blockType===`Rounds`),h=Uf(m?.block),[g,_]=V.useState(hl()),v=(0,V.useMemo)(()=>d.some(e=>e.timer.spans.some(e=>e.ended===void 0)),[d]);V.useEffect(()=>{if(!v)return;let e,t=()=>{_(hl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[v]);let y=(0,V.useMemo)(()=>l?qz(l.timer.spans,g):0,[l,g]),b=(0,V.useMemo)(()=>{let e=new Map;for(let t of d){let n=t.block.key.toString(),r=qz(t.timer.spans,g);e.set(n,{elapsed:r,duration:t.timer.durationMs,format:t.timer.direction})}return e},[d,g]),x=(0,V.useMemo)(()=>{if(!l)return;let e=l.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:l.timer.label,format:l.timer.direction,durationMs:l.timer.durationMs,role:l.isPinned?`primary`:`auto`}},[l]),S=(0,V.useMemo)(()=>u.map(e=>{let t=e.block.key.toString();return{id:`timer-${t}`,ownerId:t,timerMemoryId:``,label:e.timer.label,format:e.timer.direction,durationMs:e.timer.durationMs,role:e.isPinned?`primary`:`auto`}}),[u]),C=(0,V.useMemo)(()=>f.filter(e=>e.visible&&e.enabled&&e.eventName).map(e=>({id:e.id,name:e.label,eventName:e.eventName,ownerId:``,displayLabel:e.label,isPinned:e.isPinned})),[f]),w=l?l.block.key.toString():void 0,{mainLabel:T,subLabel:E,activeTimerEntry:D,activeElapsed:O}=(0,V.useMemo)(()=>{let e=p?.find(e=>e.isLeaf),t=e?.label,n=p?.find(e=>e.block.blockType===`Rounds`),r=h?.label??n?.label,i=e?d.find(t=>t.block.key.toString()===e.block.key.toString()):void 0,a=i?qz(i.timer.spans,g):0;if(l&&l.isPinned){let e=qz(l.timer.spans,g),n=r||l.timer.label;return{mainLabel:n,subLabel:n===t?void 0:t,activeTimerEntry:l,activeElapsed:e}}return r&&r!==t?{mainLabel:r,subLabel:t,activeTimerEntry:i||l,activeElapsed:i?a:y}:{mainLabel:t||l?.timer.label||`Timer`,subLabel:void 0,activeTimerEntry:i||l,activeElapsed:i?a:y}},[l,p,d,g,y,h]),k=(0,V.useMemo)(()=>{let e=p?.find(e=>e.isLeaf);if(!e)return E?[E]:void 0;if(e.displayRows&&e.displayRows.length>1){let t=e.displayRows.map(e=>_o.presentGroup([...e],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()).filter(Boolean);if(t.length>0)return t}return E?[E]:void 0},[p,E]),A=(0,V.useMemo)(()=>{if(D){let e=D.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:T,format:D.timer.direction,durationMs:D.timer.durationMs,role:D.isPinned?`primary`:`auto`,accumulatedMs:O}}if(x)return{...x,label:T,accumulatedMs:O}},[x,D,T,O]);return(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2`,children:[(0,H.jsx)(`div`,{className:`min-h-0 shrink overflow-y-auto pb-2`,children:(0,H.jsx)(bB,{})}),(0,H.jsx)(dB,{elapsedMs:O,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,actions:C.length>0?C:void 0,skipFlash:o,skipFlashKey:i,onAction:(n,r)=>{switch(t.handle({name:n,timestamp:new Date,data:r}),n){case`timer:pause`:e.onPause?.();break;case`timer:resume`:case`timer:start`:e.onStart?.();break;case`workout:stop`:e.onStop?.()}},isRunning:v||r===`running`,isPaused:r===`paused`,disableNext:r===`paused`,primaryTimer:A,subLabel:E,subLabels:k,secondaryTimers:S,stackItems:p,compact:e.compact,focusedBlockId:w,timerStates:b,enableGestures:n===`track`,getFocusProps:e.getFocusProps})]})},SB=e=>{let t=wF(e=>e.viewMode),{onNext:n,disableNext:r,isPaused:i}=e;return(0,V.useEffect)(()=>{if(t!==`track`)return;let e=e=>{if(e.key===`AudioVolumeUp`||e.key===`Enter`||e.keyCode===13){let t=document.activeElement;!(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))&&!r&&!i&&(e.preventDefault(),n())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,r,i,t]),e.enableDisplayStack?(0,H.jsx)(xB,{...e}):(0,H.jsx)(dB,{elapsedMs:e.elapsedMs,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isRunning:e.isRunning,isPaused:e.isPaused,disableNext:e.disableNext,compact:e.compact,enableGestures:t===`track`,getFocusProps:e.getFocusProps})},CB=Jz,wB=()=>{let e=null;try{e=tk()}catch{}return e},TB=({model:e})=>e.skipFlash?(0,H.jsx)(`div`,{className:`timer-surface-flash absolute -top-2 left-1/2 z-20 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-full bg-signal-caution px-4 py-1.5 text-sm font-semibold text-white shadow-lg pointer-events-none`,role:`status`,"aria-live":`polite`,children:`Timer can't be skipped!`},e.skipFlashKey):null,EB=({model:e,onStart:t,onPause:n,size:r,showChips:i,getFocusProps:a})=>{let o=wB(),s=(0,V.useCallback)(()=>{o?.playClick(),t()},[o,t]),c=(0,V.useCallback)(()=>{o?.playClick(),n()},[o,n]),{isRunning:l,isPaused:u}=e,d=u?`Continue`:l?`Pause`:`Start`,f=u?s:l?c:s,p=r===`tv`;return(0,H.jsxs)(`div`,{className:`relative flex min-h-0 w-full flex-1 flex-col items-center justify-center overflow-hidden text-center`,children:[(0,H.jsx)(`style`,{children:`
139
+ @keyframes timer-surface-flash-fade {
140
+ 0% { opacity: 1; transform: translate(-50%, -100%) translateY(0); }
141
+ 70% { opacity: 1; transform: translate(-50%, -100%) translateY(-4px); }
142
+ 100% { opacity: 0; transform: translate(-50%, -100%) translateY(-8px); }
143
+ }
144
+ .timer-surface-flash {
145
+ animation: timer-surface-flash-fade 3s ease-out forwards;
146
+ }
147
+ @media (prefers-reduced-motion: reduce) {
148
+ .timer-surface-flash { animation: none; }
149
+ }
150
+ `}),(0,H.jsx)(TB,{model:e}),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${p?`mb-[1.2cqw]`:`mb-2.5`}`,children:(0,H.jsxs)(uB,{children:[(0,H.jsx)(`h2`,{className:`font-semibold tracking-tight text-foreground ${p?`text-[3.4cqw]`:`text-xl`}`,children:e.mainLabel}),e.subLabels&&e.subLabels.length>0&&(0,H.jsx)(`div`,{className:`${p?`mt-[0.6cqw] space-y-[0.4cqw]`:`mt-1 space-y-0.5`}`,children:e.subLabels.map((e,t)=>(0,H.jsx)(`p`,{className:`text-muted-foreground ${p?`text-[2cqw]`:`text-[13.5px]`}`,children:e},t))})]})}),(0,H.jsx)(`button`,{onClick:f,...a?a(`timer-main`):{},className:`tv-focusable group relative z-10 flex h-full max-h-full min-h-[48px] w-full items-center justify-center focus:outline-none`,title:d,children:(0,H.jsx)(uB,{children:(0,H.jsx)(`span`,{className:`block font-mono font-bold leading-none tracking-tighter text-foreground tabular-nums ${p?`text-[13cqw]`:`text-[21cqw]`}`,role:`timer`,"aria-live":`polite`,"aria-atomic":`true`,children:CB(e.displayMs)})})}),(0,H.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${p?`mt-[1.2cqw] h-[4.4cqw]`:`mt-1.5 h-8`}`,children:i&&(0,H.jsxs)(`div`,{className:`flex items-center justify-center ${p?`gap-[1cqw]`:`gap-2`}`,children:[e.secondaryTimers.map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-[0.6em] rounded-lg border border-border bg-muted/40 text-muted-foreground ${p?`px-[1.4cqw] py-[0.8cqw] text-[1.7cqw]`:`px-2.5 py-1.5 text-xs`}`,role:`timer`,"aria-label":`${e.label} ${CB(e.displayMs)}`,"aria-atomic":`true`,children:[(0,H.jsx)(le,{className:`shrink-0 ${p?`w-[1.8cqw] h-[1.8cqw]`:`w-3 h-3`}`}),(0,H.jsx)(`span`,{className:`max-w-[10em] truncate font-medium`,children:e.label}),(0,H.jsx)(`span`,{className:`font-mono font-semibold tabular-nums`,children:CB(e.displayMs)})]},e.id)),e.roundLabel&&(0,H.jsxs)(`div`,{className:`flex items-center gap-[0.6em] rounded-lg border border-border bg-muted/40 text-muted-foreground ${p?`px-[1.4cqw] py-[0.8cqw] text-[1.7cqw]`:`px-2.5 py-1.5 text-xs`}`,"aria-label":e.roundLabel,children:[(0,H.jsx)(me,{className:`shrink-0 text-metric-rounds ${p?`w-[1.8cqw] h-[1.8cqw]`:`w-3 h-3`}`}),(0,H.jsx)(`span`,{className:`font-medium`,children:e.roundLabel})]})]})})]})},DB=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:a,getFocusProps:o})=>{let s=wB(),{isRunning:c,isPaused:l,isNextDisabled:u}=e,d=l?`Continue`:c?`Pause`:`Start`,f=(0,V.useCallback)(()=>{s?.playClick(),t()},[s,t]),p=(0,V.useCallback)(()=>{s?.playClick(),n()},[s,n]),m=(0,V.useCallback)(()=>{s?.playClick(),r()},[s,r]),h=(0,V.useCallback)(()=>{u||(s?.playClick(),i())},[s,u,i]),g=a===`tv`,_=(0,H.jsx)(`button`,{onClick:m,...o?o(`btn-stop`):{},className:`tv-focusable group flex shrink-0 items-center justify-center rounded-full border border-border bg-muted transition-all active:scale-95 ${g?`h-[6cqw] w-[6cqw]`:`h-12 w-12`}`,title:`Stop Session`,"data-testid":sB.TIMER_STOP_SESSION,children:(0,H.jsx)(ke,{className:`text-foreground transition-colors group-hover:text-destructive ${g?`h-[2.2cqw] w-[2.2cqw]`:`h-[17px] w-[17px]`}`})}),v=(0,H.jsx)(`button`,{onClick:l?f:c?p:f,...o?o(`btn-pause`):{},className:`tv-focusable flex shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/20 transition-all active:scale-95 ${g?`h-[7cqw] w-[7cqw]`:`h-[54px] w-[54px]`}`,title:d,"data-testid":sB.TIMER_PLAY_PAUSE,children:l?(0,H.jsx)(Ht,{className:`${g?`ml-[0.3cqw] h-[2.8cqw] w-[2.8cqw]`:`ml-0.5 h-[22px] w-[22px]`}`}):c?(0,H.jsx)(fr,{className:g?`h-[2.8cqw] w-[2.8cqw]`:`h-[22px] w-[22px]`}):(0,H.jsx)(Ht,{className:`${g?`ml-[0.3cqw] h-[2.8cqw] w-[2.8cqw]`:`ml-0.5 h-[22px] w-[22px]`}`})}),y=(0,H.jsxs)(`button`,{onClick:h,disabled:u,"aria-disabled":u?`true`:void 0,...o?o(`btn-next`):{},className:`tv-focusable flex items-center justify-center gap-2 bg-primary font-bold uppercase tracking-[0.12em] text-primary-foreground shadow-lg shadow-primary/20 transition-all active:scale-[0.98] disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground disabled:shadow-none ${g?`h-[7cqw] rounded-[1.4cqw] px-[4cqw] text-[2.2cqw]`:`h-[54px] flex-1 rounded-2xl text-[15px]`}`,title:`Next Block`,"data-testid":sB.TIMER_NEXT_BLOCK,children:[(0,H.jsx)(`span`,{children:`Next`}),(0,H.jsx)(ht,{className:g?`h-[2.4cqw] w-[2.4cqw]`:`h-5 w-5`})]}),b=(0,H.jsx)(`p`,{className:`truncate text-muted-foreground ${g?`pl-[0.4cqw] text-[1.8cqw]`:`pl-1 text-xs`}`,"data-testid":sB.TIMER_UP_NEXT_CAPTION,children:e.upNext&&(0,H.jsxs)(H.Fragment,{children:[`Up next: `,(0,H.jsx)(`b`,{className:`font-semibold text-foreground`,children:e.upNext})]})});return(0,H.jsxs)(`div`,{className:g?`flex items-end justify-center gap-[2cqw]`:`flex items-end gap-3`,children:[_,!g&&v,(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-col ${g?`items-start gap-[1cqw]`:`flex-1 items-stretch gap-2`}`,children:[b,g?(0,H.jsxs)(`div`,{className:`flex items-center gap-[1.6cqw]`,children:[v,y]}):y]})]})};function OB(e,t,n,r){let i=(0,V.useRef)(null),a=(0,V.useRef)(null),o=(0,V.useRef)({onNext:e,onStop:t,isNextDisabled:r});return o.current={onNext:e,onStop:t,isNextDisabled:r},{onTouchStart:(0,V.useCallback)(e=>{a.current=null,i.current=e.targetTouches[0].clientX},[]),onTouchMove:(0,V.useCallback)(e=>{a.current=e.targetTouches[0].clientX},[]),onTouchEnd:(0,V.useCallback)(()=>{let{onNext:e,onStop:t,isNextDisabled:r}=o.current;if(!n||!i.current||!a.current)return;let s=i.current-a.current,c=document.activeElement;c&&(c.tagName===`INPUT`||c.tagName===`TEXTAREA`||c.isContentEditable)||(s>50?r||e():s<-50&&t()),i.current=null,a.current=null},[n])}}var kB=({sessionElapsedMs:e,roundCurrent:t,roundTotal:n})=>{let r=t!==void 0&&n!==void 0&&n>0;return(0,H.jsxs)(`div`,{className:`flex h-11 shrink-0 items-center justify-between border-b border-border px-4`,"data-testid":`timer-status-strip`,children:[(0,H.jsxs)(`span`,{className:`flex items-center gap-1.5 font-mono text-xs text-muted-foreground tabular-nums`,children:[(0,H.jsx)(le,{className:`h-[13px] w-[13px]`}),Jz(e)]}),r&&(0,H.jsx)(`span`,{className:`flex items-center gap-[5px]`,role:`progressbar`,"aria-label":`Round ${t} of ${n}`,"aria-valuemin":1,"aria-valuemax":n,"aria-valuenow":t,children:Array.from({length:n},(e,n)=>{let r=n+1,i=r<t?`done`:r===t?`now`:`pending`;return(0,H.jsx)(`i`,{className:`block h-[7px] w-[7px] rounded-full ${i===`done`?`bg-primary/45`:i===`now`?`bg-primary`:`bg-border`}`},r)})})]})},AB=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,getFocusProps:a,enableGestures:o=!0,promptRow:s})=>{let c=OB(i,r,o,e.isNextDisabled);return(0,H.jsxs)(`div`,{className:`@container flex h-full flex-col bg-background text-foreground`,onTouchStart:c.onTouchStart,onTouchMove:c.onTouchMove,onTouchEnd:c.onTouchEnd,"data-testid":sB.TIMER_SURFACE_MINIMAL,children:[(0,H.jsx)(kB,{sessionElapsedMs:e.sessionElapsedMs,roundCurrent:e.roundCurrent,roundTotal:e.roundTotal}),s&&(0,H.jsx)(`div`,{className:`shrink-0`,children:s}),(0,H.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col px-5 pb-3 text-center`,children:(0,H.jsx)(EB,{model:e,onStart:t,onPause:n,size:`mobile`,showChips:!1,getFocusProps:a})}),(0,H.jsx)(`div`,{className:`shrink-0 border-t border-border p-4`,children:(0,H.jsx)(DB,{model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:`mobile`,getFocusProps:a})})]})},jB=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,workoutTitle:a,mode:o=`full`,promptRow:s,getFocusProps:c})=>o===`strip`?(0,H.jsxs)(`div`,{className:`@container flex h-full items-center gap-5 bg-background px-5 text-foreground`,"data-testid":sB.TIMER_SURFACE_GENERAL,children:[(0,H.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-3.5`,"data-testid":sB.TIMER_SURFACE_GENERAL_STRIP,children:[(0,H.jsx)(`h3`,{className:`truncate text-[17px] font-semibold tracking-tight`,children:e.mainLabel}),(0,H.jsx)(`span`,{className:`shrink-0 font-mono text-[40px] leading-none tabular-nums`,children:Jz(e.displayMs)})]}),(0,H.jsx)(`div`,{className:`ml-auto flex flex-col items-end gap-1.5`,children:(0,H.jsx)(DB,{model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:`mobile`,getFocusProps:c})})]}):(0,H.jsxs)(`div`,{className:`@container flex h-full flex-col bg-background p-[3cqw_4cqw] text-foreground`,"data-testid":sB.TIMER_SURFACE_GENERAL,children:[(0,H.jsxs)(`div`,{className:`flex shrink-0 items-center gap-[1.4cqw]`,children:[(0,H.jsxs)(`span`,{className:`flex items-center gap-[0.7cqw] font-mono text-[1.7cqw] text-muted-foreground tabular-nums`,children:[(0,H.jsx)(le,{className:`h-[1.9cqw] w-[1.9cqw]`}),`Session `,Jz(e.sessionElapsedMs)]}),a&&(0,H.jsx)(`span`,{className:`text-[2cqw] font-semibold tracking-tight`,children:a}),(0,H.jsxs)(`span`,{className:`ml-auto flex items-center gap-[1.4cqw] text-muted-foreground`,children:[(0,H.jsx)(On,{className:`h-[2.4cqw] w-[2.4cqw]`,"aria-hidden":`true`}),(0,H.jsx)(fe,{className:`h-[2.4cqw] w-[2.4cqw]`,"aria-hidden":`true`})]})]}),s&&(0,H.jsx)(`div`,{className:`shrink-0`,children:s}),(0,H.jsx)(EB,{model:e,onStart:t,onPause:n,size:`tv`,showChips:!0,getFocusProps:c}),(0,H.jsx)(`div`,{className:`shrink-0`,children:(0,H.jsx)(DB,{model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:`tv`,getFocusProps:c})})]});function MB(e){let t=Kf(),n=wF(e=>e.execution.status),r=$f(),i=Qf(),a=np(),o=a?.find(e=>e.block.blockType===`Rounds`),s=Uf(o?.block),c=Zf(),[l,u]=(0,V.useState)(0),[d,f]=(0,V.useState)(!1),p=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!t)return;let e=t.eventBus.on(`timer:skip-attempt`,()=>{u(e=>e+1),f(!0),clearTimeout(p.current),p.current=setTimeout(()=>f(!1),3e3)},`ui-flash`);return()=>{e(),clearTimeout(p.current)}},[t]);let m=i.some(e=>e.timer.spans.some(e=>e.ended===void 0)),[h,g]=(0,V.useState)(hl());return(0,V.useEffect)(()=>{if(!m)return;let e,t=()=>{g(hl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[m]),{...(0,V.useMemo)(()=>{let e=a?.find(e=>e.isLeaf),t=e?.label,n=s?.label??o?.label,l=e?i.find(t=>t.block.key.toString()===e.block.key.toString()):void 0,u=r?.isPinned?r:l||r,d=(r?.isPinned?n||r.timer.label:n&&n!==t?n:t||r?.timer.label)||`Timer`,f=d===t?void 0:t,p;if(e?.displayRows&&e.displayRows.length>1){let t=e.displayRows.map(e=>_o.presentGroup([...e],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()).filter(Boolean);t.length>0&&(p=t)}p||=f?[f]:void 0;let m=0;if(u){let e=qz(u.timer.spans,h);m=u.timer.direction===`down`&&u.timer.durationMs?Math.max(0,u.timer.durationMs-e):e}let g=i.map(e=>({t:e,elapsed:qz(e.timer.spans,h)})),_=r?.isPinned?{t:r,elapsed:qz(r.timer.spans,h)}:g.reduce((e,t)=>t.elapsed>(e?.elapsed??-1)?t:e,g[0]),v=_?.elapsed??0,y=u?.block.key.toString(),b=_?.t.block.key.toString(),x=i.filter(e=>{let t=e.block.key.toString();return t!==y&&t!==b}).map(e=>{let t=qz(e.timer.spans,h);return{id:e.block.key.toString(),label:e.timer.label,displayMs:e.timer.direction===`down`&&e.timer.durationMs?Math.max(0,e.timer.durationMs-t):t}}),S=null;return c?.metrics&&(S=_o.presentGroup([...c.metrics],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()||null),{mainLabel:d,subLabels:p,displayMs:m,sessionElapsedMs:v,roundCurrent:s?.current,roundTotal:s?.total,roundLabel:s?.label,secondaryTimers:x,upNext:S}},[r,i,a,h,s,o,c]),isRunning:m||n===`running`,isPaused:e.isPaused,isNextDisabled:e.isPaused,skipFlash:d,skipFlashKey:l}}var NB=e=>{let{isCompact:t,isFull:n,isShort:r}=aB(),i=MB({onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isPaused:!!e.isPaused});if(n)return(0,H.jsx)(SB,{elapsedMs:e.elapsedMs,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isRunning:e.isRunning,isPaused:e.isPaused,onBlockHover:e.onBlockHover,onBlockClick:e.onBlockClick,enableDisplayStack:e.enableDisplayStack,getFocusProps:e.getFocusProps});let a=(0,H.jsx)(`div`,{"data-testid":sB.TIMER_METRIC_PROMPTS,className:`shrink-0 overflow-y-auto border-b border-border px-4 py-1.5`,children:(0,H.jsx)(bB,{})});return t?(0,H.jsx)(AB,{model:i,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,getFocusProps:e.getFocusProps,enableGestures:e.enableGestures,promptRow:a}):(0,H.jsx)(jB,{model:i,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,getFocusProps:e.getFocusProps,workoutTitle:e.workoutTitle,mode:r?`strip`:`full`,promptRow:r?void 0:a})};function PB(e){let t=e.metric.image??String(e.metric.value??``);return{...e,colorClasses:mB(e.metric.type,t),icon:gB(e.metric.type,t),originClasses:e.userEntered?`border-dashed italic ring-1 ring-offset-1 ring-primary/30`:``}}function FB(e,t){return _o.presentGroup(e,t).map(PB)}var IB=V.memo(({metrics:e,error:t,className:n=``,size:r=`normal`,filter:i})=>{let a=(0,V.useMemo)(()=>i?e.filter(e=>{let t=String(e.value||``).toLowerCase(),n=e.type.toLowerCase();if(i.nameOverrides){if(t in i.nameOverrides)return i.nameOverrides[t];if(n in i.nameOverrides)return i.nameOverrides[n]}return i.typeOverrides&&n in i.typeOverrides?i.typeOverrides[n]:!i.allowedOrigins||i.allowedOrigins.includes(e.origin||`parser`)}):e,[e,i]);if(t)return(0,H.jsx)(`div`,{className:`border border-destructive/50 rounded-lg p-4 bg-destructive/10 ${n}`,children:(0,H.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-destructive font-bold text-lg`,children:`⚠️`}),(0,H.jsxs)(`div`,{className:`flex-1`,children:[(0,H.jsx)(`div`,{className:`font-semibold text-destructive mb-1`,children:`Parse Error`}),(0,H.jsx)(`div`,{className:`text-destructive/90 text-sm`,children:t.message}),(t.line!==void 0||t.column!==void 0)&&(0,H.jsxs)(`div`,{className:`text-destructive/80 text-xs mt-2`,children:[t.line!==void 0&&(0,H.jsxs)(`span`,{children:[`Line `,t.line]}),t.line!==void 0&&t.column!==void 0&&(0,H.jsx)(`span`,{children:`, `}),t.column!==void 0&&(0,H.jsxs)(`span`,{children:[`Column `,t.column]})]}),t.excerpt&&(0,H.jsx)(`pre`,{className:`mt-2 p-2 bg-background border border-destructive/20 rounded text-xs overflow-x-auto text-foreground`,children:t.excerpt})]})]})});if(!a||a.length===0)return(0,H.jsx)(`div`,{className:`border border-border rounded-lg p-4 bg-muted/20 text-center text-muted-foreground text-sm ${n}`,children:`No metrics to display`});let o={compact:{padding:`px-1 py-0`,text:`text-[10px] leading-tight`,icon:`text-xs`},normal:{padding:`px-2 py-0.5`,text:`text-sm`,icon:`text-base leading-none`},focused:{padding:`px-2.5 py-1`,text:`text-base`,icon:`text-lg leading-none`}}[r];return(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1 ${n}`,children:FB(a,`runtime-badge`).filter(e=>e.visible).map((e,t)=>e.renderKind===`comment`?(0,H.jsx)(`span`,{className:U(`italic text-muted-foreground select-text`,o.text),title:`COMMENT: ${e.label}`,"data-metric-type":`comment`,children:e.label},t):(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1 rounded font-mono border ${e.colorClasses} bg-opacity-60 shadow-sm cursor-help transition-colors hover:bg-opacity-80`,o.padding,o.text),title:e.tooltip,children:[e.icon&&(0,H.jsx)(`span`,{className:o.icon,children:e.icon}),(0,H.jsx)(`span`,{children:e.label})]},t))})});IB.displayName=`MetricVisualizer`;function LB(e){if(!e||e<0)return``;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}`:`${r}s`}var RB=({source:e,metrics:t,status:n=`pending`,depth:r=0,size:i=`normal`,filter:a,isSelected:o=!1,isHighlighted:s=!1,isLeaf:c=!1,isHeader:l=!1,label:u,showDuration:d=!1,duration:f,actions:p,metricGroups:m,onClick:h,onDoubleClick:g,onHover:_,className:v})=>{let y={compact:{indent:12,baseIndent:8,fontSize:`text-xs md:text-sm`},normal:{indent:16,baseIndent:12,fontSize:`text-sm md:text-base`},focused:{indent:20,baseIndent:16,fontSize:`text-base md:text-lg`}}[i],b=r*y.indent,x=K.from(t??(e?.getDisplayMetrics(a?{origins:a.allowedOrigins}:void 0)||[])).toArray(),S=t=>{h?.(e,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},C=t=>{t.preventDefault(),g?.(e)},w=()=>{_?.(e)},T=()=>{_?.(null)},E=u??(x.length===0?e?`Block ${e.id}`:`Block`:void 0);return(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 transition-all px-2`,l&&`font-semibold bg-muted/30`,h&&`cursor-pointer hover:bg-muted/50`,o&&`bg-primary/10`,s&&`bg-muted/40`,c&&`font-bold`,v),style:{paddingLeft:`${b+y.baseIndent}px`,minHeight:`var(--wod-preview-statement-height)`,paddingTop:`var(--wod-preview-statement-gap)`,paddingBottom:`var(--wod-preview-statement-gap)`},onClick:S,onDoubleClick:C,onMouseEnter:w,onMouseLeave:T,role:h?`button`:void 0,tabIndex:h?0:void 0,children:[(0,H.jsx)(`div`,{className:`flex-1 min-w-0`,children:m&&m.length>1?(0,H.jsx)(`div`,{className:`flex flex-col`,children:m.map(e=>_o.presentGroup([...e],`runtime-badge`).filter(e=>e.visible).map(e=>e.metric)).filter(e=>e.length>0).map((e,t,n)=>(0,H.jsx)(`div`,{className:U(t<n.length-1&&`border-b border-border/20 pb-0.5 mb-0.5`),children:(0,H.jsx)(IB,{metrics:e,size:i,filter:a,className:U(`inline-flex`,y.fontSize)})},t))}):x.length>0?(0,H.jsx)(IB,{metrics:x,size:i,filter:a,className:U(`inline-flex`,y.fontSize)}):E?(0,H.jsx)(`span`,{className:U(`text-muted-foreground`,y.fontSize),children:E}):(0,H.jsx)(`span`,{className:`text-muted-foreground/50 italic text-xs`,children:`No data`})}),d&&f!==void 0&&f>0&&(0,H.jsx)(`div`,{className:`flex-shrink-0 text-muted-foreground tabular-nums text-right min-w-[40px]`,style:{fontSize:i===`compact`?`10px`:`12px`},children:LB(f)}),p&&(0,H.jsx)(`div`,{className:`flex-shrink-0 flex items-center gap-1`,children:p})]})},zB={display:Ye,promote:Qt,private:ze,result:yn},BB={display:`text-green-500 dark:text-green-400`,promote:`text-blue-500 dark:text-blue-400`,private:`text-amber-500 dark:text-amber-400`,result:`text-purple-500 dark:text-purple-400`},VB={display:`bg-green-500/10 dark:bg-green-900/30`,promote:`bg-blue-500/10 dark:bg-blue-900/30`,private:`bg-amber-500/10 dark:bg-amber-900/30`,result:`bg-purple-500/10 dark:bg-purple-900/30`},HB=({visibility:e})=>{let t=zB[e];return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1 text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded`,BB[e],VB[e]),title:fl[e],children:[(0,H.jsx)(t,{className:`h-3 w-3`}),fl[e]]})},UB=({open:e,onOpenChange:t,children:n})=>(0,H.jsx)(L,{appear:!0,show:e,as:V.Fragment,children:(0,H.jsx)(He,{as:`div`,className:`relative z-[200]`,onClose:()=>t?.(!1),children:n})}),WB=V.forwardRef(({className:e,children:t,...n},r)=>(0,H.jsx)(Mn,{as:V.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0 scale-95`,enterTo:`opacity-100 scale-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100 scale-100`,leaveTo:`opacity-0 scale-95`,children:(0,H.jsx)(`div`,{className:`fixed inset-0 overflow-y-auto`,children:(0,H.jsxs)(`div`,{className:`flex min-h-full items-center justify-center p-4 text-center`,children:[(0,H.jsx)(Mn,{as:V.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0`,enterTo:`opacity-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100`,leaveTo:`opacity-0`,children:(0,H.jsx)(`div`,{className:`fixed inset-0 bg-black/25 dark:bg-black/25`})}),(0,H.jsx)(A,{ref:r,className:U(`relative w-full max-w-md transform overflow-hidden rounded-2xl bg-popover text-popover-foreground p-6 text-left align-middle shadow-xl transition-all border border-border`,e),...n,children:t})]})})}));WB.displayName=`DialogContent`;var GB=({className:e,...t})=>(0,H.jsx)(`div`,{className:U(`flex flex-col space-y-1.5 text-center sm:text-left mb-4`,e),...t});GB.displayName=`DialogHeader`;var KB=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(P,{ref:n,as:`h3`,className:U(`text-lg font-medium leading-6 text-foreground`,e),...t}));KB.displayName=`DialogTitle`;var qB=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(Xe,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t}));qB.displayName=`DialogDescription`;var JB=[`Statements`,`Behaviors`,`Memory`],YB=({open:e,onOpenChange:t,block:n,runtime:r})=>{let[i,a]=(0,V.useState)(0),o=(0,V.useMemo)(()=>!r.script||!n.sourceIds.length?[]:r.script.getIds(n.sourceIds),[r.script,n.sourceIds]),s=(0,V.useMemo)(()=>n.behaviors.map(e=>e.constructor.name),[n.behaviors]),l=(0,V.useMemo)(()=>n.getAllMemory(),[n]);return(0,H.jsx)(UB,{open:e,onOpenChange:t,children:(0,H.jsxs)(WB,{className:`max-w-2xl max-h-[80vh] flex flex-col overflow-hidden`,children:[(0,H.jsxs)(GB,{children:[(0,H.jsx)(KB,{children:(0,H.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{children:n.label}),n.blockType&&(0,H.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/10 text-primary/70 font-bold tracking-wider`,children:n.blockType})]})}),(0,H.jsxs)(`div`,{className:`text-[10px] font-mono text-muted-foreground`,children:[`Key: `,n.key.toString()]})]}),(0,H.jsxs)(c,{selectedIndex:i,onChange:a,children:[(0,H.jsx)(he,{className:`flex border-b border-border gap-0`,children:JB.map(e=>(0,H.jsx)(ve,{className:({selected:e})=>U(`px-4 py-2 text-sm font-medium transition-colors outline-none`,`border-b-2 -mb-px`,e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground hover:border-border`),children:e},e))}),(0,H.jsxs)(we,{className:`flex-1 min-h-0 overflow-y-auto mt-2`,children:[(0,H.jsx)(nn,{children:(0,H.jsx)(XB,{statements:o})}),(0,H.jsx)(nn,{children:(0,H.jsx)(ZB,{names:s})}),(0,H.jsx)(nn,{children:(0,H.jsx)(QB,{block:n,locations:l})})]})]})]})})},XB=({statements:e})=>e.length===0?(0,H.jsx)($B,{text:`No source statements`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`ID`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map(e=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:e.id}),(0,H.jsx)(`div`,{className:`py-0.5`,children:(0,H.jsx)(RB,{metrics:e.metrics,size:`compact`})})]},e.id))]}),ZB=({names:e})=>e.length===0?(0,H.jsx)($B,{text:`No behaviors attached`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`#`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Behavior`})]}),e.map((e,t)=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:t+1}),(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-sm font-mono`,children:e})]},t))]}),QB=({locations:e})=>e.length===0?(0,H.jsx)($B,{text:`No memory locations`}):(0,H.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Tag`}),(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map((e,t)=>(0,H.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:e.tag})}),(0,H.jsx)(`div`,{className:`py-0.5`,children:(0,H.jsx)(RB,{metrics:e.metrics,size:`compact`})})]},`${e.tag}-${t}`))]}),$B=({text:e})=>(0,H.jsx)(`div`,{className:`flex items-center justify-center py-8 text-sm text-muted-foreground italic`,children:e}),eV=({block:e,isLeaf:t,debug:n})=>{let{isDebugMode:r}=ty(),i=n??r,a=Kf(),{elapsed:o,isRunning:s,timeSpans:c}=rp(e.key.toString()),l=Uf(e),[u,d]=(0,V.useState)([]),[f,p]=(0,V.useState)([]),[m,h]=(0,V.useState)([]),[g,_]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let t=()=>{let t=e.getMetricMemoryByVisibility(`display`);if(d(t.map(e=>e.metrics)),i){let t=e.getMetricMemoryByVisibility(`promote`);p(t.map(e=>e.metrics));let n=e.getMetricMemoryByVisibility(`private`);h(n.map(e=>e.metrics))}};t();let n=(i?[...e.getMetricMemoryByVisibility(`display`),...e.getMetricMemoryByVisibility(`promote`),...e.getMetricMemoryByVisibility(`private`)]:e.getMetricMemoryByVisibility(`display`)).map(e=>e.subscribe(()=>t()));return()=>n.forEach(e=>e())},[e,i]);let v=c.length>0,y=(e,t,n,r)=>e.length===0?null:(0,H.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[n&&(0,H.jsx)(HB,{visibility:t}),e.map((e,n)=>(0,H.jsx)(RB,{metrics:e,size:r?`normal`:`compact`,isLeaf:r},`${t}-${n}`))]});return(0,H.jsxs)(`div`,{className:U(`relative w-full`,t?`animate-in fade-in slide-in-from-left-1 duration-300`:``),children:[(0,H.jsxs)(`div`,{className:U(`rounded-md border text-sm transition-all`,t?`bg-card shadow-sm border-primary/40 ring-1 ring-primary/10`:`bg-muted/30 border-transparent text-muted-foreground hover:bg-muted/50 hover:border-border/50`),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-3 p-3`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[!t&&(0,H.jsx)(`span`,{className:`text-xs font-medium tracking-tight text-muted-foreground/70`,children:e.blockType!==`SessionRoot`&&l?l.label:e.label}),t&&u.length>0&&(0,H.jsx)(`div`,{className:`flex items-center flex-wrap gap-0.5 min-w-0 font-bold text-foreground text-base`,children:y(u,`display`,!1,t)}),t&&u.length===0&&e.label&&(0,H.jsx)(`span`,{className:`text-base font-bold tracking-tight text-foreground`,children:e.label}),e.blockType&&i&&(0,H.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/5 text-primary/70 font-bold tracking-wider`,children:e.blockType})]}),i&&(0,H.jsx)(`div`,{className:`text-[10px] font-mono text-muted-foreground/60 truncate max-w-[200px] mt-0.5`,children:e.key.toString()})]}),v&&(0,H.jsxs)(`div`,{className:U(`flex items-center gap-1.5 px-2 py-1 rounded font-mono text-xs font-bold shrink-0`,s?`bg-primary/10 text-primary animate-pulse`:`bg-muted text-muted-foreground`),children:[(0,H.jsx)(le,{className:`h-3 w-3`}),Jz(o)]}),i&&(0,H.jsx)(`button`,{onClick:()=>_(!0),className:`h-9 w-9 rounded-md flex items-center justify-center hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0`,title:`Inspect block`,children:(0,H.jsx)(it,{className:`h-4 w-4`})})]}),!t&&u.length>0&&(0,H.jsx)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:y(u,`display`,i,t)}),i&&(f.length>0||m.length>0)&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:[y(f,`promote`,!0,t),y(m,`private`,!0,t)]})]}),i&&(0,H.jsx)(YB,{open:g,onOpenChange:_,block:e,runtime:a})]})};function tV(e,t,n){return e.filter(e=>e.outputType===`segment`&&t===Math.min(e.stackLevel-1,n-1))}var nV=({runtime:e,outputs:t,debug:n=!1})=>{let r=e.stack.blocks;if(r.length===0)return(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center p-8 text-muted-foreground border-2 border-dashed rounded-lg bg-muted/10`,children:[(0,H.jsx)(x,{className:`h-8 w-8 mb-2 opacity-20`}),(0,H.jsx)(`span`,{className:`text-sm`,children:`No Active Blocks`})]});let i=(e,n)=>{let r=tV(t,e,n);if(r.length===0)return null;let i=r.reduce((e,t)=>e+(t.getMetric(G.Elapsed)?.value??0),0);return(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground py-2 pl-4 border-l-2 border-muted ml-3 my-1 bg-muted/5 rounded-r-md`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(yn,{className:`h-3.5 w-3.5`}),(0,H.jsxs)(`span`,{className:`font-medium`,children:[r.length,` Completed`]})]}),(0,H.jsx)(`div`,{className:`w-px h-3 bg-border/50`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(De,{className:`h-3.5 w-3.5`}),(0,H.jsx)(`span`,{className:`font-mono`,children:(e=>{let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`})(i)})]})]})},a=[...r].reverse();return(0,H.jsx)(`div`,{className:`flex flex-col gap-1 relative`,children:a.map((e,t)=>{let r=t===a.length-1;return(0,H.jsxs)(V.Fragment,{children:[(0,H.jsx)(eV,{block:e,isLeaf:r,debug:n}),i(t,a.length)]},e.key.toString())})})},rV=()=>{let e=Zf();return e?(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:(0,H.jsx)(`div`,{className:U(`rounded-md border text-sm transition-all`,`bg-card/50 border-border/60 hover:bg-card/80`),children:(0,H.jsx)(`div`,{className:`flex flex-col gap-0.5 p-3`,children:(0,H.jsx)(RB,{metrics:e.metrics,size:`compact`,isLeaf:!1})})})}):(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-sm p-3 border border-dashed rounded-lg text-muted-foreground bg-muted/10`,children:[(0,H.jsx)(yn,{className:`h-4 w-4`}),(0,H.jsx)(`span`,{className:`italic`,children:`End of section`})]})},iV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`rounded-lg border bg-card text-card-foreground shadow-sm`,e),...t})));iV.displayName=`Card`;var aV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`flex flex-col space-y-1.5 p-6`,e),...t})));aV.displayName=`CardHeader`;var oV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`h3`,{ref:n,className:U(`text-2xl font-semibold leading-none tracking-tight`,e),...t})));oV.displayName=`CardTitle`;var sV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`p`,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t})));sV.displayName=`CardDescription`;var cV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`p-6 pt-0`,e),...t})));cV.displayName=`CardContent`;var lV=V.memo(V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(`div`,{ref:n,className:U(`flex items-center p-6 pt-0`,e),...t})));lV.displayName=`CardFooter`;var uV=()=>{let e=Kf(),{outputs:t}=qf(e),{isDebugMode:n}=ty(),{isCompact:r}=aB();return e?(0,H.jsxs)(`div`,{className:U(`h-full flex flex-col overflow-hidden bg-slate-50/50 dark:bg-slate-900/50`,r?`gap-2 p-2`:`gap-4 p-4`),children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col overflow-y-auto`,children:(0,H.jsx)(nV,{runtime:e,outputs:t,debug:n})}),(0,H.jsxs)(iV,{className:`shrink-0 bg-muted/30 border-dashed`,children:[(0,H.jsx)(aV,{className:U(r?`p-2 pb-0`:`p-3 pb-0`),children:(0,H.jsx)(oV,{className:U(`font-medium text-muted-foreground uppercase tracking-wider`,r?`text-xs`:`text-sm`),children:`Up Next`})}),(0,H.jsx)(cV,{className:U(r?`p-2`:`p-3`),children:(0,H.jsx)(rV,{runtime:e})})]})]}):null},dV=`38F01E0E`,fV=(e=>!!e&&e!==`CC1AD845`)(dV),pV=``;function mV(){return`chromecast`}var hV=pV===`chromecast`||pV===`local`?pV:mV(),gV=((typeof __LOCAL_RECEIVER_URL__<`u`?__LOCAL_RECEIVER_URL__:void 0)||``).trim(),_V=new class{state=`not-loaded`;listeners=new Map;loadPromise=null;appId=null;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){let n=this.listeners.get(e)??[];this.listeners.set(e,n.filter(e=>e!==t))}emit(e,...t){this.listeners.get(e)?.forEach(e=>e(...t))}getState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit(`state-changed`,e))}load(e){return this.loadPromise&&this.appId===e?this.loadPromise:(this.appId=e,this.loadPromise=this._load(e).catch(t=>{throw this.appId===e&&(this.loadPromise=null,this.appId=null),t}),this.loadPromise)}_load(e){return this.setState(`loading`),new Promise((t,n)=>{window.__onGCastApiAvailable=(r,i)=>{if(!r){console.warn(`[Cast SDK] Not available:`,i),this.setState(`unavailable`),n(Error(`Cast SDK unavailable`));return}try{this._initFramework(e),t()}catch(e){this.setState(`unavailable`),n(e)}};let r=`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`;if(!document.querySelector(`script[src="${r}"]`)){let e=document.createElement(`script`);e.src=r,e.onerror=()=>{this.setState(`unavailable`),n(Error(`Failed to load cast_sender.js`))},document.head.appendChild(e)}})}_initFramework(e){let{cast:t,chrome:n}=window;if(!t?.framework)throw Error(`cast.framework not found after SDK load`);let r=t.framework.CastContext.getInstance();r.setOptions({receiverApplicationId:e,autoJoinPolicy:n.cast.AutoJoinPolicy.ORIGIN_SCOPED,resumeSavedSession:!0}),r.addEventListener(t.framework.CastContextEventType.SESSION_STATE_CHANGED,e=>{let n=t.framework.SessionState;switch(e.sessionState){case n.SESSION_STARTED:case n.SESSION_RESUMED:this.setState(`session-active`),this.emit(`session-started`,r.getCurrentSession());break;case n.SESSION_ENDED:case n.NO_SESSION:this.setState(`ready`),this.emit(`session-ended`)}}),this.setState(`ready`),console.log(`[Cast SDK] Initialised with App ID:`,e)}async requestSession(){let{cast:e}=window;if(!e?.framework)throw Error(`Cast SDK not loaded`);let t=e.framework.CastContext.getInstance(),n=await t.requestSession();if(n)throw n===`cancel`?Error(`cancel`):(console.error(`[Cast SDK] requestSession() error code:`,n),Error(`Cast session request failed: ${n}`));let r=t.getCurrentSession();console.log(`[Cast SDK] requestSession() succeeded — sessionId:`,r?.getSessionId?.())}endSession(){window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}isSessionActive(){return this.state===`session-active`}getSession(){return window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()??null}},vV=`urn:x-cast:com.wodwiki`,yV=class{session;listeners=new Set;boundListener=null;constructor(e){this.session=e,this.boundListener=(e,t)=>{try{console.log(`[SenderCastSignaling] RAW incoming:`,typeof t,typeof t==`string`?t.substring(0,120):JSON.stringify(t).substring(0,120));let e=typeof t==`string`?JSON.parse(t):t;console.log(`[SenderCastSignaling] Parsed signal type:`,e.type);for(let t of this.listeners)t(e)}catch(e){console.error(`[SenderCastSignaling] Failed to parse incoming signal`,e)}},this.session.addMessageListener(vV,this.boundListener),console.log(`[SenderCastSignaling] Listening on ${vV}`),console.log(`[SenderCastSignaling] Session state: ${this.session.getSessionState?.()}`)}send(e){console.log(`[SenderCastSignaling] Sending: ${e.type}`),this.session.sendMessage(vV,e).then(()=>console.log(`[SenderCastSignaling] sendMessage(${e.type}) OK`)).catch(t=>console.error(`[SenderCastSignaling] sendMessage(${e.type}) FAILED`,t))}onSignal(e){return this.listeners.add(e),()=>this.listeners.delete(e)}dispose(){if(this.boundListener){try{this.session.removeMessageListener(vV,this.boundListener)}catch{}this.boundListener=null}this.listeners.clear()}},bV=class{role;signaling;pc;dc=null;signalUnsub=null;disposed=!1;messageHandlers=new Set;connectedHandlers=new Set;disconnectedHandlers=new Set;signalQueue=Promise.resolve();pendingIceCandidates=[];constructor(e,t){this.role=e,this.signaling=t,console.log(`[WebRtcRpcTransport:${e}] Initializing transport`),this.pc=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]}),this.pc.onicecandidate=t=>{t.candidate?(console.log(`[WebRtcRpcTransport:${e}] ICE candidate (local):`,t.candidate.candidate.substring(0,60)+`...`),this.signaling.send({type:`webrtc-ice`,candidate:t.candidate.toJSON()})):console.log(`[WebRtcRpcTransport:${e}] ICE gathering complete`)},this.pc.onconnectionstatechange=()=>{let t=this.pc.connectionState;console.log(`[WebRtcRpcTransport:${e}] Connection state: ${t}`),(t===`disconnected`||t===`failed`||t===`closed`)&&this.notifyDisconnected()},this.pc.oniceconnectionstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] ICE connection state: ${this.pc.iceConnectionState}`)},this.pc.onsignalingstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] Signaling state: ${this.pc.signalingState}`)},this.signalUnsub=this.signaling.onSignal(t=>{console.log(`[WebRtcRpcTransport:${e}] Incoming signal: ${t.type}`),this.signalQueue=this.signalQueue.then(()=>this.handleSignal(t))})}get connected(){return this.dc?.readyState===`open`}get needsClockSync(){return!0}send(e){if(!this.dc||this.dc.readyState!==`open`){console.warn(`[WebRtcRpcTransport] DataChannel not open — dropping message`);return}this.dc.send(JSON.stringify(e))}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onConnected(e){return this.connectedHandlers.add(e),()=>this.connectedHandlers.delete(e)}onDisconnected(e){return this.disconnectedHandlers.add(e),()=>this.disconnectedHandlers.delete(e)}dispose(){if(this.disposed)return;this.disposed=!0,this.signalUnsub?.(),this.signalUnsub=null;let e=this.dc?.readyState===`open`,t=[...this.disconnectedHandlers];if(this.messageHandlers.clear(),this.connectedHandlers.clear(),this.disconnectedHandlers.clear(),this.dc?.close(),this.pc.close(),this.signaling.dispose(),e)for(let e of t)e()}connect(e=15e3){return console.log(`[WebRtcRpcTransport:${this.role}] connect() starting, timeout=${e}ms`),this.connected?(console.log(`[WebRtcRpcTransport:${this.role}] Already connected — short-circuiting`),Promise.resolve()):new Promise((t,n)=>{let r=Date.now(),i=setTimeout(()=>{let t=`pcState=${this.pc.connectionState}, iceState=${this.pc.iceConnectionState}, sigState=${this.pc.signalingState}, dcState=${this.dc?.readyState??`null`}`;console.error(`[WebRtcRpcTransport:${this.role}] TIMEOUT after ${e}ms — ${t}`),n(Error(`WebRTC connect timed out after ${e}ms`))},e),a=()=>{clearTimeout(i),console.log(`[WebRtcRpcTransport:${this.role}] DataChannel OPEN in ${Date.now()-r}ms`),this.notifyConnected(),t()};this.role===`offerer`?(console.log(`[WebRtcRpcTransport:offerer] Creating DataChannel…`),this.dc=this.pc.createDataChannel(`wod-wiki-rpc`,{ordered:!0}),this.wireDataChannel(this.dc,a),console.log(`[WebRtcRpcTransport:offerer] Creating offer…`),this.pc.createOffer().then(e=>(console.log(`[WebRtcRpcTransport:offerer] Offer created, SDP length=${e.sdp?.length}`),this.pc.setLocalDescription(e))).then(()=>{console.log(`[WebRtcRpcTransport:offerer] Local description set — sending offer via signaling`),this.signaling.send({type:`webrtc-offer`,sdp:this.pc.localDescription.sdp}),console.log(`[WebRtcRpcTransport:offerer] Offer sent — waiting for answer…`)}).catch(e=>{console.error(`[WebRtcRpcTransport:offerer] Failed to create/set offer`,e),n(e)})):(console.log(`[WebRtcRpcTransport:answerer] Waiting for ondatachannel…`),this.pc.ondatachannel=e=>{console.log(`[WebRtcRpcTransport:answerer] Remote DataChannel received: ${e.channel.label}`),this.dc=e.channel,this.wireDataChannel(this.dc,a)})})}wireDataChannel(e,t){e.onopen=()=>t(),e.onclose=()=>{this.disposed||this.notifyDisconnected()},e.onerror=e=>{console.error(`[WebRtcRpcTransport] DataChannel error`,e)},e.onmessage=e=>{try{let t=JSON.parse(e.data);for(let e of this.messageHandlers)e(t)}catch(e){console.error(`[WebRtcRpcTransport] Failed to parse RPC message`,e)}}}async handleSignal(e){try{switch(e.type){case`webrtc-offer`:{if(this.role!==`answerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring offer (not an answerer)`);return}console.log(`[WebRtcRpcTransport:answerer] Received offer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`offer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:answerer] Remote description set — creating answer`);let t=await this.pc.createAnswer();console.log(`[WebRtcRpcTransport:answerer] Answer created, length=${t.sdp?.length}`),await this.pc.setLocalDescription(t),console.log(`[WebRtcRpcTransport:answerer] Local description set — sending answer via signaling`),this.signaling.send({type:`webrtc-answer`,sdp:this.pc.localDescription.sdp}),await this.processPendingIceCandidates();break}case`webrtc-answer`:if(this.role!==`offerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring answer (not an offerer)`);return}console.log(`[WebRtcRpcTransport:offerer] Received answer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`answer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:offerer] Remote description set — processing pending candidates…`),await this.processPendingIceCandidates();break;case`webrtc-ice`:{let t=e.candidate;this.pc.remoteDescription?(console.log(`[WebRtcRpcTransport:${this.role}] Adding remote ICE candidate`),await this.pc.addIceCandidate(t)):(console.log(`[WebRtcRpcTransport:${this.role}] Buffering candidate until remote description is set`),this.pendingIceCandidates.push(t));break}}}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Signal handling error`,e)}}async processPendingIceCandidates(){if(this.pendingIceCandidates.length===0)return;console.log(`[WebRtcRpcTransport:${this.role}] Processing ${this.pendingIceCandidates.length} buffered ICE candidates`);let e=[...this.pendingIceCandidates];this.pendingIceCandidates=[];for(let t of e)try{await this.pc.addIceCandidate(t),console.log(`[WebRtcRpcTransport:${this.role}] Buffered ICE candidate added OK`)}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Failed to add buffered ICE candidate`,e)}}notifyConnected(){for(let e of this.connectedHandlers)e()}notifyDisconnected(){for(let e of this.disconnectedHandlers)e()}},xV={"not-loaded":`ready`,loading:`ready`,unavailable:`unavailable`,ready:`ready`,"session-active":`session-active`},SV=class{_state;stateListeners=new Set;sdkUnsubState=null;sdkUnsubEnded=null;activeTransport=null;disposed=!1;constructor(){this._state=xV[_V.getState()],this.subscribeToSdk(),fV&&typeof window<`u`&&_V.load(dV).catch(()=>{})}get state(){return this._state}onStateChanged(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}setState(e){if(this._state!==e){this._state=e;for(let t of[...this.stateListeners])t(e)}}subscribeToSdk(){this.sdkUnsubState=_V.on(`state-changed`,e=>{let t=xV[e]??`ready`;this._state!==`session-active`&&(this._state!==`connecting`||t!==`session-active`)&&this.setState(t)}),this.sdkUnsubEnded=_V.on(`session-ended`,()=>{this.activeTransport=null,this.setState(`session-ended`)})}async startSession(){if(this.disposed)throw Error(`ChromecastBackend: startSession after dispose`);if(!fV)throw this.setState(`unavailable`),Error(`ChromecastBackend: VITE_CAST_APP_ID is not configured`);this.setState(`connecting`);let e=null;try{try{await _V.load(dV)}catch(e){throw this.setState(xV[_V.getState()]),e}if(this.disposed)throw Error(`ChromecastBackend: dispose() called during SDK load`);if(_V.getState()===`unavailable`)throw this.setState(`unavailable`),Error(`ChromecastBackend: Cast not supported in this browser`);if(await _V.requestSession(),this.disposed)throw Error(`ChromecastBackend: dispose() called during requestSession`);let t=_V.getSession();if(!t)throw Error(`ChromecastBackend: no Cast session after requestSession()`);try{await t.sendMessage(`urn:x-cast:com.wodwiki`,{type:`ping`,timestamp:Date.now()})}catch(e){aF(`ChromecastBackend`,`namespace ping failed`,e)}e=new bV(`offerer`,new yV(t)),await e.connect()}catch(t){throw e?.dispose(),!this.disposed&&this._state===`connecting`&&this.setState(`ready`),t}return this.activeTransport=e,e.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),e}async resumeSession(){if(this.disposed)throw Error(`ChromecastBackend: resumeSession after dispose`);if(this.activeTransport)return this.activeTransport;await _V.load(dV);let e=_V.getSession();if(!e)throw Error(`ChromecastBackend: no Cast session to resume`);let t=new bV(`offerer`,new yV(e));try{await t.connect()}catch(e){throw t.dispose(),e}return this.activeTransport=t,t.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),t}endSession(){try{_V.endSession()}catch{}this.activeTransport&&=(this.activeTransport.dispose(),null),this._state!==`unavailable`&&this.setState(`ready`)}dispose(){this.disposed||(this.disposed=!0,this.endSession(),this.sdkUnsubState?.(),this.sdkUnsubEnded?.(),this.sdkUnsubState=null,this.sdkUnsubEnded=null,this.stateListeners.clear())}},CV=class{port;_connected=!1;messageHandlers=new Set;connectedHandlers=new Set;disconnectedHandlers=new Set;_disposed=!1;portMessageUnsub;boundHandler;constructor(e){this.port=e,this.boundHandler=e=>{let t=e.data;for(let e of[...this.messageHandlers])e(t)},this.port.addEventListener(`message`,this.boundHandler),this.portMessageUnsub=()=>this.port.removeEventListener(`message`,this.boundHandler)}start(){if(!this._disposed&&!this._connected){this._connected=!0,this.port.start();for(let e of[...this.connectedHandlers])e()}}notifyDisconnected(){if(!this._disposed&&this._connected){this._connected=!1;for(let e of[...this.disconnectedHandlers])e()}}get connected(){return this._connected}get needsClockSync(){return!1}async connect(){this._connected||this.start()}send(e){if(this._disposed)throw Error(`BroadcastChannelRpcTransport: send after dispose`);if(!this._connected)throw Error(`BroadcastChannelRpcTransport: send before connected`);this.port.postMessage(e)}onMessage(e){return this.messageHandlers.add(e),()=>{this.messageHandlers.delete(e)}}onConnected(e){return this.connectedHandlers.add(e),()=>{this.connectedHandlers.delete(e)}}onDisconnected(e){return this.disconnectedHandlers.add(e),()=>{this.disconnectedHandlers.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this.portMessageUnsub();try{this.port.close()}catch{}this.messageHandlers.clear(),this.connectedHandlers.clear(),this.disconnectedHandlers.clear(),this._connected=!1}}},wV=5e3,TV=class{_state=`ready`;stateListeners=new Set;activePopup=null;activeTransport=null;activeTimeout=null;activeSessionId=null;pendingReject=null;messageUnsub=null;disposed=!1;deps;constructor(e={}){let t=e=>(window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e));this.deps={openPopup:e.openPopup??(e=>window.open(e,`_blank`,`width=1280,height=720`)),addEventListener:e.addEventListener??t,removeEventListener:e.removeEventListener??(e=>{window.removeEventListener(`message`,e)}),postToPopup:e.postToPopup??((e,t)=>{e.postMessage(t,window.location.origin)}),generateId:e.generateId??(()=>{let e=typeof crypto<`u`?crypto:void 0;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(!e)throw Error(`LocalTabBackend: crypto API unavailable`);let t=new Uint8Array(16);return e.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}),buildReceiverUrl:e.buildReceiverUrl??((e,t)=>`${gV||`${e}/receiver-rpc.html`}?local=${t}`),MessageChannelCtor:e.MessageChannelCtor??(typeof MessageChannel<`u`?MessageChannel:void 0),getOrigin:e.getOrigin??(()=>typeof window<`u`?window.location.origin:``),setTimeoutFn:e.setTimeoutFn??((e,t)=>setTimeout(e,t)),clearTimeoutFn:e.clearTimeoutFn??(e=>clearTimeout(e))}}get state(){return this._state}onStateChanged(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}setState(e){if(this._state!==e){this._state=e;for(let t of[...this.stateListeners])t(e)}}async startSession(){if(this.disposed)throw Error(`LocalTabBackend: startSession after dispose`);if(this._state===`connecting`||this._state===`session-active`)throw Error(`LocalTabBackend: startSession while a session is already active`);this.setState(`connecting`);let e=this.deps.generateId();this.activeSessionId=e;let t=this.deps.buildReceiverUrl(this.deps.getOrigin(),e);console.log(`[LocalTabBackend] startSession: opening popup`,{url:t,sessionId:e});let n=this.deps.openPopup(t);if(!n)throw this.setState(`session-ended`),this.activeSessionId=null,Error(`LocalTabBackend: window.open returned null (popup blocked?)`);this.activePopup=n,console.log(`[LocalTabBackend] popup opened`,{sessionId:e});let r=new this.deps.MessageChannelCtor,i=r.port1,a=r.port2,{promise:o,resolve:s,reject:c}=Promise.withResolvers();this.pendingReject=c;let l=e=>{this.cleanupOnError(),this.setState(`session-ended`),this.activeSessionId=null,this.pendingReject=null,c(Error(e))};this.activeTimeout=this.deps.setTimeoutFn(()=>{l(`LocalTabBackend: receiver did not complete handshake within ${wV}ms`)},wV);let u=t=>{if(t.source!==n)return;let r=t.data;if(!(!r||typeof r!=`object`||typeof r.kind!=`string`)&&r.sessionId===e){if(r.kind===`ready`){console.log(`[LocalTabBackend] received ready`,{sessionId:e});try{this.deps.postToPopup(n,{kind:`offer`,sessionId:e}),console.log(`[LocalTabBackend] posted offer`,{sessionId:e})}catch(e){l(e instanceof Error?e.message:String(e));return}try{n.postMessage({kind:`data-port`,sessionId:e},this.deps.getOrigin(),[a]),console.log(`[LocalTabBackend] transferred data port`,{sessionId:e})}catch(e){l(e instanceof Error?e.message:String(e))}}else if(r.kind===`accept`){console.log(`[LocalTabBackend] received accept`,{sessionId:e}),this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.pendingReject=null;let t=new CV(i);t.onDisconnected(()=>{this._state===`session-active`&&this.setState(`session-ended`)}),t.start(),this.activeTransport=t,this.setState(`session-active`),s(t)}else r.kind===`goodbye`&&(this.activeTransport&&this.activeTransport.notifyDisconnected(),this.activeTransport=null,this.activePopup=null,this.activeSessionId=null,this.setState(`session-ended`))}};return this.messageUnsub=this.deps.addEventListener(u),o}cleanupOnError(){this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.messageUnsub&&=(this.messageUnsub(),null),this.activeSessionId=null}endSession(){if(this._state===`session-active`||this._state===`connecting`){if(this.pendingReject&&=(this.pendingReject(Error(`LocalTabBackend: endSession called during handshake`)),null),this.activePopup&&this.activeSessionId)try{this.deps.postToPopup(this.activePopup,{kind:`goodbye`,sessionId:this.activeSessionId})}catch{}if(this.messageUnsub&&=(this.messageUnsub(),null),this.activePopup){try{this.activePopup.close()}catch{}this.activePopup=null}this.activeSessionId=null,this.setState(`session-ended`)}}dispose(){this.disposed||(this.disposed=!0,this.deps.clearTimeoutFn(this.activeTimeout),this.activeTimeout=null,this.pendingReject&&=(this.pendingReject(Error(`LocalTabBackend: dispose() called during handshake`)),null),this._state!==`session-active`&&this.activeTransport===null&&(this.activePopup=null),this.endSession(),this.stateListeners.clear())}},EV=null;function DV(e){return e===`chromecast`?new SV:new TV}function OV(){return EV||(EV=DV(hV),EV)}function kV(e,t){switch(e){case`next`:t.onNext();return;case`start`:t.onStart();return;case`pause`:t.onPause();return;case`stop`:t.onStop();return}}function AV(e,t){kV(e.name,t)}var jV=new Set;function MV(e){return jV.add(e),()=>{jV.delete(e)}}function NV(e){for(let t of jV)try{t(e)}catch(e){dF(`resultRecorder`,`error in listener:`,e)}}function PV(e){return{async record({resultId:t,data:n,createdAt:r}){let i=await e.finishSession(t,n,r);return NV(i),i}}}var FV=PV(Nj);function IV(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:Jz(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:Jz(Math.round(e.elapsed*1e3))})})}return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:n,completedSegments:e.length,rows:r}}}function LV(e){return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:e.totalDurationMs,completedSegments:e.segmentCount,rows:[{label:`Total Time`,value:Jz(e.totalDurationMs)},{label:`Segments`,value:String(e.segmentCount)}]}}}function RV(e,t){let n=t.filter(e=>e.type===`time`||e.type===`log`);return n.length===0&&!e?{type:`rpc-workbench-update`,mode:`idle`}:{type:`rpc-workbench-update`,mode:`preview`,previewData:{title:(e?.content??n[0]?.content??``).split(`
139
151
  `)[0].trim().substring(0,60)||`Workout`,blocks:n.slice(0,8).map(e=>({id:e.id,title:(e.scriptBlock?.content??e.content).split(`
140
- `)[0].trim().substring(0,50)||`Workout`,statementCount:e.scriptBlock?.statements?.length??0}))}}}var OV=`wod-wiki:userOutputOverrides`;function kV(e=!1){let t=wF(e=>e.userOutputOverrides),n=wF(e=>e.setUserOverride),r=wF(e=>e.clearUserOverride);return(0,V.useEffect)(()=>{if(e)try{let e=localStorage.getItem(OV);if(!e)return;let t=JSON.parse(e);for(let[e,r]of Object.entries(t))n(e,r.map(jV))}catch{}},[e,n]),(0,V.useEffect)(()=>{if(!e)return;if(t.size===0){localStorage.removeItem(OV);return}let n={};for(let[e,r]of t)n[e]=r.map(AV);localStorage.setItem(OV,JSON.stringify(n))},[t,e]),{overrides:t,setOverride:(0,V.useCallback)((e,r,i,a)=>{let o=(t.get(e)??K.empty(e)).filter(e=>e.type!==r),s={type:r,origin:`user`,value:i,image:a??String(i??``)};n(e,K.from(o,e).add(s))},[t,n]),removeOverride:(0,V.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,V.useCallback)(e=>{r(e)},[r]),clearAll:(0,V.useCallback)(()=>{for(let e of t.keys())r(e)},[t,r])}}function AV(e){return{type:e.type,value:e.value,image:e.image,origin:e.origin,sourceBlockKey:e.sourceBlockKey,timestamp:e.timestamp?.toISOString()}}function jV(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 MV=(typeof window<`u`?window.__wod_runtimeNowProvider?.():void 0)??Fc,NV=new $d(gf(),MV);function PV(e){return e.statements?.length?e:{...e,statements:Is().read(e.content,e.sport).statements}}function FV(e){return NV.createRuntime(PV(e))??null}function IV(e,t){return{startTime:t.startTime??t.now.nowMs(),endTime:t.now.nowMs(),duration:t.elapsedTime,completed:t.completed,logs:e.map(vj)}}function LV(e){return e.filter(e=>e.outputType===`segment`).length}function RV(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 zV(e,t,n){let r=e?.statements[t.statementIndex];r&&Zd(r,t.alternatives,n)}function BV(e,t,n){let r=(0,V.useMemo)(()=>{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===G.Effort||e.type===G.Label),c=s?.value?.toString()||s?.image||`Exercise`;for(let t of i.metrics){if(t.type===G.Choice){let n=t;r.push({kind:`choice`,blockKey:a,exerciseLabel:c,alternatives:n.alternatives,selectedIndex:0,statementIndex:e});continue}(t.origin===`hinted`||t.image===`?`)&&(o?.some(e=>e.type===t.type&&e.origin===`user`)||r.push({kind:`value`,blockKey:a,exerciseLabel:c,metricType:t.type,hint:t.image||`?`,origin:`hinted`,statementIndex:e}))}}return r}for(let n of e){if(!n.metrics)continue;let e=n.name||`segment-${n.id}`,i=t.get(e);for(let t of n.metrics)if((t.origin===`hinted`||t.image===`?`)&&!i?.some(e=>e.type===t.type&&e.origin===`user`)){let i=n.metrics.find(e=>e.type===G.Effort||e.type===G.Label),a=i?.value?.toString()||i?.image||`Exercise`,o=e.match(/\[(\d+)\]/),s=e.match(/\[\d+\]\[(\d+)\]/);r.push({kind:`value`,blockKey:e,exerciseLabel:a,metricType:t.type,hint:t.image||`?`,origin:`hinted`,statementIndex:0,roundIndex:o?parseInt(o[1])+1:void 0,setIndex:s?parseInt(s[1])+1:void 0})}}return r},[e,t,n]);return{collectionItems:r,totalCount:r.length,isComplete:r.length===0}}var VV=({items:e,onSave:t,onSkip:n,onStart:r,onClose:i,mode:a,className:o})=>{let[s,c]=(0,V.useState)(0),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(()=>{let t={};return e.forEach((e,n)=>{e.kind===`choice`&&(t[n]=0)}),t}),[p,m]=(0,V.useState)(a===`pre-run`);if((0,V.useEffect)(()=>{s>=e.length&&e.length>0&&c(e.length-1)},[e.length,s]),e.length===0)return null;let h=e[s];return h?a===`post-run`&&!p?(0,H.jsxs)(`div`,{className:U(`bg-warning/10 border border-warning/30 rounded-xl p-3 flex items-center justify-between`,o),children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-warning text-sm font-medium`,children:[(0,H.jsx)(gt,{className:`w-4 h-4`}),(0,H.jsxs)(`span`,{children:[e.length,` uncollected metrics — fill in your actuals`]})]}),(0,H.jsx)(`button`,{onClick:()=>m(!0),className:`px-3 py-1 bg-warning text-warning-foreground rounded-lg text-xs font-bold uppercase tracking-label hover:brightness-110 transition-all`,children:`Fill In Now`})]}):(0,H.jsxs)(`div`,{className:U(`bg-card border border-border rounded-2xl shadow-xl overflow-hidden flex flex-col`,a===`pre-run`?`fixed inset-0 z-50 md:inset-10`:`relative`,o),children:[(0,H.jsx)(`div`,{className:`h-1 bg-muted`,children:(0,H.jsx)(`div`,{className:`h-full bg-primary transition-all duration-300`,style:{width:`${(s+1)/e.length*100}%`}})}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-b border-border flex items-center justify-between bg-muted/10`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:a===`pre-run`?`Set Your Targets`:`Fill in your actuals`}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground uppercase tracking-label`,children:[s+1,` of `,e.length,` metrics`]})]}),i&&(0,H.jsx)(`button`,{onClick:i,className:`p-2 hover:bg-muted rounded-full transition-colors`,children:(0,H.jsx)(Te,{className:`w-5 h-5 text-muted-foreground`})})]}),(0,H.jsx)(`div`,{className:`flex-1 p-8 flex flex-col items-center justify-center max-w-md mx-auto w-full`,children:(0,H.jsxs)(`div`,{className:`w-full space-y-6`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,H.jsxs)(`div`,{className:`px-3 py-1 rounded-pill bg-metric-effort/15 border border-metric-effort/40 text-metric-effort text-xs font-bold`,children:[`🏃 `,h.exerciseLabel]}),(h.setIndex||h.roundIndex)&&(0,H.jsxs)(`div`,{className:`text-[10px] font-bold tracking-label uppercase text-muted-foreground`,children:[h.roundIndex&&`Round ${h.roundIndex}`,h.roundIndex&&h.setIndex&&` · `,h.setIndex&&`Set ${h.setIndex}`]}),h.kind===`choice`&&(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground font-medium`,children:`Choose one:`})]}),(0,H.jsx)(`div`,{className:`space-y-4`,children:h.kind===`choice`?((e,t)=>{let n=d[t]??0;return(0,H.jsx)(`div`,{className:`flex flex-col gap-3 w-full`,children:e.alternatives.map((e,r)=>{let i=n===r,a=e.image??String(e.value?.amount??e.value??r);return(0,H.jsx)(`button`,{onClick:()=>{i||f(e=>({...e,[t]:r}))},className:U(`w-full py-4 px-6 rounded-xl border-2 text-lg font-bold transition-all`,i?`border-primary bg-primary/10 text-primary shadow-sm`:`border-border bg-background text-foreground hover:border-primary/50`),children:a},r)})})})(h,s):(e=>{let t=e.metricType===G.Duration?`MM:SS`:`Value`;return(0,H.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:t,autoFocus:!0,className:`w-full text-2xl font-bold text-center py-3 bg-background border-2 border-border rounded-lg focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all tabular-nums`})})(h)})]})}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex items-center justify-between bg-muted/10`,children:[(0,H.jsxs)(`button`,{onClick:()=>{s>0&&(c(s-1),u(``))},disabled:s===0,className:`flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors`,children:[(0,H.jsx)(Tt,{className:`w-4 h-4`}),`Back`]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[h.kind===`value`&&(0,H.jsx)(`button`,{onClick:()=>{h.kind!==`choice`&&n(h),s<e.length-1&&(c(s+1),u(``))},className:`px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors`,children:`Skip`}),s<e.length-1&&(0,H.jsx)(`button`,{onClick:()=>{if(h.kind!==`choice`){if(!l)return;t(h,l),u(``)}s<e.length-1&&c(s+1)},disabled:h.kind===`value`&&!l,className:`flex items-center gap-2 px-6 py-2 bg-primary text-primary-foreground rounded-lg font-bold shadow-sm hover:brightness-110 disabled:opacity-50 disabled:grayscale transition-all`,children:`Next →`})]})]}),a===`pre-run`&&(0,H.jsx)(`div`,{className:`p-4 bg-background border-t border-border mt-auto`,children:(0,H.jsxs)(`button`,{onClick:()=>{h.kind===`value`&&l&&(t(h,l),u(``)),e.forEach((e,n)=>{e.kind===`choice`&&t(e,d[n]??0)}),r?.()},className:`w-full py-4 bg-primary text-primary-foreground rounded-xl font-bold text-lg shadow-lg hover:brightness-110 transition-all flex items-center justify-center gap-2`,children:[`Start Workout`,(0,H.jsx)(Vn,{className:`w-5 h-5`})]})})]}):null},HV=({execution:e,outputCount:t,createdAt:n,handleStart:r,handleStop:i,handleNext:a})=>{let{isCompact:o}=aB();return(0,H.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,children:[(0,H.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex ${o?`flex-col`:`flex-row`}`,children:[(0,H.jsx)(`div`,{className:`overflow-hidden bg-secondary/10 ${o?`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,H.jsx)($B,{})}),(0,H.jsx)(`div`,{className:`flex flex-col overflow-y-auto bg-background ${o?`order-1 min-h-[min(280px,100%)] flex-[3]`:`min-h-0 w-2/3`}`,children:(0,H.jsx)(oB,{children:(0,H.jsx)(SB,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,compact:o,enableDisplayStack:!0})})})]}),(0,H.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,H.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,H.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]})},UV=({block:e,view:t,onClose:n,onComplete:r,isExpanded:i=!1,onToggleExpand:a,autoStart:o,onRuntimeReady:s,onRunStarted:c,externalPause:l,externalStop:u})=>{let[d]=(0,V.useState)(()=>PV(e)),[f]=(0,V.useState)(()=>({statements:d.statements})),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(0),[y,b]=(0,V.useState)(null),[x,S]=(0,V.useState)(!1),[C,w]=(0,V.useState)(!1),T=(0,V.useRef)(!1),[E,D]=(0,V.useState)(!1),O=e.startLine+1,{overrides:k,setOverride:A}=kV(!0),{collectionItems:j}=BV([],k,f);(0,V.useEffect)(()=>{if(!x&&j.length>0)return;let e=FV(d);if(!e){D(!0);return}m(e),s?.(e);let n=e.subscribeToStack(n=>{if(!t)return;if(n.blocks.length===0){zT(t,[]);return}let r=n.blocks[0];r?.sourceIds?.length?zT(t,RV(e.script,r.sourceIds).map(e=>O+e)):zT(t,[])}),r=e.subscribeToOutput(e=>{(e.outputType===`segment`||e.outputType===`milestone`)&&(T.current||(T.current=!0,c?.()),v(e=>e+1))});return g(!0),()=>{n(),r(),t&&zT(t,[]),e.dispose()}},[x,j.length]);let M=Rf(p);(0,V.useEffect)(()=>{M.status!==`idle`&&CF().getState().setExecution(M)},[M.status,M.elapsedTime,M.stepCount,M.startTime]),(0,V.useEffect)(()=>{(o||C)&&h&&M.status===`idle`&&(M.start(),w(!1))},[o,C,h,M.status,M.start]),(0,V.useEffect)(()=>{M.status===`running`&&!T.current&&(T.current=!0,c?.())},[M.status,c]),(0,V.useEffect)(()=>{l&&M.status===`running`&&M.pause()},[l,M.status,M.pause]),(0,V.useEffect)(()=>{!u||M.status===`completed`||M.status!==`running`&&M.status!==`paused`&&!T.current||ee()},[u,M.status,M.stop]);let N=(0,V.useCallback)(t=>{if(!p)return;p.finalizeAnalytics();let n=IV(p.getOutputStatements(),{startTime:M.startTime??void 0,elapsedTime:M.elapsedTime,completed:t,now:p.nowProvider});r?.(e.id,n)},[e.id,M.elapsedTime,M.startTime,r,p]),[P,F]=(0,V.useState)(()=>JO());(0,V.useEffect)(()=>YO(F),[]),(0,V.useEffect)(()=>{if(!p||!P)return;let e=new rF(P),t=p.subscribeToStack(t=>e.onStackSnapshot(t)),n=p.subscribeToOutput(t=>e.onOutput(t));return()=>{t(),n(),e.dispose()}},[p,P]);let I=(0,V.useRef)(null);(0,V.useEffect)(()=>{I.current=null},[P]),(0,V.useEffect)(()=>{if(M.status===`completed`){I.current=null;return}let e=h&&M.status!==`completed`?`active`:null;if(!(!e||e===I.current||!P?.connected)){I.current=e;try{P.send({type:`rpc-workbench-update`,mode:e})}catch{}}},[h,M.status,P]),(0,V.useEffect)(()=>()=>{if(I.current===`active`)try{JO()?.send({type:`rpc-workbench-update`,mode:`idle`})}catch{}},[]),(0,V.useEffect)(()=>{if(M.status===`completed`&&!y&&(b(new Date),N(!0),P?.connected)){let e=LV(p?.getOutputStatements()||[]),t=EV({totalDurationMs:M.elapsedTime,segmentCount:e});try{P.send(t)}catch{}}},[M.status,M.elapsedTime,y,N,P,p]);let ee=(0,V.useCallback)(()=>{let e=p?p.stack.count===0:!1;M.stop(),p?.handle({name:`workout:stop`,timestamp:new Date,data:{}}),N(e)},[p,M,N]),te=(0,V.useCallback)(()=>{ee(),n()},[ee,n]),ne=(0,V.useCallback)(()=>{M.start(),i||a?.()},[M,i,a]),re=!x&&j.length>0,ie=()=>{S(!0),w(!0),i||a?.()},ae=(e,t)=>{zV(f,e,t)},oe=(0,V.useCallback)(()=>{p?.handle(new mf(void 0,p.nowProvider))},[p]);return(0,V.useEffect)(()=>{if(!p)return;let e=CF().getState();return e.setRuntime(p),e.setHandles({handleStart:ne,handlePause:()=>M.pause(),handleStop:te,handleNext:oe,handleStartWorkoutAction:()=>{}}),()=>{let e=CF().getState();e.runtime===p&&e.setRuntime(null)}},[p,M,ne,te,oe]),re?(0,H.jsx)(oB,{children:(0,H.jsx)(VV,{items:j,onSave:(e,t)=>{e.kind===`choice`?ae(e,t):A(e.blockKey,e.metricType,t)},onSkip:()=>{},onStart:ie,mode:`pre-run`})}):E?(0,H.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`Nothing to run`}),(0,H.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,H.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Close`})]}):!h||!p?(0,H.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Initializing…`}):(0,H.jsx)(oB,{children:(0,H.jsx)(Gf,{runtime:p,children:(0,H.jsx)(HV,{execution:M,outputCount:_,createdAt:y,handleStart:ne,handleStop:te,handleNext:oe})})})},WV=`wodwiki-telemetry`,GV=1,KV=`events`,qV=`wodwiki.telemetry.consent`,JV=class{events=new VD;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(qV)!==`denied`}get consent(){return this._consent}setConsent(e){if(this._consent!==e){this._consent=e;try{this.storage?.setItem(qV,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(KV,`readonly`).objectStore(KV).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(KV,`readwrite`);return a.objectStore(KV).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(WV,GV);return r.onupgradeneeded=()=>{let e=r.result;if(!e.objectStoreNames.contains(KV)){let t=e.createObjectStore(KV,{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))}},YV=UD?new JV({sink:e=>QD(`telemetry:${crypto.randomUUID()}`,{name:e.name,payload:e.payload,at:e.at}),load:async()=>(await ZD(`telemetry:`)).map(e=>e.value).sort((e,t)=>e.at-t.at)}):new JV,XV={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`};function ZV(){let e=(0,V.useSyncExternalStore)(e=>YV.subscribeConsent(e),()=>YV.consent);return{track:(0,V.useCallback)((e,t)=>YV.record(e,t),[]),consent:e,setConsent:(0,V.useCallback)(e=>YV.setConsent(e),[])}}var QV=[25,50,75,90];function $V(e,t=QV){let n=(0,V.useRef)(new Set);(0,V.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),YV.record(`scroll`,{percent_scrolled:r,page_path:e}))};return window.addEventListener(`scroll`,r,{passive:!0}),r(),()=>{window.removeEventListener(`scroll`,r)}},[e,t])}var eH=`playground`;function tH(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`entry`}function nH({persistence:e,pages:t,now:n=Date.now}){async function r(t,r,i,a){return(await e.createNote({id:C(),title:r,rawContent:i,targetDate:n(),type:`playground`,slug:t,sourceId:a??eH})).id}async function i(e,r,i,a){await t.savePage({id:e.id,slug:r,category:`playground`,name:i,content:a,sourceRevision:e.sourceRevision,updatedAt:n()})}return{async createPage(e,a){let o=ly(n()),s=az(`playground`,o),c=await t.getPage(s);return c?(await i(c,c.slug??s,c.name||o,e),o):(await r(s,o,e,a?.sourcePath),o)},async ensureEntry(e,a={}){if(!a.reuseKey){let t=ly(n()),i=az(`playground`,t);return{noteId:await r(i,t,e),routeId:i}}let o=tH(a.reuseKey),s=az(`playground`,o),c=await t.getPage(s);if(c&&c.type===`playground`)return await i(c,c.slug??s,c.name||o,e),{noteId:c.id,routeId:s};if(c){console.warn(`[playground-intake] reuse key '${o}' resolves to a non-playground note (${c.id}); minting a fresh entry instead of overwriting it.`);let t=`${o}-${ly(n())}`,i=az(`playground`,t);return{noteId:await r(i,a.title??t,e),routeId:i}}return{noteId:await r(s,a.title??o,e),routeId:s}},async snapshotEntry(e,i){let a=ly(n()),o=[tH(i.pageTitle),i.sectionTitle?tH(i.sectionTitle):null,a].filter(Boolean).join(`-`),s=az(`playground`,o);for(let e=2;await t.getPage(s);e+=1)s=az(`playground`,`${o}-${e}`);let c=[i.pageTitle,i.sectionTitle,a].filter(Boolean).join(` `);return{noteId:await r(s,c,e),routeId:s}},moveToJournal(t,n){return e.mutateNote({id:t},{metadata:{journalDate:n,type:`journal`,sourceId:null,slug:null}})}}}var rH=nH({persistence:Nj,pages:uz});function iH(e,t){return rH.createPage(e,t)}function aH(e,t){return rH.ensureEntry(e,t)}function oH(e,t){return rH.moveToJournal(e,t)}function sH({intake:e=rH,recorder:t=wV,persistence:n=Nj}={}){let[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(null),l=(0,V.useRef)(null),u=(0,V.useRef)(!1),d=(0,V.useRef)(null),f=(0,V.useRef)(null),p=(0,V.useRef)(null),m=(0,V.useCallback)(async(t,r,a)=>{if(f.current)throw Error(`A workout is already starting.`);if(l.current&&!u.current)throw Error(`A workout is already running.`);if(d.current)throw Error(`Previous workout results are not saved yet.`);let s=(async()=>{let s=await e.snapshotEntry(t,{pageTitle:a.pageTitle,sectionTitle:a.sectionTitle}),f=await n.getNote(s.noteId);if(!f.blocks||f.sourceRevision===void 0)throw Error(`The saved workout map is unavailable.`);let p=Object.values(f.blocks).filter(e=>e.kind===`wod`).sort((e,t)=>e.from-t.from),m=t.split(`
152
+ `)[0].trim().substring(0,50)||`Workout`,statementCount:e.scriptBlock?.statements?.length??0}))}}}var zV=`wod-wiki:userOutputOverrides`;function BV(e=!1){let t=wF(e=>e.userOutputOverrides),n=wF(e=>e.setUserOverride),r=wF(e=>e.clearUserOverride);return(0,V.useEffect)(()=>{if(e)try{let e=localStorage.getItem(zV);if(!e)return;let t=JSON.parse(e);for(let[e,r]of Object.entries(t))n(e,r.map(HV))}catch{}},[e,n]),(0,V.useEffect)(()=>{if(!e)return;if(t.size===0){localStorage.removeItem(zV);return}let n={};for(let[e,r]of t)n[e]=r.map(VV);localStorage.setItem(zV,JSON.stringify(n))},[t,e]),{overrides:t,setOverride:(0,V.useCallback)((e,r,i,a)=>{let o=(t.get(e)??K.empty(e)).filter(e=>e.type!==r),s={type:r,origin:`user`,value:i,image:a??String(i??``)};n(e,K.from(o,e).add(s))},[t,n]),removeOverride:(0,V.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,V.useCallback)(e=>{r(e)},[r]),clearAll:(0,V.useCallback)(()=>{for(let e of t.keys())r(e)},[t,r])}}function VV(e){return{type:e.type,value:e.value,image:e.image,origin:e.origin,sourceBlockKey:e.sourceBlockKey,timestamp:e.timestamp?.toISOString()}}function HV(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 UV=(typeof window<`u`?window.__wod_runtimeNowProvider?.():void 0)??Fc,WV=new $d(gf(),UV);function GV(e){return e.statements?.length?e:{...e,statements:Is().read(e.content,e.sport).statements}}function KV(e){return WV.createRuntime(GV(e))??null}function qV(e,t){return{startTime:t.startTime??t.now.nowMs(),endTime:t.now.nowMs(),duration:t.elapsedTime,completed:t.completed,logs:e.map(vj)}}function JV(e){return e.filter(e=>e.outputType===`segment`).length}function YV(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 XV(e,t,n){let r=e?.statements[t.statementIndex];r&&Zd(r,t.alternatives,n)}function ZV(e,t,n){let r=(0,V.useMemo)(()=>{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===G.Effort||e.type===G.Label),c=s?.value?.toString()||s?.image||`Exercise`;for(let t of i.metrics){if(t.type===G.Choice){let n=t;r.push({kind:`choice`,blockKey:a,exerciseLabel:c,alternatives:n.alternatives,selectedIndex:0,statementIndex:e});continue}(t.origin===`hinted`||t.image===`?`)&&(o?.some(e=>e.type===t.type&&e.origin===`user`)||r.push({kind:`value`,blockKey:a,exerciseLabel:c,metricType:t.type,hint:t.image||`?`,origin:`hinted`,statementIndex:e}))}}return r}for(let n of e){if(!n.metrics)continue;let e=n.name||`segment-${n.id}`,i=t.get(e);for(let t of n.metrics)if((t.origin===`hinted`||t.image===`?`)&&!i?.some(e=>e.type===t.type&&e.origin===`user`)){let i=n.metrics.find(e=>e.type===G.Effort||e.type===G.Label),a=i?.value?.toString()||i?.image||`Exercise`,o=e.match(/\[(\d+)\]/),s=e.match(/\[\d+\]\[(\d+)\]/);r.push({kind:`value`,blockKey:e,exerciseLabel:a,metricType:t.type,hint:t.image||`?`,origin:`hinted`,statementIndex:0,roundIndex:o?parseInt(o[1])+1:void 0,setIndex:s?parseInt(s[1])+1:void 0})}}return r},[e,t,n]);return{collectionItems:r,totalCount:r.length,isComplete:r.length===0}}var QV=({items:e,onSave:t,onSkip:n,onStart:r,onClose:i,mode:a,className:o})=>{let[s,c]=(0,V.useState)(0),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(()=>{let t={};return e.forEach((e,n)=>{e.kind===`choice`&&(t[n]=0)}),t}),[p,m]=(0,V.useState)(a===`pre-run`);if((0,V.useEffect)(()=>{s>=e.length&&e.length>0&&c(e.length-1)},[e.length,s]),e.length===0)return null;let h=e[s];return h?a===`post-run`&&!p?(0,H.jsxs)(`div`,{className:U(`bg-warning/10 border border-warning/30 rounded-xl p-3 flex items-center justify-between`,o),children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-warning text-sm font-medium`,children:[(0,H.jsx)(gt,{className:`w-4 h-4`}),(0,H.jsxs)(`span`,{children:[e.length,` uncollected metrics — fill in your actuals`]})]}),(0,H.jsx)(`button`,{onClick:()=>m(!0),className:`px-3 py-1 bg-warning text-warning-foreground rounded-lg text-xs font-bold uppercase tracking-label hover:brightness-110 transition-all`,children:`Fill In Now`})]}):(0,H.jsxs)(`div`,{className:U(`bg-card border border-border rounded-2xl shadow-xl overflow-hidden flex flex-col`,a===`pre-run`?`fixed inset-0 z-50 md:inset-10`:`relative`,o),children:[(0,H.jsx)(`div`,{className:`h-1 bg-muted`,children:(0,H.jsx)(`div`,{className:`h-full bg-primary transition-all duration-300`,style:{width:`${(s+1)/e.length*100}%`}})}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-b border-border flex items-center justify-between bg-muted/10`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:a===`pre-run`?`Set Your Targets`:`Fill in your actuals`}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground uppercase tracking-label`,children:[s+1,` of `,e.length,` metrics`]})]}),i&&(0,H.jsx)(`button`,{onClick:i,className:`p-2 hover:bg-muted rounded-full transition-colors`,children:(0,H.jsx)(Te,{className:`w-5 h-5 text-muted-foreground`})})]}),(0,H.jsx)(`div`,{className:`flex-1 p-8 flex flex-col items-center justify-center max-w-md mx-auto w-full`,children:(0,H.jsxs)(`div`,{className:`w-full space-y-6`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,H.jsxs)(`div`,{className:`px-3 py-1 rounded-pill bg-metric-effort/15 border border-metric-effort/40 text-metric-effort text-xs font-bold`,children:[`🏃 `,h.exerciseLabel]}),(h.setIndex||h.roundIndex)&&(0,H.jsxs)(`div`,{className:`text-[10px] font-bold tracking-label uppercase text-muted-foreground`,children:[h.roundIndex&&`Round ${h.roundIndex}`,h.roundIndex&&h.setIndex&&` · `,h.setIndex&&`Set ${h.setIndex}`]}),h.kind===`choice`&&(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground font-medium`,children:`Choose one:`})]}),(0,H.jsx)(`div`,{className:`space-y-4`,children:h.kind===`choice`?((e,t)=>{let n=d[t]??0;return(0,H.jsx)(`div`,{className:`flex flex-col gap-3 w-full`,children:e.alternatives.map((e,r)=>{let i=n===r,a=e.image??String(e.value?.amount??e.value??r);return(0,H.jsx)(`button`,{onClick:()=>{i||f(e=>({...e,[t]:r}))},className:U(`w-full py-4 px-6 rounded-xl border-2 text-lg font-bold transition-all`,i?`border-primary bg-primary/10 text-primary shadow-sm`:`border-border bg-background text-foreground hover:border-primary/50`),children:a},r)})})})(h,s):(e=>{let t=e.metricType===G.Duration?`MM:SS`:`Value`;return(0,H.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:t,autoFocus:!0,className:`w-full text-2xl font-bold text-center py-3 bg-background border-2 border-border rounded-lg focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all tabular-nums`})})(h)})]})}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex items-center justify-between bg-muted/10`,children:[(0,H.jsxs)(`button`,{onClick:()=>{s>0&&(c(s-1),u(``))},disabled:s===0,className:`flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors`,children:[(0,H.jsx)(Tt,{className:`w-4 h-4`}),`Back`]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[h.kind===`value`&&(0,H.jsx)(`button`,{onClick:()=>{h.kind!==`choice`&&n(h),s<e.length-1&&(c(s+1),u(``))},className:`px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors`,children:`Skip`}),s<e.length-1&&(0,H.jsx)(`button`,{onClick:()=>{if(h.kind!==`choice`){if(!l)return;t(h,l),u(``)}s<e.length-1&&c(s+1)},disabled:h.kind===`value`&&!l,className:`flex items-center gap-2 px-6 py-2 bg-primary text-primary-foreground rounded-lg font-bold shadow-sm hover:brightness-110 disabled:opacity-50 disabled:grayscale transition-all`,children:`Next →`})]})]}),a===`pre-run`&&(0,H.jsx)(`div`,{className:`p-4 bg-background border-t border-border mt-auto`,children:(0,H.jsxs)(`button`,{onClick:()=>{h.kind===`value`&&l&&(t(h,l),u(``)),e.forEach((e,n)=>{e.kind===`choice`&&t(e,d[n]??0)}),r?.()},className:`w-full py-4 bg-primary text-primary-foreground rounded-xl font-bold text-lg shadow-lg hover:brightness-110 transition-all flex items-center justify-center gap-2`,children:[`Start Workout`,(0,H.jsx)(Vn,{className:`w-5 h-5`})]})})]}):null},$V=({execution:e,outputCount:t,createdAt:n,handleStart:r,handleStop:i,handleNext:a})=>{let{isCompact:o,isFull:s}=aB();return s?(0,H.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,children:[(0,H.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex ${o?`flex-col`:`flex-row`}`,children:[(0,H.jsx)(`div`,{className:`overflow-hidden bg-secondary/10 ${o?`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,H.jsx)(uV,{})}),(0,H.jsx)(`div`,{className:`flex flex-col overflow-y-auto bg-background ${o?`order-1 min-h-[min(280px,100%)] flex-[3]`:`min-h-0 w-2/3`}`,children:(0,H.jsx)(oB,{children:(0,H.jsx)(SB,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,compact:o,enableDisplayStack:!0})})})]}),(0,H.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,H.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,H.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]}):(0,H.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,children:[(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:(0,H.jsx)(NB,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`})}),(0,H.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,H.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,H.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]})},eH=({block:e,view:t,onClose:n,onComplete:r,isExpanded:i=!1,onToggleExpand:a,autoStart:o,onRuntimeReady:s,onRunStarted:c,externalPause:l,externalStop:u})=>{let[d]=(0,V.useState)(()=>GV(e)),[f]=(0,V.useState)(()=>({statements:d.statements})),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(0),[y,b]=(0,V.useState)(null),[x,S]=(0,V.useState)(!1),[C,w]=(0,V.useState)(!1),T=(0,V.useRef)(!1),[E,D]=(0,V.useState)(!1),O=e.startLine+1,{overrides:k,setOverride:A}=BV(!0),{collectionItems:j}=ZV([],k,f);(0,V.useEffect)(()=>{if(!x&&j.length>0)return;let e=KV(d);if(!e){D(!0);return}m(e),s?.(e);let n=e.subscribeToStack(n=>{if(!t)return;if(n.blocks.length===0){zT(t,[]);return}let r=n.blocks[0];r?.sourceIds?.length?zT(t,YV(e.script,r.sourceIds).map(e=>O+e)):zT(t,[])}),r=e.subscribeToOutput(e=>{(e.outputType===`segment`||e.outputType===`milestone`)&&(T.current||(T.current=!0,c?.()),v(e=>e+1))});return g(!0),()=>{n(),r(),t&&zT(t,[]),e.dispose()}},[x,j.length]);let M=Rf(p);(0,V.useEffect)(()=>{M.status!==`idle`&&CF().getState().setExecution(M)},[M.status,M.elapsedTime,M.stepCount,M.startTime]),(0,V.useEffect)(()=>{(o||C)&&h&&M.status===`idle`&&(M.start(),w(!1))},[o,C,h,M.status,M.start]),(0,V.useEffect)(()=>{M.status===`running`&&!T.current&&(T.current=!0,c?.())},[M.status,c]),(0,V.useEffect)(()=>{l&&M.status===`running`&&M.pause()},[l,M.status,M.pause]),(0,V.useEffect)(()=>{!u||M.status===`completed`||M.status!==`running`&&M.status!==`paused`&&!T.current||ee()},[u,M.status,M.stop]);let N=(0,V.useCallback)(t=>{if(!p)return;p.finalizeAnalytics();let n=qV(p.getOutputStatements(),{startTime:M.startTime??void 0,elapsedTime:M.elapsedTime,completed:t,now:p.nowProvider});r?.(e.id,n)},[e.id,M.elapsedTime,M.startTime,r,p]),[P,F]=(0,V.useState)(()=>JO());(0,V.useEffect)(()=>YO(F),[]),(0,V.useEffect)(()=>{if(!p||!P)return;let e=new rF(P),t=p.subscribeToStack(t=>e.onStackSnapshot(t)),n=p.subscribeToOutput(t=>e.onOutput(t));return()=>{t(),n(),e.dispose()}},[p,P]);let I=(0,V.useRef)(null);(0,V.useEffect)(()=>{I.current=null},[P]),(0,V.useEffect)(()=>{if(M.status===`completed`){I.current=null;return}let e=h&&M.status!==`completed`?`active`:null;if(!(!e||e===I.current||!P?.connected)){I.current=e;try{P.send({type:`rpc-workbench-update`,mode:e})}catch{}}},[h,M.status,P]),(0,V.useEffect)(()=>()=>{if(I.current===`active`)try{JO()?.send({type:`rpc-workbench-update`,mode:`idle`})}catch{}},[]),(0,V.useEffect)(()=>{if(M.status===`completed`&&!y&&(b(new Date),N(!0),P?.connected)){let e=JV(p?.getOutputStatements()||[]),t=LV({totalDurationMs:M.elapsedTime,segmentCount:e});try{P.send(t)}catch{}}},[M.status,M.elapsedTime,y,N,P,p]);let ee=(0,V.useCallback)(()=>{let e=p?p.stack.count===0:!1;M.stop(),p?.handle({name:`workout:stop`,timestamp:new Date,data:{}}),N(e)},[p,M,N]),te=(0,V.useCallback)(()=>{ee(),n()},[ee,n]),ne=(0,V.useCallback)(()=>{M.start(),i||a?.()},[M,i,a]),re=!x&&j.length>0,ie=()=>{S(!0),w(!0),i||a?.()},ae=(e,t)=>{XV(f,e,t)},oe=(0,V.useCallback)(()=>{p?.handle(new mf(void 0,p.nowProvider))},[p]);return(0,V.useEffect)(()=>{if(!p)return;let e=CF().getState();return e.setRuntime(p),e.setHandles({handleStart:ne,handlePause:()=>M.pause(),handleStop:te,handleNext:oe,handleStartWorkoutAction:()=>{}}),()=>{let e=CF().getState();e.runtime===p&&e.setRuntime(null)}},[p,M,ne,te,oe]),re?(0,H.jsx)(oB,{children:(0,H.jsx)(QV,{items:j,onSave:(e,t)=>{e.kind===`choice`?ae(e,t):A(e.blockKey,e.metricType,t)},onSkip:()=>{},onStart:ie,mode:`pre-run`})}):E?(0,H.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`Nothing to run`}),(0,H.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,H.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Close`})]}):!h||!p?(0,H.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Initializing…`}):(0,H.jsx)(oB,{children:(0,H.jsx)(Gf,{runtime:p,children:(0,H.jsx)($V,{execution:M,outputCount:_,createdAt:y,handleStart:ne,handleStop:te,handleNext:oe})})})},tH=`wodwiki-telemetry`,nH=1,rH=`events`,iH=`wodwiki.telemetry.consent`,aH=class{events=new VD;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(iH)!==`denied`}get consent(){return this._consent}setConsent(e){if(this._consent!==e){this._consent=e;try{this.storage?.setItem(iH,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(rH,`readonly`).objectStore(rH).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(rH,`readwrite`);return a.objectStore(rH).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(tH,nH);return r.onupgradeneeded=()=>{let e=r.result;if(!e.objectStoreNames.contains(rH)){let t=e.createObjectStore(rH,{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))}},oH=UD?new aH({sink:e=>QD(`telemetry:${crypto.randomUUID()}`,{name:e.name,payload:e.payload,at:e.at}),load:async()=>(await ZD(`telemetry:`)).map(e=>e.value).sort((e,t)=>e.at-t.at)}):new aH,sH={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`};function cH(){let e=(0,V.useSyncExternalStore)(e=>oH.subscribeConsent(e),()=>oH.consent);return{track:(0,V.useCallback)((e,t)=>oH.record(e,t),[]),consent:e,setConsent:(0,V.useCallback)(e=>oH.setConsent(e),[])}}var lH=[25,50,75,90];function uH(e,t=lH){let n=(0,V.useRef)(new Set);(0,V.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),oH.record(`scroll`,{percent_scrolled:r,page_path:e}))};return window.addEventListener(`scroll`,r,{passive:!0}),r(),()=>{window.removeEventListener(`scroll`,r)}},[e,t])}var dH=`playground`;function fH(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`entry`}function pH({persistence:e,pages:t,now:n=Date.now}){async function r(t,r,i,a){return(await e.createNote({id:C(),title:r,rawContent:i,targetDate:n(),type:`playground`,slug:t,sourceId:a??dH})).id}async function i(e,r,i,a){await t.savePage({id:e.id,slug:r,category:`playground`,name:i,content:a,sourceRevision:e.sourceRevision,updatedAt:n()})}return{async createPage(e,a){let o=ly(n()),s=az(`playground`,o),c=await t.getPage(s);return c?(await i(c,c.slug??s,c.name||o,e),o):(await r(s,o,e,a?.sourcePath),o)},async ensureEntry(e,a={}){if(!a.reuseKey){let t=ly(n()),i=az(`playground`,t);return{noteId:await r(i,t,e),routeId:i}}let o=fH(a.reuseKey),s=az(`playground`,o),c=await t.getPage(s);if(c&&c.type===`playground`)return await i(c,c.slug??s,c.name||o,e),{noteId:c.id,routeId:s};if(c){console.warn(`[playground-intake] reuse key '${o}' resolves to a non-playground note (${c.id}); minting a fresh entry instead of overwriting it.`);let t=`${o}-${ly(n())}`,i=az(`playground`,t);return{noteId:await r(i,a.title??t,e),routeId:i}}return{noteId:await r(s,a.title??o,e),routeId:s}},async snapshotEntry(e,i){let a=ly(n()),o=[fH(i.pageTitle),i.sectionTitle?fH(i.sectionTitle):null,a].filter(Boolean).join(`-`),s=az(`playground`,o);for(let e=2;await t.getPage(s);e+=1)s=az(`playground`,`${o}-${e}`);let c=[i.pageTitle,i.sectionTitle,a].filter(Boolean).join(` `);return{noteId:await r(s,c,e),routeId:s}},moveToJournal(t,n){return e.mutateNote({id:t},{metadata:{journalDate:n,type:`journal`,sourceId:null,slug:null}})}}}var mH=pH({persistence:Nj,pages:uz});function hH(e,t){return mH.createPage(e,t)}function gH(e,t){return mH.ensureEntry(e,t)}function _H(e,t){return mH.moveToJournal(e,t)}function vH({intake:e=mH,recorder:t=FV,persistence:n=Nj}={}){let[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(null),l=(0,V.useRef)(null),u=(0,V.useRef)(!1),d=(0,V.useRef)(null),f=(0,V.useRef)(null),p=(0,V.useRef)(null),m=(0,V.useCallback)(async(t,r,a)=>{if(f.current)throw Error(`A workout is already starting.`);if(l.current&&!u.current)throw Error(`A workout is already running.`);if(d.current)throw Error(`Previous workout results are not saved yet.`);let s=(async()=>{let s=await e.snapshotEntry(t,{pageTitle:a.pageTitle,sectionTitle:a.sectionTitle}),f=await n.getNote(s.noteId);if(!f.blocks||f.sourceRevision===void 0)throw Error(`The saved workout map is unavailable.`);let p=Object.values(f.blocks).filter(e=>e.kind===`wod`).sort((e,t)=>e.from-t.from),m=t.split(`
141
153
  `).slice(0,r.startLine).join(`
142
- `).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=C(),_=await hF({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,V.useCallback)(async(e,n)=>{if(f.current)try{await f.current}catch{}let r=l.current;if(!r||u.current)return;if(p.current)return p.current;let i=d.current??{results:e,completed:n},a=(async()=>{d.current=i,c(d.current);try{await t.record({runBlock:r.block,blockId:r.block.id,noteId:r.noteId,resultId:r.resultId,data:i.results,createdAt:i.results.endTime??Date.now(),origin:`playground`})}finally{p.current===a&&(p.current=null)}u.current=!0,o(!0),d.current=null,c(null)})();return p.current=a,a},[t]),g=(0,V.useCallback)(async()=>{if(f.current)try{await f.current}catch{}p.current&&await p.current},[]);return{run:r,recorded:a,pendingResults:s,start:m,finalize:h,reset:(0,V.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,V.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 cH({title:e,getBlock:t,getContent:n}){let r=sH(),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(!1),u=(0,V.useRef)(!1),d=(0,V.useRef)(0),f=(0,V.useRef)(null),p=(0,V.useRef)(null);(0,V.useEffect)(()=>()=>{d.current+=1},[]);let m=(0,V.useCallback)(async e=>{let t=++d.current;try{await r.end(e?.results)}catch(e){t===d.current&&Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try stopping again.`,variant:`destructive`});return}t===d.current&&a(null)},[r]),h=(0,V.useCallback)(async(i,o)=>{let c=i??t();if(!c||u.current)return;u.current=!0;let l=++d.current;try{let t=await r.start(o??n(),c,{pageTitle:e??`Playground`});if(l!==d.current)return;s(null),a({kind:`timer`,block:t.block,results:null})}catch(e){l===d.current&&Z({title:`Could not save playground workout`,description:e instanceof Error?e.message:`The workout was not started. Please try again.`,variant:`destructive`})}finally{u.current=!1}},[r,e,t,n]),g=(0,V.useCallback)(async t=>{let i=d.current;try{await r.finalize(t,t.completed??!1)}catch(e){i===d.current&&Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try completing again.`,variant:`destructive`});return}if(i===d.current&&(s(t),a(null),f.current)){let t=f.current;f.current=null,l(!1);let i=p.current??{doc:n(),meta:{pageTitle:e??`Playground`}};p.current=null;try{await r.reset(i.doc,i.meta)}catch(e){Z({title:`Could not save reset snapshot`,description:e instanceof Error?e.message:`Your partial results are kept — try resetting again.`,variant:`destructive`})}finally{t()}}},[r,n,e]),_=(0,V.useCallback)(async t=>{let a=t??n(),o={pageTitle:e??`Playground`};try{if(r.run&&!r.recorded&&i){if(r.pendingResults)return await r.finalize(r.pendingResults.results,!1),await r.reset(a,o),!0;p.current={doc:a,meta:o},l(!0);let e=Promise.withResolvers();return f.current=e.resolve,await e.promise,!0}return await r.reset(a,o),!0}catch(e){return Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try resetting again.`,variant:`destructive`}),!1}},[r,n,e,i]);return{fullscreen:i,startRun:h,closeRun:m,completedResults:o,runState:(0,V.useMemo)(()=>({isReconnect:!1,onReconnect:()=>{},onRun:()=>{h()}}),[h]),handleWorkoutComplete:g,run:r.run,recorded:r.recorded,pendingResults:r.pendingResults,resetRequested:c,resetRun:_}}function lH({initialSource:e,initialSourceKey:t,contentOverride:n}){let[r,i]=(0,V.useState)(e),[a,o]=(0,V.useState)(1),[s,c]=(0,V.useState)(!1),[l,u]=(0,V.useState)(t),[d,f]=(0,V.useState)(e),p=(0,V.useRef)(e),m=(0,V.useRef)(null),h=(0,V.useRef)(new Map([[t,{original:e,current:e}]])),g=(0,V.useRef)(void 0),_=(0,V.useCallback)(()=>{requestAnimationFrame(()=>m.current?.focus())},[]),v=(0,V.useCallback)((e,t=e)=>{let n=h.current.get(t),r=n?.current??e,a=n?.original??e;if(n||h.current.set(t,{original:e,current:e}),u(t),f(a),_(),r===p.current){c(!1);return}clearTimeout(g.current),c(!0),o(0),g.current=setTimeout(()=>{p.current=r,i(r),o(1),c(!1),g.current=void 0,_()},180)},[_]),y=(0,V.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,V.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,V.useCallback)(e=>{m.current=e},[]),S=(0,V.useCallback)(()=>p.current,[]),C=(0,V.useRef)(void 0);return(0,V.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 uH=`wodwiki.quests.v1`;function dH(){try{let e=window.localStorage.getItem(uH);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 fH(e){try{window.localStorage.setItem(uH,JSON.stringify(e))}catch(e){console.error(`Failed to write quest progress:`,e)}}function pH(e){return dH()[e]??{}}function mH(e,t){let n=dH();n[e]=t,fH(n),window.dispatchEvent(new StorageEvent(`storage`,{key:uH}))}function hH(e,t){let n=pH(e);n[t]||(n[t]=!0,mH(e,n))}function gH(e,t){let n=pH(e);n[t]=!n[t],mH(e,n)}function _H(e,t){let[n,r]=(0,V.useState)(()=>pH(e));(0,V.useEffect)(()=>{let t=t=>{t.key===`wodwiki.quests.v1`&&r(pH(e))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)},[e]);let i=(0,V.useCallback)(t=>{hH(e,t),r(pH(e))},[e]),a=(0,V.useCallback)(t=>{gH(e,t),r(pH(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 vH({pageRoute:e,quests:t,completedResults:n,enabled:r=!0}){let{markComplete:i}=_H(e,t),a=(0,V.useRef)(new Set),o=t.map(e=>e.id).join(`|`);(0,V.useEffect)(()=>{a.current.clear()},[e,o]);let s=t.filter(e=>e.validation?.type===`workout-complete`);return(0,V.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 yH({pageRoute:e,quests:t,initialSource:n,currentSource:r,enabled:i=!0}){let{markComplete:a}=_H(e,t),o=t.some(e=>e.id===`qs-arrive`),s=t.some(e=>e.id===`qs-edit`),c=(0,V.useRef)(n);c.current=n;let l=(0,V.useRef)(r);l.current=r,(0,V.useEffect)(()=>{!i||!o||a(`qs-arrive`)},[i,o,a]),(0,V.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 bH(e){let[t,n]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(e).matches);return(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=e=>n(e.matches);return t.addEventListener?(t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)):(t.addListener(r),()=>t.removeListener(r))},[e]),t}var xH=(0,V.createContext)(null);function SH(){return(0,V.useContext)(xH)}function CH({title:e,subtitle:t,children:n,onReset:r,headerActions:i,className:a}){let o=SH();return(0,H.jsxs)(`div`,{className:U(`flex flex-col w-full h-full rounded-2xl lg:rounded-3xl border border-border shadow-2xl bg-background`,a),children:[(0,H.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,H.jsxs)(`div`,{className:`flex gap-1.5`,children:[r?(0,H.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,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-red-500/30`}),(0,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-amber-500/30`}),(0,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-emerald-500/30`})]}),(0,H.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[o?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`flex min-w-0 flex-1 justify-end`,children:o.status}),o.pips]}):(0,H.jsxs)(`span`,{className:`text-[9px] font-black text-muted-foreground uppercase tracking-[0.2em]`,children:[e,t&&(0,H.jsxs)(`span`,{className:`ml-1.5 font-medium normal-case tracking-normal text-muted-foreground/50`,children:[`· `,t]})]}),i,r&&(0,H.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,H.jsx)(Dn,{className:`size-3`}),`Reset`]})]})]}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden rounded-b-2xl lg:rounded-b-3xl`,children:n})]})}function wH(){return Ow.of(async()=>{let[e,t,n]=await Promise.all([X.getAllTagTypes(),X.getAllTags(),MH()]);return{types:e.map(e=>e.name),tags:t,efforts:n.efforts.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]})),equipment:n.equipment.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]}))}})}var TH=null;function EH(e,t,n){return Cz(e===`effort`?{id:t,kind:`effort`,sourceCatalog:`efforts`,sourceItem:t,title:n,date:null,effort:{slug:t,label:n}}:{id:t,kind:`equipment`,sourceCatalog:`equipment`,sourceItem:t,title:n,date:null})}function DH(e){return{resolve:(t,n)=>e.resolve(t,n),resolveEffort:t=>e.resolveEffort(t),resolveEquipment:t=>e.resolveEquipment(t),openHref:(e,t)=>EH(e,t,t),createHref:e=>e===`effort`?`/e/new?mode=create`:`/equipment/new?mode=create`}}function OH(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 kH(){let e=IE(),t=fk();if(!e.isInitialized()||!t.isInitialized())return null;let n={efforts:[...e.list()],equipment:[...t.list()]},r=OH(n);if(!TH||TH.signature!==r){let e=kc(n);TH={index:e,provider:DH(e),signature:r}}return TH.provider}function AH(){return kH(),TH?.index??null}function jH(){let e=Vr.fromClass(class{view;channel=null;onSeed=()=>{this.view.dispatch({effects:Aw.of(null)})};constructor(e){this.view=e,typeof BroadcastChannel<`u`&&(this.channel=new BroadcastChannel(z_),this.channel.onmessage=this.onSeed)}destroy(){this.channel?.close()}});return[kw.of(kH),e]}async function MH(){return{efforts:[...IE().list()],equipment:[...fk().list()]}}function NH(e){let{meta:t}=s_(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 PH(e,t){return{id:`reference:${e}`,label:e===`effort`?`Effort`:`Equipment`,search:async n=>{let r=await MH(),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 FH(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 IH(e){let t=FH(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 LH(e,t){let n=IH(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 RH(e,t){return t||(e.current||=new Mj,e.current)}function zH(e,t){return Er.domEventHandlers({drop:(n,r)=>{let i=n.dataTransfer?.files;if(!i||i.length===0)return!1;n.preventDefault();let a=r.posAtCoords({x:n.clientX,y:n.clientY});return a!==null&&(Array.from(i).forEach(async n=>{let i=C(),o=new FileReader;o.onload=async()=>{let s=o.result;if(e)try{await t.mutateNote(e,{attachments:{add:[{id:i,file:new File([s],n.name,{type:n.type})}]}})}catch(e){uF(`NoteEditor`,`Attachment persist skipped:`,e)}let c=`\n${n.type.startsWith(`image/`)?`!`:``}[${n.name}](${i})\n`;r.dispatch({changes:{from:a,insert:c},selection:{anchor:a+c.length}})},o.readAsArrayBuffer(n)}),!0)}})}function BH(e){let t=e?.split(`:`,1)[0];return t===`time`||t===`log`?Ls:null}var VH={[G.Duration]:`cm-metric-underline-duration`,[G.Rep]:`cm-metric-underline-rep`,[G.Effort]:`cm-metric-underline-effort`,[G.Rounds]:`cm-metric-underline-rounds`,[G.Distance]:`cm-metric-underline-distance`,[G.Resistance]:`cm-metric-underline-resistance`,[G.Action]:`cm-metric-underline-action`};function HH(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=AH();return r?Is({references:r,defaults:NH(t.doc.toString())}).read(n,e.sport).statements:Is().read(n,e.sport).statements}catch{return null}}function UH(e,t,n,r){let i=[];for(let a of e){if(a.contentFrom===void 0||a.contentTo===void 0)continue;let e=HH(a,r);if(e)for(let o of e){let e=a.startLine+(o.meta?.line??0),s=t===a&&e===n;for(let e of o.metrics){let t=VH[e.type===G.Choice?e.alternatives[0]?.type:e.type];if(!t)continue;let n=o.metricMeta?.get(e);if(!n)continue;let c=a.contentFrom+n.startOffset,l=a.contentFrom+n.endOffset;if(!Number.isFinite(c)||!Number.isFinite(l)||c>=l||c<0||l>r.doc.length)continue;let u=s?t:`${t}-dim`;i.push(Br.mark({class:u}).range(c,l))}}}return i.sort((e,t)=>e.from-t.from),Br.set(i)}function WH(e){let{sections:t}=e.field(ZC),{head:n}=e.selection.main,r=e.doc.lineAt(n).number,i=t.filter(e=>e.type===`time`||e.type===`log`),a=i.find(e=>r>=e.startLine+1&&r<e.endLine)??null,o=null,s=null,c=-1,l=null;if(a){let t=e.doc.line(r);l=HH(a,e);let i=r-a.startLine;c=l?.findIndex(e=>e.meta?.line===i&&e.metrics.some(t=>{let r=e.metricMeta.get(t),i=n-(a.contentFrom??0);return r&&i>=r.startOffset&&i<=r.endOffset}))??-1,c<0&&(c=l?.findIndex(e=>e.meta?.line===i)??-1),s=c>=0&&l?l[c]:null,o={sectionId:a.id,section:a,statement:s,statementIndex:c,cursorLine:r,docLine:r,lineFrom:t.from,lineTo:t.to,focusedMetric:null,focusedMetricIndex:-1,allStatements:l??[]}}let u=null,d=-1;if(a&&s&&a.contentFrom!==void 0)for(let e=0;e<s.metrics.length;e++){let t=s.metrics[e];if(t.type===G.Sound||t.type===G.System)continue;let r=s.metricMeta?.get(t);if(!r)continue;let i=a.contentFrom+r.startOffset,o=a.contentFrom+r.endOffset;if(n>=i&&n<=o){u=t,d=e;break}}o&&(o.focusedMetric=u,o.focusedMetricIndex=d);let f=UH(i,a,r,e);return{focus:o,decos:f}}var GH=si.define({create(e){return WH(e)},update(e,t){return t.effects.some(e=>e.is(Aw))?WH(t.state):!t.docChanged&&t.startState.selection.eq(t.state.selection)?e:WH(t.state)},provide:e=>Er.decorations.from(e,e=>e.decos)});function KH(e){try{return e.field(GH).focus}catch{return null}}function qH(e,t){let n=KH(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=HH(r,e.state)??[],s=[];for(let e of o)for(let t of e.metrics){if(t.type===G.Sound||t.type===G.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 JH=fi.high(yr.of([{key:`Ctrl-ArrowRight`,run:e=>qH(e,1)},{key:`Ctrl-ArrowLeft`,run:e=>qH(e,-1)}])),YH=[GH,Er.baseTheme({".cm-metric-underline-duration":{borderBottom:`2px solid hsl(var(--metric-time))`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep":{borderBottom:`2px solid hsl(var(--metric-rep))`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort":{borderBottom:`2px solid hsl(var(--metric-effort))`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds":{borderBottom:`2px solid hsl(var(--metric-rounds))`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance":{borderBottom:`2px solid hsl(var(--metric-distance))`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance":{borderBottom:`2px solid hsl(var(--metric-resistance))`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action":{borderBottom:`2px solid hsl(var(--metric-action))`,color:`hsl(var(--metric-action))`},".cm-metric-underline-duration-dim":{borderBottom:`2px solid hsl(var(--metric-time) / 0.2)`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep-dim":{borderBottom:`2px solid hsl(var(--metric-rep) / 0.2)`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort-dim":{borderBottom:`2px solid hsl(var(--metric-effort) / 0.2)`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds-dim":{borderBottom:`2px solid hsl(var(--metric-rounds) / 0.2)`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance-dim":{borderBottom:`2px solid hsl(var(--metric-distance) / 0.2)`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance-dim":{borderBottom:`2px solid hsl(var(--metric-resistance) / 0.2)`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action-dim":{borderBottom:`2px solid hsl(var(--metric-action) / 0.2)`,color:`hsl(var(--metric-action))`}}),JH],XH={frontmatter:120,code:60,widget:220,embed:180},ZH={frontmatter:280,code:140,widget:220,embed:280},QH=({view:e,widths:t,activeSectionId:n,renderSlot:r,cursorLine:i})=>{let a=(0,V.useRef)(null),o=(0,V.useRef)(null),[s,c]=(0,V.useState)(()=>e?.plugin(hw)?.rects??[]),[l,u]=(0,V.useState)(0),[d,f]=(0,V.useState)({left:0,right:0}),[p,m]=(0,V.useState)(()=>e?.plugin(hw)?.docVersion??0),[h,g]=(0,V.useState)(void 0),[_,v]=(0,V.useState)(void 0);(0,V.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,V.useEffect)(()=>{if(!e)return;let t=e.plugin(hw);if(t)return t.addListener((e,t)=>{c(e),m(t)})},[e]),(0,V.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,V.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(hw)?.rects??[]).filter(e=>{let n=t.get(e.sectionId);return n&&n.effectiveWidth>0});return!e||y.length===0?null:(0,H.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,H.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?ZH:XH)[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,H.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)})})})},$H={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 eU(e,t=$H){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 tU(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 nU={typeOverrides:{},sectionOverrides:{}};function rU(e,t,n=$H){let[r,i]=(0,V.useReducer)(tU,nU);return{widths:(0,V.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=eU({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,V.useCallback)((e,t)=>i({type:`SET_SECTION_WIDTH`,sectionId:e,width:t}),[]),setTypeWidth:(0,V.useCallback)((e,t)=>i({type:`SET_TYPE_WIDTH`,sectionType:e,width:t}),[]),clearSectionOverride:(0,V.useCallback)(e=>i({type:`CLEAR_SECTION_OVERRIDE`,sectionId:e}),[])}}function iU(e,t){let{sections:n}=e.state.field(ZC);return n.find(e=>e.id===t)}function aU(e,t){return t.contentFrom===void 0||t.contentTo===void 0?``:e.state.doc.sliceString(t.contentFrom,t.contentTo)}var oU=({props:e,isActive:t})=>{let n=e.source_url||e.website||``,r=e.title||e.label||`Link`,i=!t;return(0,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,H.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,H.jsx)(`span`,{className:`truncate text-xs font-medium`,children:r})]}),(0,H.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,H.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.`})]})},sU=({sectionId:e,section:t,view:n,isActive:r})=>{let i=(0,V.useMemo)(()=>t||iU(n,e),[n,e,t]),a=i?aU(n,i):``,o=(0,V.useMemo)(()=>Nb(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=Pb(t);if(e)return(0,H.jsx)(cU,{videoId:e,title:n,isActive:r})}return(0,H.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,H.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,H.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,H.jsx)(`span`,{className:`text-xs font-medium truncate`,children:n||`Untitled`})]}),(0,H.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mb-3`,children:t}),i.embed.isImage&&(0,H.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=Pb(c);if(e)return(0,H.jsx)(cU,{videoId:e,title:o.title||`YouTube Video`,isActive:r})}return o.source_url||o.website||s===`strava`?(0,H.jsx)(oU,{props:o,isActive:r}):null},cU=({videoId:e,title:t,isActive:n})=>(0,H.jsxs)(`div`,{className:U(`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,H.jsx)(`div`,{className:`relative flex-1 min-h-0`,children:(0,H.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,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground truncate border-t border-border bg-popover/90`,children:t})]});function lU(e,t,n,r){let[i,a]=(0,V.useState)([]),[o,s]=(0,V.useState)(!0),c=wF(e=>e.currentEntry),l=wF(e=>e.getNote),u=n??c?.extendedResults;return(0,V.useEffect)(()=>{if(!e||!t){a([]),s(!1);return}let n=!1;async function r(){if(Array.isArray(u)){let r=u.filter(n=>n.noteId===e&&n.blockId===t);if(r.length>0&&!n){a(r.sort((e,t)=>t.createdAt-e.createdAt)),s(!1);return}}if(typeof l!=`function`){n||(a([]),s(!1));return}try{let r=await l(e,{projection:`history-detail`,resultSelection:{mode:`all-for-section`,blockId:t}});n||a((r?.extendedResults??[]).sort((e,t)=>t.createdAt-e.createdAt))}catch{n||a([])}finally{n||s(!1)}}return r(),()=>{n=!0}},[e,t,u,l,r]),{results:i,loading:o}}function uU(e){let t=e.metrics?.find(e=>e.type===G.Elapsed);return t?.value!==void 0&&typeof t.value==`number`?t.value:0}function dU(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+uU(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 fU(e,t){return(0,V.useMemo)(()=>{if(t===void 0||e.length===0)return null;let n=dU(e,t);return n.resultCount>0?n:null},[e,t])}function pU(e,t){if(t){t(e.action,e);return}e.action.type===`call`&&e.action.handler()}var mU=({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,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:()=>pU(e,o),className:U(`flex items-center gap-2 transition-colors active:scale-95`,n===`xs`&&`gap-0 sm:gap-2`,l?U(`bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest`,f):U(`hover:bg-accent hover:text-accent-foreground text-muted-foreground font-medium`,u)),children:[s&&(0,H.jsx)(s,{className:U(`shrink-0`,l?`size-4 fill-current sm:size-3`:`size-4 sm:h-4 sm:w-4`)}),(0,H.jsx)(`span`,{className:a,children:e.label})]}),(0,H.jsx)(`div`,{className:U(`self-stretch`,l?`w-px bg-primary-foreground/20 my-2 sm:my-1`:`w-px bg-border/60`)}),(0,H.jsx)(`button`,{type:`button`,title:t.label,"aria-label":t.label,onClick:()=>pU(t,o),className:U(`flex items-center justify-center transition-colors active:scale-95`,l?U(`bg-primary text-primary-foreground hover:bg-primary/90`,p):U(`hover:bg-accent hover:text-accent-foreground text-muted-foreground`,d)),children:c?(0,H.jsx)(c,{className:U(`shrink-0`,l?`size-4 sm:size-3.5`:`size-4 sm:h-4 sm:w-4`)}):(0,H.jsx)(`span`,{className:`sr-only`,children:t.label})})]})},hU=new Fs;function gU(e,t){let{sections:n}=e.state.field(ZC);return n.find(e=>e.id===t)??null}function _U(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 hU.read(n,t.sport).statements}catch{return[]}}function vU(e,t,n){if(!e.length)return null;let r=n-t.startLine;return e.find(e=>e.meta?.line===r)??null}function yU(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 bU={[G.Duration]:{label:`Timer`,icon:`⏱`,color:`bg-metric-time/10 text-metric-time`},[G.Rep]:{label:`Reps`,icon:`✕`,color:`bg-metric-rep/10 text-metric-rep`},[G.Effort]:{label:`Exercise`,icon:`🏋`,color:`bg-metric-effort/10 text-metric-effort`},[G.Rounds]:{label:`Rounds`,icon:`↻`,color:`bg-metric-rounds/10 text-metric-rounds`},[G.Distance]:{label:`Distance`,icon:`📏`,color:`bg-metric-distance/10 text-metric-distance`},[G.Resistance]:{label:`Weight`,icon:`⚖`,color:`bg-metric-resistance/10 text-metric-resistance`},[G.Action]:{label:`Action`,icon:`⚡`,color:`bg-metric-action/10 text-metric-action`}};function xU(e){return e.metrics.filter(e=>e.type!==G.Sound&&e.type!==G.System).map(e=>{let t=bU[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 SU=({summary:e})=>{let t=e.entries.slice(0,3);return(0,H.jsxs)(`div`,{className:`px-3 py-2 border-t border-border/30 bg-muted/20`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1.5`,children:[(0,H.jsx)(S,{className:`h-3 w-3 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`text-[10px] font-semibold text-muted-foreground uppercase tracking-wider`,children:`History`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-muted-foreground`,children:[e.totalHits,`× across `,e.resultCount,` run`,e.resultCount===1?``:`s`]})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t.map(e=>(0,H.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,H.jsx)(`span`,{className:`font-mono font-medium text-foreground`,children:yU(e.elapsedMs)}),e.hitCount>1&&(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[`×`,e.hitCount]}),(0,H.jsx)(`span`,{className:`text-muted-foreground/60`,children:HP(new Date(e.createdAt))})]},e.createdAt)),e.entries.length>3&&(0,H.jsxs)(`span`,{className:`text-[10px] text-muted-foreground self-center`,children:[`+`,e.entries.length-3,` more`]})]})]})};function CU(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 wU(e){return function({className:t}){return V.isValidElement(e)?V.cloneElement(e,{className:U(e.props.className,t)}):(0,H.jsx)(`span`,{className:U(`flex items-center`,t),children:e})}}var TU=({cmd:e,block:t})=>{let[n,r]=(0,V.useState)(!1),i=(0,V.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),a=(0,V.useMemo)(()=>wU(e.icon),[e.icon]),o=(0,V.useMemo)(()=>wU(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),s=(0,V.useMemo)(()=>({id:e.id,label:e.label,icon:a,action:{type:`call`,handler:()=>e.onClick(t)}}),[e,t,a]),c=(0,V.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:o,action:{type:`call`,handler:i}}),[e.id,o,i]),l=(0,V.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);return e.onSplitClick?(0,H.jsx)(`div`,{onClick:l,onMouseDown:l,onPointerDown:l,children:(0,H.jsx)(mU,{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,H.jsxs)(W,{variant:e.primary?`default`:`secondary`,className:U(`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`),title:e.label,"aria-label":e.label,onClick:n=>{l(n),e.onClick(t)},onMouseDown:l,onPointerDown:l,children:[(0,H.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:e.icon}),(0,H.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})},EU=({commands:e,section:t,view:n,compact:r})=>{if(!e.length)return null;let i=CU(n,t);return r?(0,H.jsx)(`div`,{className:`flex flex-row items-center gap-1 p-0 sm:p-1.5`,children:e.map(e=>(0,H.jsx)(TU,{cmd:e,block:i},e.id))}):(0,H.jsx)(`div`,{className:`flex items-center gap-1.5 p-2 border-t border-border/50 flex-wrap`,children:e.map(e=>(0,H.jsx)(TU,{cmd:e,block:i},e.id))})},DU=({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,V.useMemo)(()=>gU(n,t),[n,t,u]),{results:h}=lU(p,t,f,m?.contentId),g=(0,V.useMemo)(()=>m?_U(n,m):[],[n,m?.id,u]),_=V.useRef(null),v=m&&a!==void 0&&a>=m.startLine&&a<=m.endLine;v&&a!==void 0&&(_.current=a);let y=v?a:s?_.current??null:null,b=r?i:y??i,x=!(m&&(b===m.startLine||b===m.endLine))&&(r||y!==null),S=(0,V.useMemo)(()=>m&&x?vU(g,m,b):null,[m,b,x,g]),C=(0,V.useMemo)(()=>S?g.filter(e=>e.meta?.line===S.meta.line).flatMap(xU):[],[S,g]),w=fU(h,S?.meta?.line);if(!m)return null;let T=S?.meta?.raw??``,E=b-m.startLine,D=typeof window<`u`&&window.matchMedia(`(max-width: 639px)`).matches?44:28,O;if(c!==void 0){let e=c-l.top-100,t=o+D+4,n=l.height-200;O=Math.max(t,Math.min(e,Math.max(t,n)))}else O=o+D+4;return(0,H.jsxs)(`div`,{className:`relative w-full h-full`,style:{pointerEvents:`none`},children:[(0,H.jsx)(`div`,{className:`absolute inset-x-0 flex items-center justify-end gap-1 px-2 pointer-events-auto
143
- bg-background/70 backdrop-blur-sm border-l border-b border-border/40 rounded-bl-md`,style:{top:o,height:D},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h.length>0&&(0,H.jsxs)(H.Fragment,{children:[(0,H.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,H.jsx)(ee,{className:`h-3 w-3`}),(0,H.jsx)(`span`,{children:h.length})]}),(0,H.jsx)(`div`,{className:`h-3 w-[1px] bg-border/40 mx-0.5`})]}),(0,H.jsx)(EU,{commands:d,section:m,view:n,compact:!0})]})}),x&&(0,H.jsxs)(`div`,{className:`absolute inset-x-0 flex flex-col bg-popover/95 backdrop-blur-md
144
- border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:O,maxHeight:200},children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,H.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,H.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,H.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,E]}),(0,H.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,H.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:T,children:T||(0,H.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,H.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:C.length>0?(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:C.map((e,t)=>(0,H.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,H.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,H.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,H.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),w&&(0,H.jsx)(SU,{summary:w}),(0,H.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,H.jsx)(EU,{commands:d,section:m,view:n})})]})]})},OU=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,V.useMemo)(()=>{let t=n.state.field(ZC).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,H.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,H.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,H.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,H.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,H.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})};function kU(e,t,n,r,i){switch(t.type){case`fixed-field`:return AU(e,t);case`metric-type`:return jU(e,t);case`derived`:return MU(e,t,n,r,i);case`fallback`:return NU(e,t,n,r,i);default:return}}function AU(e,t){return e[t.field]}function jU(e,t){return e.cells.get(t.metricType)}function MU(e,t,n,r,i){let a=new Map;if(t.dependencies&&r)for(let o of t.dependencies){if(i?.includes(o))throw Error(`Circular dependency detected in column '${o}': ${(i??[]).join(` -> `)} -> ${o}`);let t=r.get(o);if(t){let s=kU(e,t.source,n,r,[...i??[],o]);a.set(o,s)}}let o={...n,allRows:n?.allRows??[e],rowIndex:n?.rowIndex??0,columnDef:n?.columnDef??{id:`unknown`,label:``,source:t,format:{type:`text`}},dependencies:a,...t.context};return t.compute(e,o)}function NU(e,t,n,r,i){return PU(e,t,n,r,i)}function PU(e,t,n,r,i){if(!(!t.sources||t.sources.length===0))switch(t.semantics){case`first-present`:return FU(e,t.sources,n,r,i);case`all-present-joined`:return IU(e,t.sources,t.joinString,n,r,i);case`all-present-combined`:return LU(e,t.sources,n,r,i);default:return}}function FU(e,t,n,r,i){for(let a of t){let t=kU(e,a,n,r,i);if(t!=null)return t}}function IU(e,t,n,r,i,a){let o=[];for(let n of t){let t=kU(e,n,r,i,a);if(t==null)return;o.push(t)}let s=n??` `;return o.map(e=>zU(e)).join(s)}function LU(e,t,n,r,i){let a=[];for(let o of t){let t=kU(e,o,n,r,i);if(t==null)return;a.push(t)}return a}function RU(e){if(e==null)return``;let t=Array.isArray(e)?e:e instanceof K?e.toArray():[];if(t.length===0)return``;let n=t[0];if(typeof n==`object`&&n){if(`image`in n&&typeof n.image==`string`)return n.image;if(`value`in n&&n.value!==void 0)return String(n.value)}return String(n)}function zU(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`&&`metrics`in e){let t=RU(e.metrics);if(t.length>0)return t}return String(e)}function BU(e,t,n,r){if(!t.sort)return``;let i=kU(e,t.source,n,r);return(t.sort.type===`custom`?typeof i==`number`||typeof i==`string`?i:String(i??``):t.sort.extractor(i))??``}function VU(e,t){if(typeof e==`number`&&typeof t==`number`)return Number.isNaN(e)&&Number.isNaN(t)?0:Number.isNaN(e)?1:Number.isNaN(t)?-1:e-t;let n=String(e??``),r=String(t??``),i=parseFloat(n),a=parseFloat(r);return!Number.isNaN(i)&&!Number.isNaN(a)&&n===String(i)&&r===String(a)?i-a:n.localeCompare(r)}function HU(e,t,n,r){if(!t.graph)return;let i=kU(e,t.source,n,r);return t.graph.extractor(i)}function UU(e,t,n,r){if(!t.filter)return``;let i=kU(e,t.source,n,r);return t.filter.extractor(i)??``}function WU(e,t,n,r,i){if(!n||n.trim().length===0||!t.filter)return!0;let a=UU(e,t,r,i),o=t.filter.caseInsensitive===!1?n.trim():n.trim().toLowerCase(),s=t.filter.caseInsensitive===!1?a:a.toLowerCase();return t.filter.matcher?t.filter.matcher(s,o):s.includes(o)}var GU=({metric:e})=>{let t=e.origin===`hinted`||e.image===`?`,n=(0,V.useMemo)(()=>CB(_o.present(e,`review-grid-cell`)),[e]);return(0,H.jsxs)(`span`,{className:[`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium border transition-all`,t?`bg-warning/10 border-warning/40 text-warning animate-pulse-opacity`:`${n.colorClasses} ${n.originClasses}`].join(` `),title:t?`Missing value - click to fill`:n.tooltip,children:[t&&(0,H.jsx)(`span`,{className:`mr-0.5 text-[10px]`,children:`◉`}),n.label,n.userEntered&&!t&&(0,H.jsx)(`span`,{className:`text-[10px] opacity-70 ml-0.5`,children:`👤`})]})},KU=({columnDef:e,row:t,allRows:n,rowIndex:r,indent:i=0,onDoubleClick:a,className:o,style:s,definitionMap:c})=>{let l=(0,V.useRef)(null),u=(0,V.useMemo)(()=>{if(!(!n||r===void 0))return{allRows:n,rowIndex:r,columnDef:e,dependencies:new Map}},[n,r,e]),d=(0,V.useMemo)(()=>kU(t,e.source,u,c),[t,e.source,u,c]),f=e.source.type===`metric-type`,p=(0,V.useCallback)(n=>{if(n.stopPropagation(),f&&a&&l.current){let n=l.current.getBoundingClientRect();a(t.sourceBlockKey,e.source.metricType,n)}},[f,e.source,t.sourceBlockKey,a]),m=(0,V.useMemo)(()=>qU(d,e.format,i,t),[d,e.format,i,t]);return(0,H.jsx)(`td`,{ref:l,className:U(`py-1 px-2`,f&&`cursor-cell`,o),style:s,onDoubleClick:p,children:m})};function qU(e,t,n,r){if(e==null)return(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[oW(n),(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]});switch(t.type){case`text`:return JU(e,t,n);case`time`:return YU(e,t);case`number`:return XU(e,t);case`badge`:return ZU(e,t);case`pill`:return QU(e,t);case`combined`:return eW(e,t,n);case`custom`:return nW(e,t,r);default:return iW(e,n)}}function JU(e,t,n){let r=t.transform?t.transform(e):sW(e);return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1`,t.className),children:[oW(n),r]})}function YU(e,t){let n=cW(e);if(n==null||!Number.isFinite(n))return(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r;switch(t.style){case`long`:r=Zz(n);break;case`precise`:r=`${n.toFixed(2)}s`;break;default:r=Xz(n)}return t.transform&&(r=t.transform(r)),(0,H.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:r})}function XU(e,t){let n=cW(e);if(n==null||!Number.isFinite(n))return(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r=t.decimals??0,i=n.toFixed(r)+(t.unit??``);return t.transform?(0,H.jsx)(`span`,{children:t.transform(i)}):(0,H.jsx)(`span`,{children:i})}function ZU(e,t){let n=t.styleResolver(e),r=t.textResolver(e);return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium`,n.className),title:n.title,children:[n.icon&&(0,H.jsx)(`span`,{className:`mr-0.5`,children:n.icon}),r]})}function QU(e,t){let n=t.transform?t.transform(e):sW(e),r=t.backgroundColor??`bg-muted`,i=t.borderRadius??`rounded`;return(0,H.jsx)(`span`,{className:U(`inline-block px-1.5 py-0.5 text-xs font-medium`,r,i),children:n})}var $U={primary:`text-sm font-semibold text-foreground`,secondary:`text-xs text-muted-foreground`,tertiary:`text-[11px] text-muted-foreground opacity-80`};function eW(e,t,n,r){let[i,a,o]=Array.isArray(e)?e:[e],s=i===void 0?null:tW(i,t.primaryFormat??{type:`text`},r,`primary`),c=a===void 0?null:tW(a,t.secondaryFormat??{type:`text`},r,`secondary`),l=o===void 0?null:tW(o,t.tertiaryFormat??{type:`text`},r,`tertiary`),u=t.layout===`horizontal`;return(0,H.jsxs)(`div`,{className:U(`inline-flex`,u?`flex-row items-center gap-1`:`flex-col items-start gap-0.5`,t.containerClassName),children:[oW(n),s,c&&(0,H.jsxs)(H.Fragment,{children:[u&&t.separator&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),c]}),l&&(0,H.jsxs)(H.Fragment,{children:[u&&t.separator&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),l]})]})}function tW(e,t,n,r){let i=qU(e,t,0,n);return r?(0,H.jsx)(`span`,{className:U(`inline-flex items-center`,$U[r]),children:i}):i}function nW(e,t,n){let r=n?{...t.context,row:n}:t.context;return t.render(e,r)}function rW(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function iW(e,t){return e?.metrics?aW(e,t):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[oW(t),sW(e)]})}function aW(e,t){let n=rW(e);return n.length===0?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[oW(t),(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]}):(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1 items-center`,children:[oW(t),n.map((e,t)=>(0,H.jsx)(GU,{metric:e},t))]})}function oW(e){return e<=0?null:(0,H.jsx)(`div`,{className:`flex-shrink-0 mr-1 border-l-2 border-muted h-4`,style:{width:`${e*1.25}rem`,marginLeft:`2px`}})}function sW(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);let t=rW(e);if(t.length>0){let e=t[0];if(e?.image)return e.image;if(e?.value!==void 0)return String(e.value)}return String(e)}function cW(e){if(e==null)return;if(typeof e==`number`)return e;if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}let t=rW(e);if(t.length>0&&typeof t[0]?.value==`number`)return t[0].value}var lW=e=>e;function uW(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function dW(e){let t=uW(e);if(t.length===0)return;let n=t[0];return typeof n?.value==`number`?n.value:n?.image?n.image:String(n?.value??``)}function fW(e){let t=uW(e);for(let e of t)if(typeof e?.value==`number`)return e.value}function pW(e){return uW(e).map(e=>e.image??String(e.value??``)).join(`, `)}function mW(e){return e==null?``:Array.isArray(e)?e.map(e=>mW(e)).filter(Boolean).join(` — `):typeof e==`string`?e:typeof e==`number`?String(e):pW(e)}function hW(e){switch(e){case G.Duration:case G.Rep:case G.Distance:case G.Rounds:case G.Resistance:case G.Increment:case G.Metric:case G.Volume:case G.Intensity:case G.Load:case G.Work:case G.CurrentRound:case G.Calculated:return!0;default:return!1}}function gW(e){switch(e){case G.Duration:return`s`;case G.Rep:return`reps`;case G.Distance:return`m`;case G.Rounds:return`rounds`;case G.Resistance:return`kg`;case G.Increment:return`Δ`;case G.Calculated:case G.Custom:return``;default:return``}}function _W(e,t){let n=po(e),r=gB(e)??void 0,i=t?.graphable??hW(e);return{id:e,label:n,icon:r,source:{type:`metric-type`,metricType:e},format:{type:`custom`,render:e=>aW(e,0)},sort:hW(e)?{type:`numeric`,extractor:e=>fW(e)}:{type:`text`,extractor:e=>{let t=dW(e);return t===void 0?void 0:String(t)}},graph:i?{extractor:e=>fW(e),axisLabel:n,unit:gW(e)}:void 0,filter:{extractor:e=>pW(e),caseInsensitive:!0},meta:{defaultVisible:t?.defaultVisible??!0,debugOnly:t?.debugOnly,tags:[e]}}}function vW(e){switch(e){case`segment`:return`bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-200`;case`milestone`:return`bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-200`;case`system`:return`bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400`;case`event`:return`bg-purple-100 text-purple-800 dark:bg-purple-900/50 dark:text-purple-200`;case`group`:return`bg-indigo-100 text-indigo-800 dark:bg-indigo-900/50 dark:text-indigo-200`;case`load`:return`bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-200`;case`compiler`:return`bg-pink-100 text-pink-800 dark:bg-pink-900/50 dark:text-pink-200`;default:return`bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300`}}function yW(e,t){if(!e||e.length===0)return``;let n=e=>Xz(e);if(t===0)return n(e[0].started);let r=n(e[0].started),i=e[e.length-1];if(i.ended===void 0)return r;let a=n(i.ended);return r===a?r:`${r} — ${a}`}function bW(e,t=!0){if(e===void 0||e===0)return``;let n=new Date(e),r=n.getHours().toString().padStart(2,`0`),i=n.getMinutes().toString().padStart(2,`0`),a=n.getSeconds().toString().padStart(2,`0`);return t?`${r}:${i}:${a}.${n.getMilliseconds().toString().padStart(3,`0`)}`:`${r}:${i}:${a}`}function xW({value:e}){let t=e.match(/^(-?)(\d+)(:\d{2})(?::\d{2})?(\.\d+)?$/);if(!t)return(0,H.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:e});let[,n,r,i,a,o]=t,s=i.slice(1);return(0,H.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap inline-flex items-baseline`,children:[n&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:n}),(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:r}),(0,H.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`:`,s]}),a&&(0,H.jsx)(`span`,{className:`text-muted-foreground/40`,children:a}),o&&(0,H.jsx)(`span`,{className:`text-muted-foreground/30 text-[10px]`,children:o})]})}function SW({elapsed:e,duration:t}){let n=Xz(e);return(0,H.jsxs)(`span`,{className:`inline-flex items-baseline gap-0.5`,children:[(0,H.jsx)(xW,{value:n}),t!==void 0&&t>0&&t!==e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-muted-foreground/40 mx-0.5`,children:`/`}),(0,H.jsx)(`span`,{className:`opacity-60`,children:(0,H.jsx)(xW,{value:Xz(t)})})]})]})}var CW={id:`#`,label:`#`,source:{type:`derived`,compute:e=>({index:e.index,outputType:e.outputType,sourceBlockKey:e.sourceBlockKey})},format:{type:`custom`,render:e=>{let{index:t,outputType:n,sourceBlockKey:r}=e??{};return(0,H.jsx)(`span`,{className:U(`font-mono text-[11px] w-8 text-right inline-block`,vW(n)),title:`Type: ${n}\nBlock: ${r}`,children:t})}},sort:{type:`numeric`,extractor:e=>lW(e)?.index||0},meta:{tags:[`layout`],defaultVisible:!0,width:`40px`,resizable:!1}},wW={id:`timestamp`,label:`Timestamp`,source:{type:`fixed-field`,field:`absoluteStartTime`},format:{type:`custom`,render:(e,t)=>{let n=e,r=lW(t)?.hideMs!==!1;return(0,H.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-24 whitespace-nowrap`,children:bW(n,r)})},context:{hideMs:!1}},sort:{type:`numeric`,extractor:e=>lW(e)?.absoluteStartTime??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},TW={id:`spans`,label:`Time`,source:{type:`derived`,compute:e=>({spans:e.spans,duration:e.duration})},format:{type:`custom`,render:e=>{let{spans:t,duration:n}=e??{};return(0,H.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-40 whitespace-nowrap`,children:yW(t,n)})}},sort:{type:`numeric`,extractor:e=>(lW(e)?.spans)?.[0]?.started??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},EW={id:`timeSpan`,label:`Time`,source:{type:`derived`,compute:e=>({timestamp:e.absoluteStartTime,elapsed:e.elapsed,duration:e.duration})},format:{type:`custom`,render:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{};return n===void 0?(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`}):(0,H.jsxs)(`div`,{className:`flex flex-col items-start gap-0 leading-tight`,children:[t!==void 0&&t>0&&(0,H.jsx)(`span`,{className:`text-muted-foreground/50 font-mono text-[10px] whitespace-nowrap`,children:bW(t,!1)}),(0,H.jsx)(SW,{elapsed:n,duration:r})]})}},sort:{type:`numeric`,extractor:e=>lW(e)?.elapsed??0},graph:{extractor:e=>lW(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`},filter:{extractor:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{},i=[];return t!==void 0&&t>0&&i.push(bW(t,!1)),n!==void 0&&i.push(Xz(n)),r!==void 0&&r>0&&r!==n&&i.push(Xz(r)),i.join(` `)},caseInsensitive:!0},meta:{tags:[`timing`,`compound`],defaultVisible:!0,width:`100px`,subsumes:[`duration`,`elapsedTotal`]}},DW={id:`blockKey`,label:`Block`,source:{type:`fixed-field`,field:`sourceBlockKey`},format:{type:`text`,className:`truncate max-w-[160px] text-sm`},sort:{type:`text`,extractor:e=>lW(e)?.sourceBlockKey??``},filter:{extractor:e=>lW(e)?.sourceBlockKey??``,caseInsensitive:!0},meta:{tags:[`layout`],defaultVisible:!1}},OW={id:`outputType`,label:`Type`,source:{type:`fixed-field`,field:`outputType`},format:{type:`custom`,render:e=>{let t=String(e??``);return(0,H.jsx)(`span`,{className:U(`text-xs px-1.5 py-0.5 rounded font-medium`,vW(t)),children:t})}},sort:{type:`text`,extractor:e=>lW(e)?.outputType??``},filter:{extractor:e=>lW(e)?.outputType??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1}},kW={id:`stackLevel`,label:`Depth`,source:{type:`fixed-field`,field:`stackLevel`},format:{type:`text`,className:`text-muted-foreground font-mono text-xs text-center w-12`},sort:{type:`numeric`,extractor:e=>lW(e)?.stackLevel??0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},AW={id:`elapsedTotal`,label:`Elapsed`,source:{type:`derived`,compute:e=>({elapsed:e.elapsed,total:e.total})},format:{type:`custom`,render:e=>{let{elapsed:t,total:n}=e??{};if(t===void 0||n===void 0)return``;let r=t===n?Xz(t):`${Xz(t)} / ${Xz(n)}`;return(0,H.jsx)(`span`,{className:`text-foreground font-mono text-xs text-right w-32 whitespace-nowrap`,children:r})}},sort:{type:`numeric`,extractor:e=>lW(e)?.elapsed??0},graph:{extractor:e=>lW(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`,color:`#14b8a6`},meta:{tags:[`timing`],defaultVisible:!1}},jW={id:`completionReason`,label:`Reason`,source:{type:`fixed-field`,field:`completionReason`},format:{type:`text`,className:`text-muted-foreground text-xs truncate max-w-[120px]`},sort:{type:`text`,extractor:e=>lW(e)?.completionReason??``},filter:{extractor:e=>lW(e)?.completionReason??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},MW=_W(G.Effort,{defaultVisible:!1}),NW=_W(G.Duration,{debugOnly:!0}),PW=_W(G.Rep),FW=_W(G.Rounds,{defaultVisible:!1}),IW=_W(G.Distance),LW=_W(G.Resistance),RW=_W(G.Action),zW=_W(G.Increment),BW=_W(G.Metric),VW=_W(G.Calculated),HW=_W(G.Custom,{defaultVisible:!1}),UW=_W(G.Group,{defaultVisible:!1}),WW=_W(G.System,{defaultVisible:!1}),GW=_W(G.Label,{defaultVisible:!1}),KW=_W(G.Text),qW=_W(G.CurrentRound,{defaultVisible:!1}),JW=_W(G.Volume),YW=_W(G.Intensity),XW=_W(G.Load),ZW=_W(G.Work),QW=[CW,EW,wW,TW,DW,OW,kW,AW,jW,{id:`exercise`,label:`Exercise`,icon:gB(G.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`fallback`,semantics:`all-present-combined`,sources:[{type:`metric-type`,metricType:G.Effort},{type:`metric-type`,metricType:G.Text}]},{type:`metric-type`,metricType:G.Text},{type:`metric-type`,metricType:G.Label},{type:`metric-type`,metricType:G.Effort}]},format:{type:`combined`,layout:`vertical`,primaryFormat:{type:`text`,className:`font-medium text-foreground`},secondaryFormat:{type:`text`,className:`text-muted-foreground text-xs`},containerClassName:`items-start`},sort:{type:`text`,extractor:e=>mW(e)},filter:{extractor:e=>mW(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`grouping`,`fallback`,`descriptor`],subsumes:[`effort`,`text`,`label`]}},{id:`descriptor`,label:`Descriptor`,icon:gB(G.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:G.Effort},{type:`metric-type`,metricType:G.Label},{type:`metric-type`,metricType:G.Rounds},{type:`metric-type`,metricType:G.CurrentRound}]},format:{type:`custom`,render:e=>aW(e,0)},sort:{type:`text`,extractor:e=>mW(e)},filter:{extractor:e=>mW(e),caseInsensitive:!0},meta:{defaultVisible:!0,subsumes:[`effort`,`label`,`rounds`,`current-round`]}},MW,KW,GW,NW,{id:`pace`,label:`Pace`,icon:`⏱️`,source:{type:`derived`,dependencies:[`distance`,`duration`],compute:(e,t)=>{let n=fW(t.dependencies.get(`distance`)),r=fW(t.dependencies.get(`duration`));if(!(!n||!r))return n/r}},format:{type:`custom`,render:e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`});let t=1e3/e;return(0,H.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:[Xz(t),`/km`]})}},sort:{type:`numeric`,extractor:e=>typeof e==`number`?e:void 0},graph:{extractor:e=>typeof e==`number`?e:void 0,axisLabel:`Pace`,unit:`m/s`},filter:{extractor:e=>typeof e!=`number`||!Number.isFinite(e)||e<=0?``:`${Xz(1e3/e)}/km`,caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`endurance`,`derived`]}},PW,FW,IW,LW,RW,zW,BW,VW,HW,qW,JW,YW,{id:`loadFocus`,label:`Load`,icon:gB(G.Load)??gB(G.Resistance)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:G.Load},{type:`metric-type`,metricType:G.Resistance}]},format:{type:`custom`,render:e=>aW(e,0)},sort:{type:`numeric`,extractor:e=>fW(e)},graph:{extractor:e=>fW(e),axisLabel:`Load`,unit:`kg`},filter:{extractor:e=>pW(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`strength`,`fallback`]}},XW,ZW,UW,WW],$W={outputTypes:[`segment`,`milestone`,`group`,`analytics`]},eG={definitions:QW,presets:{default:{label:`Default`,filters:$W,visibleColumnIds:[`#`,`timeSpan`,`descriptor`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`]},debug:{label:`Debug`,filters:{},visibleColumnIds:[`#`,`timeSpan`,`timestamp`,`spans`,`blockKey`,`outputType`,`stackLevel`,`descriptor`,`duration`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`,`group`,`system`,`elapsedTotal`,`completionReason`]},strength:{label:`Strength`,filters:$W,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`rep`,`loadFocus`,`volume`,`intensity`,`load`,`work`,`elapsedTotal`]},endurance:{label:`Endurance`,filters:$W,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`distance`,`duration`,`pace`,`rounds`,`increment`,`work`,`elapsedTotal`]}},defaultPreset:`default`},tG=new class{config;definitionMap;constructor(e){this.config=e,this.definitionMap=new Map(e.definitions.map(e=>[e.id,e]))}getVisibleColumns(e){return this.getOrderedCandidates(e).filter(t=>this.computeVisibility(t.id,e))}getAvailableColumns(e){let t=new Set(this.getVisibleColumns(e).map(e=>e.id));return this.config.definitions.filter(n=>!t.has(n.id)&&this.isColumnAvailable(n,e))}getGraphableColumns(e){return this.getVisibleColumns(e).filter(e=>e.graph!==void 0)}getGraphTaggedColumns(e){let t=e.graphTaggedColumnIds;return!t||t.size===0?[]:this.getVisibleColumns(e).filter(e=>t.has(e.id))}isColumnVisible(e,t){return this.getDefinition(e)?this.computeVisibility(e,t):!1}getDefinition(e){return this.definitionMap.get(e)}getPreset(e){return this.config.presets[e]??this.config.presets[this.config.defaultPreset]}getAllDefinitions(){return this.config.definitions}get definitions(){return this.definitionMap}resolveColumnValue(e,t,n,r){let i=this.getDefinition(t);if(!i)return;let a={allRows:n,rowIndex:r??n.findIndex(t=>t.id===e.id),columnDef:i,dependencies:new Map};return kU(e,i.source,a,this.definitionMap)}getOrderedCandidates(e){let t=this.getPreset(e.activePresetId),n=[],r=new Set,i=e=>{if(r.has(e))return;let t=this.getDefinition(e);t&&(n.push(t),r.add(e))};for(let e of t.visibleColumnIds)i(e);for(let e of this.config.definitions)i(e.id);if(e.addedColumnIds)for(let t of e.addedColumnIds)i(t);return n}computeVisibility(e,t,n){if(t.visibilityOverrides&&e in t.visibilityOverrides)return t.visibilityOverrides[e];if(t.addedColumnIds?.has(e))return!0;let r=this.getDefinition(e);if(!r||r.meta?.debugOnly&&!t.isDebugMode||!n&&this.isColumnSubsumed(e,t))return!1;let i=this.getPreset(t.activePresetId).visibleColumnIds.includes(e),a=this.hasDataInRows(r,t.rows);switch(r.source.type){case`fixed-field`:return i;case`derived`:return i;case`metric-type`:return a;case`fallback`:return i&&a;default:return i}}isColumnSubsumed(e,t){for(let n of this.config.definitions)if(n.meta?.subsumes?.length&&this.getPreset(t.activePresetId).visibleColumnIds.includes(n.id)&&n.meta.subsumes.includes(e))return!0;return!1}isColumnAvailable(e,t){return e.meta?.debugOnly&&!t.isDebugMode?!1:this.getPreset(t.activePresetId).visibleColumnIds.includes(e.id)?!this.computeVisibility(e.id,t):e.source.type===`fixed-field`||e.source.type===`derived`||this.hasDataInRows(e,t.rows)}hasDataInRows(e,t){if(t.length===0)return!1;switch(e.source.type){case`fixed-field`:return!0;case`metric-type`:{let{metricType:n}=e.source;return t.some(e=>e.cells.has(n))}case`derived`:return!0;case`fallback`:{let{sources:n}=e.source;return t.some(e=>n.some(t=>this.sourceHasDataInRow(t,e)))}default:return!0}}sourceHasDataInRow(e,t){switch(e.type){case`fixed-field`:return t[e.field]!==void 0&&t[e.field]!==null;case`metric-type`:return t.cells.has(e.metricType);case`derived`:return!0;case`fallback`:return e.sources.some(e=>this.sourceHasDataInRow(e,t));default:return!1}}}(eG);function nG(e){let{segments:t,userOutputOverrides:n,presetId:r,isDebugMode:i,sortConfigs:a,filterOverrides:o,graphTaggedColumns:s,extraMetricTypes:c,columnVisibilityOverrides:l,addedColumnIds:u}=e,d=(0,V.useMemo)(()=>rG(t,n),[t,n]),f=(0,V.useMemo)(()=>{let e=new Set(u??[]);for(let t of c??[])e.add(t);return e},[u,c]),p=(0,V.useMemo)(()=>({rows:d,activePresetId:r,isDebugMode:i,graphTaggedColumnIds:s,visibilityOverrides:l,addedColumnIds:f}),[d,r,i,s,l,f]),m=(0,V.useMemo)(()=>tG.getVisibleColumns(p),[p]),h=(0,V.useMemo)(()=>tG.getAvailableColumns(p),[p]),g=(0,V.useMemo)(()=>({...tG.getPreset(r).filters??{},...o}),[r,o]);return{rows:(0,V.useMemo)(()=>sG(oG(d,g,m,tG.definitions),a,m,tG.definitions),[d,g,a,m]),visibleColumns:m,availableColumns:h,graphTaggedColumnIds:(0,V.useMemo)(()=>Array.from(s??[]),[s])}}function rG(e,t){return e.map((e,n)=>{let r=new Map;if(e.metrics)for(let t of e.metrics)aG(r,t);let i=iG(e),a=i?t.get(i):void 0;if(a)for(let e of a)aG(r,e);for(let[,e]of r)e.hasUserOverride=e.metrics.some(e=>e.origin===`user`);let o=e.context?.outputType??e.type;return{id:e.id,index:n+1,sourceBlockKey:i??`segment-${e.id}`,sourceStatementId:e.context?.sourceStatementId,outputType:o,stackLevel:e.depth,absoluteStartTime:e.absoluteStartTime,duration:e.duration,elapsed:e.elapsed,total:e.total,spans:e.spans?[...e.spans]:[],completionReason:e.context?.completionReason,cells:r}})}function iG(e){let t=e.context;return t?.sourceBlockKey?t.sourceBlockKey:e.name}function aG(e,t){let n=t.type;if(n===G.Sound)return;let r=e.get(n);r?e.set(n,{metrics:r.metrics.clone().add(t),hasUserOverride:r.hasUserOverride}):e.set(n,{metrics:K.empty(n).add(t),hasUserOverride:!1})}function oG(e,t,n,r){let i=e;if(t.outputTypes&&t.outputTypes.length>0){let e=new Set(t.outputTypes);i=i.filter(t=>e.has(t.outputType))}if(t.origins&&t.origins.length>0){let e=new Set(t.origins);i=i.filter(t=>{for(let[,n]of t.cells)if(n.metrics.some(t=>t.origin&&e.has(t.origin)))return!0;return!1})}if(t.searchText&&t.searchText.trim().length>0){let a=t.searchText.trim().toLowerCase();i=i.filter(t=>{for(let i of n)if(i.filter&&UU(t,i,{allRows:e,rowIndex:e.indexOf(t),columnDef:i,dependencies:new Map},r).toLowerCase().includes(a))return!0;return!1})}if(t.columnFilters)for(let[a,o]of Object.entries(t.columnFilters)){if(!o||o.trim().length===0)continue;let t=n.find(e=>e.id===a);t&&(i=i.filter(n=>{let i={allRows:e,rowIndex:e.indexOf(n),columnDef:t,dependencies:new Map};return WU(n,t,o,i,r)}))}return i}function sG(e,t,n,r){if(t.length===0)return e;let i=[...e];return i.sort((i,a)=>{for(let o of t){let t=n.find(e=>e.id===o.columnId);if(!t||!t.sort)continue;let s={allRows:e,rowIndex:e.indexOf(i),columnDef:t,dependencies:new Map},c={allRows:e,rowIndex:e.indexOf(a),columnDef:t,dependencies:new Map},l=VU(BU(i,t,s,r),BU(a,t,c,r));if(l!==0)return o.direction===`asc`?l:-l}return i.index-a.index}),i}function cG(e,t){return{id:e,label:t.label,filters:t.filters??{},visibleColumns:[...t.visibleColumnIds],isDefault:e===eG.defaultPreset}}var lG=Object.fromEntries(Object.entries(eG.presets).map(([e,t])=>[e,cG(e,t)])),uG=lG.default;lG.debug,lG.strength,lG.endurance;function dG(e){return lG[e]??uG}var fG=({activePreset:e,onPresetChange:t,searchText:n,onSearchChange:r,showFilters:i,onToggleFilters:a,totalRows:o,visibleRows:s})=>(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2 border-b border-border bg-muted/10 dark:bg-muted/5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`label`,{className:`text-xs text-muted-foreground font-medium`,children:`View:`}),(0,H.jsx)(`select`,{className:`text-xs rounded border border-border bg-background text-foreground px-1.5 py-1 focus:outline-none focus:ring-1 focus:ring-primary/40`,value:e.id,onChange:e=>t(e.target.value),children:Object.values(lG).map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,H.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,H.jsx)(`div`,{className:`flex items-center flex-1 max-w-md`,children:(0,H.jsxs)(`div`,{className:`flex w-full group`,children:[(0,H.jsx)(`input`,{type:`text`,className:`flex-1 px-2.5 py-1 text-xs rounded-l border border-r-0 border-border bg-background text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-primary/40 focus:z-10`,placeholder:`Filter results…`,value:n,onChange:e=>r(e.target.value)}),(0,H.jsxs)(`button`,{className:`px-2.5 py-1 text-xs rounded-r border border-border bg-muted/30 text-muted-foreground hover:bg-muted/50 hover:text-foreground transition-colors flex items-center gap-1.5 border-l-0`,title:`Filter results`,children:[(0,H.jsx)(`span`,{children:`🔍`}),(0,H.jsx)(`span`,{className:`font-medium`,children:`Search`})]})]})}),(0,H.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,H.jsx)(`button`,{className:[`text-xs px-2 py-1 rounded border transition-colors`,i?`bg-primary/10 border-primary/30 text-primary`:`bg-muted/30 border-border text-muted-foreground hover:text-foreground`].join(` `),onClick:a,title:i?`Hide column filters`:`Show column filters`,children:`🔽 Filters`}),(0,H.jsx)(`div`,{className:`ml-auto text-xs text-muted-foreground tabular-nums`,children:s===o?`${o} rows`:`${s} / ${o} rows`})]}),pG={"#":`40px`,exercise:`180px`,text:`160px`,notes:`160px`,completionReason:`160px`,rep:`72px`,rounds:`72px`,"current-round":`72px`,duration:`96px`,distance:`96px`,resistance:`96px`,load:`96px`,volume:`96px`,intensity:`96px`,metric:`96px`,work:`96px`,elapsedTotal:`96px`,action:`96px`,increment:`96px`,timestamp:`96px`,spans:`96px`,blockKey:`180px`,outputType:`96px`,stackLevel:`72px`,elapsed:`96px`},mG=`48px`;function hG(e){return e.meta?.width??pG[e.id]??`96px`}function gG(){return mG}var _G=({columns:e,sortConfigs:t,onSort:n,onToggleGraph:r,showFilters:i,columnFilters:a,onColumnFilterChange:o,availableToAdd:s,onAddColumn:c,graphTaggedColumnIds:l})=>(0,H.jsxs)(`thead`,{className:`bg-muted/50 dark:bg-muted/30 sticky top-0 z-10`,children:[(0,H.jsxs)(`tr`,{className:`border-b border-border`,children:[e.map(e=>(0,H.jsx)(vG,{column:e,sortConfig:t.find(t=>t.columnId===e.id),onSort:n,onToggleGraph:r,isGraphed:l?.has(e.id)??!1},e.id)),c&&(0,H.jsx)(`th`,{className:`py-2 px-1`,style:{minWidth:gG()},children:(0,H.jsx)(xG,{availableToAdd:s??[],onAddColumn:c})})]}),i&&(0,H.jsxs)(`tr`,{className:`border-b border-border/50 bg-muted/20 dark:bg-muted/10`,children:[e.map(e=>(0,H.jsx)(bG,{column:e,value:a[e.id]??``,onChange:o},e.id)),c&&(0,H.jsx)(`th`,{className:`py-1 px-1`,style:{minWidth:gG()}})]})]}),vG=({column:e,sortConfig:t,onSort:n,onToggleGraph:r,isGraphed:i})=>{let a=e.sort!==void 0,o=e.graph!==void 0,s=(0,V.useCallback)(t=>{a&&n(e.id,t.shiftKey)},[e.id,a,n]),c=(0,V.useCallback)(t=>{t.stopPropagation(),r(e.id)},[e.id,r]);return(0,H.jsx)(`th`,{className:[`py-1.5 px-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap select-none`,a?`cursor-pointer hover:text-foreground transition-colors`:``].join(` `),style:{minWidth:hG(e)},onClick:s,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.icon&&(0,H.jsx)(`span`,{className:`text-sm`,children:e.icon}),(0,H.jsx)(`span`,{children:e.label}),t&&(0,H.jsx)(yG,{direction:t.direction}),o&&(0,H.jsx)(`button`,{className:[`ml-auto text-sm opacity-40 hover:opacity-100 transition-opacity`,i?`opacity-100 text-primary`:``].join(` `),onClick:c,title:i?`Remove from graph`:`Add to graph`,children:`📊`})]})})},yG=({direction:e})=>(0,H.jsx)(`span`,{className:`text-primary text-[10px] ml-0.5`,children:e===`asc`?`▲`:`▼`}),bG=({column:e,value:t,onChange:n})=>e.filter?(0,H.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:hG(e)},children:(0,H.jsx)(`input`,{type:`text`,className:`w-full px-1.5 py-0.5 text-xs rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/40`,placeholder:`Filter…`,value:t,onChange:t=>n(e.id,t.target.value)})}):(0,H.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:hG(e)}}),xG=({availableToAdd:e,onAddColumn:t})=>{let[n,r]=(0,V.useState)(!1),i=(0,V.useRef)(null),a=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&a.current&&!a.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]),e.length===0?null:(0,H.jsxs)(`div`,{className:`relative flex items-center justify-center`,children:[(0,H.jsx)(`button`,{ref:a,title:`Add metric column`,onClick:e=>{e.stopPropagation(),r(e=>!e)},className:[`flex items-center justify-center w-5 h-5 rounded text-[11px] font-bold transition-all`,`text-muted-foreground hover:text-foreground hover:bg-primary/10 hover:border-primary/40`,`border border-dashed border-muted-foreground/40`,n?`bg-primary/10 border-primary/40 text-foreground`:``].join(` `),children:`+`}),n&&(0,H.jsxs)(`div`,{ref:i,className:`absolute right-0 top-full mt-1 z-50 min-w-[160px] max-h-64 overflow-y-auto
145
- bg-popover border border-border rounded-md shadow-xl py-1`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider border-b border-border/50 mb-1`,children:`Add metric column`}),e.map(e=>{let n=gB(e)??`•`,i=_o.columnLabel(e);return(0,H.jsxs)(`button`,{onClick:()=>{t(e),r(!1)},className:`w-full flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-muted text-foreground transition-colors`,children:[(0,H.jsx)(`span`,{className:`text-sm w-4 text-center`,children:n}),(0,H.jsx)(`span`,{children:i})]},e)})]})]})},SG=({row:e,allRows:t,rowIndex:n,columns:r,isSelected:i,onSelect:a,isHovered:o,onHover:s,onCellDoubleClick:c})=>{let l=t=>{a(e.id,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},u=e.outputType===`group`;return(0,H.jsx)(`tr`,{className:U(`border-b border-border transition-colors cursor-pointer`,u?`bg-muted/50 font-bold`:``,i?`bg-accent dark:bg-accent/20`:o?`bg-muted/50 dark:bg-muted/40`:`hover:bg-muted/30 dark:hover:bg-muted/20`),onClick:l,onMouseEnter:()=>s(e.sourceBlockKey),onMouseLeave:()=>s(null),children:r.map(r=>{let i=r.source.type===`metric-type`&&r.source.metricType===G.Effort;return(0,H.jsx)(KU,{columnDef:r,row:e,allRows:t,rowIndex:n,indent:i?e.stackLevel:0,onDoubleClick:c,style:{minWidth:hG(r)}},r.id)})})};function CG(e){let{rows:t,columns:n,graphTaggedColumnIds:r,definitionMap:i}=e,a=(0,V.useMemo)(()=>wG(r,n),[r,n]),o=(0,V.useMemo)(()=>TG(t,r,n,i),[t,r,n,i]);return{data:o,graphConfigs:a,hasData:a.length>0&&o.length>0}}function wG(e,t){let n=[];for(let r of e){let e=t.find(e=>e.id===r);e&&n.push({id:r,label:e.label,unit:kG(e),color:EG(e),dataKey:r,icon:e.icon})}return n}function TG(e,t,n,r){return t.length===0?[]:e.map((i,a)=>{let o={index:i.index,label:i.sourceBlockKey};for(let s of t){let t=n.find(e=>e.id===s);if(!t||!t.graph){o[s]=0;continue}o[s]=HU(i,t,{allRows:e,rowIndex:a,columnDef:t,dependencies:new Map},r)??0}return o})}function EG(e){if(e.graph?.color)return e.graph.color;let t=DG(e);return t?OG[t]??`#888888`:`#888888`}function DG(e){if(e.source.type===`metric-type`)return e.source.metricType}var OG={[G.Time]:`#3b82f6`,[G.Rep]:`#22c55e`,[G.Effort]:`#eab308`,[G.Distance]:`#14b8a6`,[G.Rounds]:`#a855f7`,[G.Resistance]:`#ef4444`,[G.Increment]:`#6366f1`,[G.Action]:`#ec4899`};function kG(e){if(e.graph?.unit)return e.graph.unit;let t=DG(e);if(!t)return``;switch(t){case G.Time:return`ms`;case G.Rep:return`reps`;case G.Distance:return`m`;case G.Rounds:return`rounds`;case G.Resistance:return`kg`;case G.Increment:return`Δ`;default:return``}}var AG=({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r,onSelectRow:i})=>{let[a,o]=(0,V.useState)(!1),{data:s,graphConfigs:c,hasData:l}=CG({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r}),u=(0,V.useCallback)(t=>{if(!t?.activePayload?.[0])return;let n=t.activePayload[0].payload,r=e.find(e=>e.index===n.index);r&&i&&i(r.id)},[e,i]);return n.length===0?null:(0,H.jsxs)(`div`,{className:`border-b border-border bg-background`,children:[(0,H.jsxs)(`button`,{className:`w-full flex items-center justify-between px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/20 transition-colors`,onClick:()=>o(e=>!e),children:[(0,H.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{children:`📊`}),(0,H.jsxs)(`span`,{children:[`Graph — `,c.map(e=>e.label).join(`, `)]})]}),(0,H.jsx)(`span`,{className:`text-[10px]`,children:a?`▼`:`▲`})]}),!a&&(0,H.jsx)(`div`,{className:`px-3 pb-3`,children:l?(0,H.jsx)(`div`,{className:`w-full bg-muted/30 rounded-lg border border-border p-2`,style:{height:220},children:(0,H.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,H.jsxs)(An,{data:s,onClick:u,children:[(0,H.jsx)(Ee,{strokeDasharray:`3 3`,stroke:`hsl(var(--border))`,vertical:!1}),(0,H.jsx)(tt,{dataKey:`index`,stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},label:{value:`Row #`,position:`insideBottom`,offset:-5,fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,H.jsx)(re,{stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},domain:[`auto`,`auto`]}),(0,H.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>`Row ${e}`,formatter:(e,t)=>{let n=c.find(e=>e.dataKey===t);return[`${typeof e==`number`?e.toLocaleString():e}${n?.unit?` ${n.unit}`:``}`,n?.label??t]}}),(0,H.jsx)(bn,{verticalAlign:`top`,height:24,wrapperStyle:{fontSize:`11px`}}),c.map(e=>(0,H.jsx)(at,{type:`monotone`,dataKey:e.dataKey,name:e.label,stroke:e.color,strokeWidth:2,dot:{r:3,fill:e.color},activeDot:{r:5,stroke:e.color,strokeWidth:2}},e.id))]})})}):(0,H.jsx)(`div`,{className:`h-32 flex items-center justify-center text-sm text-muted-foreground`,children:`No numeric data available for the tagged columns.`})})]})},jG=({isOpen:e,blockKey:t,metricType:n,existingFragments:r,existingUserValue:i,anchorRect:a,onSave:o,onRemove:s,onClose:c})=>{let[l,u]=(0,V.useState)(``),d=(0,V.useRef)(null),f=(0,V.useRef)(null);(0,V.useEffect)(()=>{e&&(u(i===void 0?``:String(i)),setTimeout(()=>d.current?.focus(),0))},[e,i]),(0,V.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&c()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,c]),(0,V.useEffect)(()=>{if(!e)return;let t=e=>{f.current&&!f.current.contains(e.target)&&c()},n=setTimeout(()=>{document.addEventListener(`mousedown`,t)},100);return()=>{clearTimeout(n),document.removeEventListener(`mousedown`,t)}},[e,c]);let p=(0,V.useCallback)(()=>{if(l.trim()===``)return;let e=Number(l.trim()),r=!isNaN(e)&&l.trim()!==``?e:l.trim();o(t,n,r,String(r)),c()},[l,t,n,o,c]),m=(0,V.useCallback)(()=>{s(t,n),c()},[t,n,s,c]),h=(0,V.useCallback)(e=>{e.key===`Enter`&&(e.preventDefault(),p())},[p]);if(!e)return null;let g=gB(n),_=mB(n),v=i!==void 0,y=r.filter(e=>e.origin!==`user`),b=a?{position:`fixed`,top:a.bottom+4,left:Math.max(8,Math.min(a.left,window.innerWidth-280)),zIndex:50}:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,zIndex:50};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`fixed inset-0 bg-black/20 dark:bg-black/40 z-40`}),(0,H.jsxs)(`div`,{ref:f,className:`w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-lg`,style:b,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[g&&(0,H.jsx)(`span`,{className:`text-sm`,children:g}),(0,H.jsx)(`span`,{className:`text-sm font-medium capitalize`,children:n}),(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground ml-auto truncate max-w-[100px]`,title:t,children:t})]}),y.length>0&&(0,H.jsxs)(`div`,{className:`px-3 py-1.5 border-b border-border/50 bg-muted/10`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1 uppercase tracking-wider`,children:`Current`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:y.map((e,t)=>(0,H.jsx)(`span`,{className:`inline-flex items-center px-1.5 py-0.5 rounded text-xs border ${_}`,children:e.image??String(e.value??e.type)},t))})]}),(0,H.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,H.jsx)(`label`,{className:`text-[10px] text-muted-foreground uppercase tracking-wider mb-1 block`,children:v?`Update override`:`Enter value`}),(0,H.jsx)(`input`,{ref:d,type:`text`,className:`w-full px-2 py-1.5 text-sm rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/40`,placeholder:`Enter ${n} value…`,value:l,onChange:e=>u(e.target.value),onKeyDown:h})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-t border-border/50`,children:[(0,H.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors`,onClick:c,children:`Cancel`}),v&&(0,H.jsx)(`button`,{className:`px-2 py-1 text-xs rounded border border-destructive/30 text-destructive hover:bg-destructive/10 transition-colors`,onClick:m,title:`Remove user override`,children:`Clear`}),(0,H.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,onClick:p,disabled:l.trim()===``,children:`Save`})]})]})]})},MG=({segments:e,selectedSegmentIds:t,onSelectSegment:n,userOutputOverrides:r=new Map,gridViewPreset:i=`default`,onPresetChange:a,hoveredBlockKey:o,onHoverBlockKey:s})=>{let{isDebugMode:c}=ty(),[l,u]=(0,V.useState)([]),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)({}),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(new Set),[y,b]=(0,V.useState)({}),[x,S]=(0,V.useState)(new Set),{overrides:C,setOverride:w,removeOverride:T}=kV(!0),[E,D]=(0,V.useState)({isOpen:!1,blockKey:``,type:`Time`,anchorRect:null,existingFragments:[]}),O=(0,V.useMemo)(()=>{let e=new Map;for(let[t,n]of r)e.set(t,n instanceof K?n:K.from(n,t));for(let[t,n]of C)e.set(t,n);return e},[r,C]),k=c?`debug`:i,A=(0,V.useMemo)(()=>dG(k),[k]),{rows:j,visibleColumns:M,availableColumns:N,graphTaggedColumnIds:P}=nG({segments:e,userOutputOverrides:O,presetId:k,isDebugMode:c,sortConfigs:l,filterOverrides:(0,V.useMemo)(()=>({searchText:d||void 0,columnFilters:Object.keys(p).length>0?p:void 0}),[d,p]),graphTaggedColumns:_,extraMetricTypes:x,columnVisibilityOverrides:y,addedColumnIds:x}),F=M,I=e.length,ee=(0,V.useMemo)(()=>j.map(e=>e.id),[j]),te=(0,V.useCallback)((e,t)=>{u(n=>{let r=n.find(t=>t.columnId===e);return t?r?r.direction===`asc`?n.map(t=>t.columnId===e?{...t,direction:`desc`}:t):n.filter(t=>t.columnId!==e):[...n,{columnId:e,direction:`asc`}]:r?r.direction===`asc`?[{columnId:e,direction:`desc`}]:[]:[{columnId:e,direction:`asc`}]})},[]),ne=(0,V.useCallback)(e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),re=(0,V.useCallback)((e,t)=>{m(n=>{if(!t){let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),ie=(0,V.useCallback)(e=>{b({}),m({}),f(``),a?.(e)},[a]),ae=(0,V.useCallback)(e=>{S(t=>{let n=new Set(t);return n.add(e),n})},[]),oe=(0,V.useMemo)(()=>N.filter(e=>e.source.type===`metric-type`).map(e=>e.source.metricType),[N]),se=(0,V.useCallback)((e,t)=>{n(e,t,ee)},[n,ee]),ce=(0,V.useCallback)(e=>{s?.(e)},[s]),L=(0,V.useCallback)(e=>{n(e,{ctrlKey:!1,shiftKey:!1},ee)},[n,ee]),le=(0,V.useCallback)((e,t,n)=>{let r=(j.find(t=>t.sourceBlockKey===e)?.cells.get(t))?.metrics.toArray()??[],i=r.find(e=>e.origin===`user`),a=i?.value==null?void 0:String(i.value);D({isOpen:!0,blockKey:e,type:t,anchorRect:n,existingFragments:r,existingUserValue:a})},[j]),ue=(0,V.useCallback)((e,t,n,r)=>{w(e,t,n,r),D(e=>({...e,isOpen:!1}))},[w]),R=(0,V.useCallback)(()=>{T(E.blockKey,E.type),D(e=>({...e,isOpen:!1}))},[E.blockKey,E.type,T]),de=(0,V.useCallback)(()=>{D(e=>({...e,isOpen:!1}))},[]);return(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-background`,children:[(0,H.jsx)(fG,{activePreset:A,onPresetChange:ie,searchText:d,onSearchChange:f,showFilters:h,onToggleFilters:()=>g(e=>!e),totalRows:I,visibleRows:j.length}),(0,H.jsx)(AG,{rows:j,columns:M,graphTaggedColumnIds:P,selectedIds:t,onSelectRow:L}),(0,H.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,H.jsxs)(`table`,{className:`text-left text-sm border-collapse min-w-[700px]`,children:[(0,H.jsx)(_G,{columns:F,sortConfigs:l,onSort:te,onToggleGraph:ne,showFilters:h,columnFilters:p,onColumnFilterChange:re,availableToAdd:oe,onAddColumn:ae,graphTaggedColumnIds:_}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border`,children:j.length===0?(0,H.jsx)(`tr`,{children:(0,H.jsx)(`td`,{colSpan:F.length,className:`py-8 text-center text-muted-foreground text-sm`,children:e.length===0?`Finish or stop the timer — results land here`:`No rows match the current filters.`})}):j.map((e,n)=>(0,H.jsx)(SG,{row:e,allRows:j,rowIndex:n,columns:F,isSelected:t.has(e.id),onSelect:se,isHovered:o===e.sourceBlockKey,onHover:ce,onCellDoubleClick:le},e.id))})]})}),(0,H.jsx)(jG,{isOpen:E.isOpen,blockKey:E.blockKey,metricType:E.type,existingFragments:E.existingFragments,existingUserValue:E.existingUserValue,anchorRect:E.anchorRect??void 0,onSave:ue,onRemove:R,onClose:de}),(0,H.jsxs)(`div`,{className:`px-3 py-1.5 border-t border-border bg-muted/10 text-xs text-muted-foreground flex items-center justify-between`,children:[(0,H.jsx)(`span`,{children:t.size>0?`${t.size} selected`:`Click a row to select`}),(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[j.length,` / `,I,` rows`]})]})]})};Yt();var NG=({title:e,onClose:t,children:n,closeButtonClassName:r,floatingClose:i=!1,variant:a=`default`,actions:o,closeLabel:s})=>{(0,V.useEffect)(()=>(document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=``}),[]);let c=a===`minimal`,l=(0,H.jsx)(`button`,{onClick:t,className:r??`rounded-pill transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${c?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${s?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`p-2`}`,title:s??`Close`,"data-testid":sB.FOCUSED_DIALOG_CLOSE,children:s??(0,H.jsx)(Te,{className:`h-5 w-5`})});return aS.createPortal((0,H.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex flex-col bg-background text-foreground animate-in fade-in duration-200`,children:[i||c&&!e?(0,H.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[o,l]}):e?(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${c?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,H.jsx)(`h2`,{className:`text-lg ${c?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[o,l]})]}):null,(0,H.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:n})]}),document.body)},PG=(0,V.createContext)({updateFromSegments:()=>{},clear:()=>{}}),FG=({children:e,chromecastSubscription:t=null})=>(0,H.jsx)(PG.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),IG=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?TV(e.analyticsSegments):DV(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 LG(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 RG=()=>{let e=_V(),[t,n]=(0,V.useState)(e.state),[r,i]=(0,V.useState)(!1),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(null),[l,u]=(0,V.useState)(null),d=(0,V.useRef)(null),f=cF,p=(0,V.useRef)(f.getActiveHandle()),m=(0,V.useRef)(!1),h=(0,V.useCallback)(e=>{let t=p.current;p.current=null,t&&f.dispose(e),qO(null),u(null),c(null),i(!1)},[f]),g=(0,V.useCallback)(async e=>{if(!m.current){m.current=!0;try{let t=JI.getState().subscriptionManager,n=f.connect(e,t);p.current=n,u(n),c(n.subscription),i(!0),qO(n.transport),n.eventProvider.onEvent(e=>{let t=JI.getState();yV(e,{onNext:()=>{t.handles.handleNext&&t.handles.handleNext(),t.runtime&&(!t.handles.handleNext||t.handles.handleNext===_F.handleNext)&&(t.runtime.handle(new mf(void 0,t.runtime.nowProvider)),t.execution.status!==`running`&&t.execution.start())},onStart:()=>{t.handles.handleStart&&t.handles.handleStart(),t.execution&&(!t.handles.handleStart||t.handles.handleStart===_F.handleStart)&&t.execution.start()},onPause:()=>{t.handles.handlePause&&t.handles.handlePause(),t.execution&&(!t.handles.handlePause||t.handles.handlePause===_F.handlePause)&&t.execution.pause()},onStop:()=>{t.handles.handleStop&&t.handles.handleStop(),t.execution&&(!t.handles.handleStop||t.handles.handleStop===_F.handleStop)&&t.execution.stop()}})});let r=JI.getState(),a=IG.resolve({viewMode:r.viewMode,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:r.analyticsSegments,selectedBlock:r.selectedBlock,documentItems:r.documentItems});n.pushInitialWorkbench(a)}finally{m.current=!1}}},[f]),_=(0,V.useRef)(!1),v=(0,V.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:`,LG(t)),h(!1),e.endSession()}finally{_.current=!1}}},[e,g,h,f]);(0,V.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,V.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,V.useEffect)(()=>{let e=()=>{f.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[f]),(0,V.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=LG(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):console.error(`[CastButtonRpc] Cast failed:`,t),h(!1)}};return t.addEventListener(`click`,n),()=>t.removeEventListener(`click`,n)},[e,g,h]);let y=(0,V.useRef)(t);y.current=t;let b=(0,V.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,H.jsx)(W,{variant:`ghost`,size:`icon`,disabled:!0,className:`opacity-20 cursor-not-allowed`,children:(0,H.jsx)(On,{className:`h-5 w-5`})}):(0,H.jsx)(QO,{transport:l?.transport??null,children:(0,H.jsx)(FG,{chromecastSubscription:s,children:(0,H.jsx)(W,{ref:d,variant:`ghost`,size:`icon`,disabled:D,onClick:()=>{},className:U(`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,H.jsx)(F,{className:`h-5 w-5`}):(0,H.jsx)(On,{className:`h-5 w-5`})})})})};function zG(){let{isEnabled:e,toggleAudio:t}=tk();return(0,H.jsxs)(W,{variant:`ghost`,size:`icon`,onClick:t,className:`h-9 w-9 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,H.jsx)(fe,{className:`h-[1.2rem] w-[1.2rem]`}):(0,H.jsx)(ne,{className:`h-[1.2rem] w-[1.2rem]`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}var BG=({block:e,prepareRun:t,view:n,onClose:r,onCompleteWorkout:i,autoStart:a,onRuntimeReady:o,onRunStarted:s,externalStop:c})=>{let[l,u]=(0,V.useState)(t?null:e),[d,f]=(0,V.useState)(null),p=(0,V.useRef)(!1),m=(0,V.useCallback)(async()=>{if(!(!t||p.current)){p.current=!0,f(null);try{u(await t())}catch(e){f(e instanceof Error?e.message:String(e))}finally{p.current=!1}}},[t]);(0,V.useEffect)(()=>{m()},[m]);let[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(new Set),{isDebugMode:y}=ty(),b=(0,V.useRef)(Date.now()),x=(0,V.useRef)(typeof document<`u`?document.title:`Wod.Wiki`);(0,V.useEffect)(()=>{let t=e.label||e.id,n=h!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,window.gtag?.(`event`,`page_view`,{page_title:r,page_path:i,page_location:typeof window<`u`?`${window.location.origin}${i}`:i}),n?window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):(YV.record(`runtime:dialog_loaded`,{workout_label:t,block_type:e.blockType}),window.gtag?.(`event`,`runtime_dialog_loaded`,{workout_label:t,block_type:e.blockType}))},[e.id,e.label,e.blockType,h]),(0,V.useEffect)(()=>{let t=x.current,n=e.label||e.id;return()=>{let e=Date.now()-b.current;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:n,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label]);let S=(0,V.useRef)(!1),C=(0,V.useRef)(!1),w=(0,V.useRef)(!1),[T,E]=(0,V.useState)(!1),D=(0,V.useRef)(!1),O=(0,V.useRef)(!1),k=(0,V.useRef)(null),[A,j]=(0,V.useState)(`idle`),[M,N]=(0,V.useState)(null),[P,F]=(0,V.useState)(!1),I=async()=>{let e=k.current;if(!e||D.current)return;D.current=!0,O.current=!1,j(`saving`),N(null);let t;try{t=i?.(e.blockId,e.results),await t}catch(e){O.current=!0,N(e instanceof Error?e.message:String(e)),j(`error`),D.current=!1;return}D.current=!1,j(`idle`),F(!0);let{results:n}=e;if(n.completed&&n.logs&&n.logs.length>0)try{let{segments:e}=BP(n.logs,n.startTime);g(e)}catch{g([])}else n.completed?g([]):w.current&&r()},ee=(0,V.useCallback)(()=>{S.current=!0,s?.()},[s]),te=()=>{if(D.current||O.current){w.current=!0;return}if(h!==null||C.current||!S.current){r();return}w.current=!0,E(!0)},ne=(e,t)=>{C.current||(C.current=!0,k.current={blockId:e,results:t},I())},re=(e,t,n)=>{v(r=>{let i=new Set(r);if(t?.ctrlKey)i.has(e)?i.delete(e):i.add(e);else if(t?.shiftKey&&n){let t=Array.from(r).pop();if(t!==void 0){let r=n.indexOf(t),a=n.indexOf(e);if(r!==-1&&a!==-1){let e=Math.min(r,a),t=Math.max(r,a);for(let r=e;r<=t;r++)i.add(n[r])}else i.add(e)}else i.add(e)}else i.clear(),i.add(e);return i})},ie=A===`idle`?null:(0,H.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:[A===`saving`&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),A===`error`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,M?` — ${M}`:``]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>void I(),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 l?h===null?(0,H.jsx)(NG,{onClose:te,title:`Workout`,closeLabel:`Exit`,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,onClick:te,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,H.jsx)(RG,{}),(0,H.jsx)(zG,{})]}),children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[ie,d?(0,H.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,d]}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void m(),children:`Retry starting workout`})]}):l?null:(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,H.jsx)(UV,{block:l,view:n,onClose:te,onComplete:ne,isExpanded:!0,autoStart:a,onRuntimeReady:o,onRunStarted:ee,externalStop:c||T})})]})}):(0,H.jsx)(NG,{title:`Workout Complete`,onClose:te,actions:(0,H.jsxs)(H.Fragment,{children:[P&&(0,H.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,H.jsx)(RG,{}),(0,H.jsx)(zG,{})]}),children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[ie,(0,H.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,H.jsx)(MG,{runtime:null,segments:h,selectedSegmentIds:_,onSelectSegment:re,groups:[],gridViewPreset:y?`debug`:`default`})})]})}):(0,H.jsx)(NG,{title:`Starting workout`,onClose:r,children:d?(0,H.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,d,` Your draft is kept.`]}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void m(),children:`Retry start`})]}):(0,H.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},VG={play:!0,"add-to-today":!0,schedule:!0},HG=`log`;function UG(e,t){return e.filter(e=>e.id===HG?t===`log`:!VG[e.id]||t===`run`)}function WG(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 GG(e){return function({className:t}){return V.isValidElement(e)?V.cloneElement(e,{className:U(e.props.className,t)}):(0,H.jsx)(`span`,{className:U(`flex items-center`,t),children:e})}}var KG=({cmd:e,block:t})=>{let[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(!1),o=(0,V.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,V.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,V.useMemo)(()=>GG(i?e.successIcon??e.icon:e.icon),[e.icon,e.successIcon,i]),l=(0,V.useMemo)(()=>GG(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),u=(0,V.useMemo)(()=>({id:e.id,label:e.label,icon:c,action:{type:`call`,handler:()=>s()}}),[e.id,e.label,c,s]),d=(0,V.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:l,action:{type:`call`,handler:o}}),[e.id,l,o]),f=(0,V.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);if(!e.onSplitClick){let t=i?e.successIcon??e.icon:e.icon;return(0,H.jsxs)(W,{variant:e.primary?`default`:`secondary`,className:U(e.iconOnly?`h-11 w-11 rounded-full p-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:rounded-sm sm:px-1.5 sm:py-0.5 text-[10px] font-medium shadow-sm`:`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`,i&&`text-emerald-600 bg-emerald-500/15 dark:text-emerald-400 dark:bg-emerald-500/20 border-emerald-500/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`?sB.EDITOR_START_WORKOUT:void 0,onClick:e=>{f(e),s()},onMouseDown:f,onPointerDown:f,children:[(0,H.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:t}),!e.iconOnly&&(0,H.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})}return(0,H.jsx)(`div`,{onClick:f,onMouseDown:f,onPointerDown:f,children:(0,H.jsx)(mU,{primary:u,secondary:d,size:`xs`,variant:e.primary?`primary`:`default`,className:`rounded-full sm:rounded-sm`,labelClassName:`sr-only sm:not-sr-only sm:inline`})})},qG=({view:e,commands:t})=>{let[n,r]=(0,V.useState)(()=>e?.plugin(hw)?.rects??[]),[i,a]=(0,V.useState)(0);(0,V.useEffect)(()=>{if(!e)return;let t=e.plugin(hw);t&&(r([...t.rects]),t.addListener(e=>r([...e])))},[e]),(0,V.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n=null,r=()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,a(t.scrollTop)}))};return t.addEventListener(`scroll`,r,{passive:!0}),a(t.scrollTop),()=>{n!==null&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,r)}},[e]);let o=e?e.plugin(hw):null,s=(n.length>0?n:o?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(s.length===0)return null;let{sections:c}=e.state.field(ZC),l=new Map(c.map(e=>[e.id,e]));return(0,H.jsx)(H.Fragment,{children:s.map(n=>{let r=l.get(n.sectionId);if(!r)return null;let a=WG(e,r),o=UG(t,ba(r.type));return o.length===0?null:(0,H.jsx)(`div`,{className:`absolute right-1 z-10 flex items-end gap-1 pointer-events-auto`,style:{top:n.top-i,height:n.firstLineHeight},children:o.map(e=>(0,H.jsx)(KG,{cmd:e,block:a},e.id))},n.sectionId)})})},JG=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=ZO(),a=(0,V.useRef)(``);return(0,V.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(`
154
+ `).length+ +(r.startLine>0),h=p.find(e=>e.from===m);if(!h)throw Error(`The selected workout occurrence is not in the saved note.`);let g=C(),_=await hF({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,V.useCallback)(async(e,n)=>{if(f.current)try{await f.current}catch{}let r=l.current;if(!r||u.current)return;if(p.current)return p.current;let i=d.current??{results:e,completed:n},a=(async()=>{d.current=i,c(d.current);try{await t.record({runBlock:r.block,blockId:r.block.id,noteId:r.noteId,resultId:r.resultId,data:i.results,createdAt:i.results.endTime??Date.now(),origin:`playground`})}finally{p.current===a&&(p.current=null)}u.current=!0,o(!0),d.current=null,c(null)})();return p.current=a,a},[t]),g=(0,V.useCallback)(async()=>{if(f.current)try{await f.current}catch{}p.current&&await p.current},[]);return{run:r,recorded:a,pendingResults:s,start:m,finalize:h,reset:(0,V.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,V.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 yH({title:e,getBlock:t,getContent:n}){let r=vH(),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(!1),u=(0,V.useRef)(!1),d=(0,V.useRef)(0),f=(0,V.useRef)(null),p=(0,V.useRef)(null);(0,V.useEffect)(()=>()=>{d.current+=1},[]);let m=(0,V.useCallback)(async e=>{let t=++d.current;try{await r.end(e?.results)}catch(e){t===d.current&&Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try stopping again.`,variant:`destructive`});return}t===d.current&&a(null)},[r]),h=(0,V.useCallback)(async(i,o)=>{let c=i??t();if(!c||u.current)return;u.current=!0;let l=++d.current;try{let t=await r.start(o??n(),c,{pageTitle:e??`Playground`});if(l!==d.current)return;s(null),a({kind:`timer`,block:t.block,results:null})}catch(e){l===d.current&&Z({title:`Could not save playground workout`,description:e instanceof Error?e.message:`The workout was not started. Please try again.`,variant:`destructive`})}finally{u.current=!1}},[r,e,t,n]),g=(0,V.useCallback)(async t=>{let i=d.current;try{await r.finalize(t,t.completed??!1)}catch(e){i===d.current&&Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try completing again.`,variant:`destructive`});return}if(i===d.current&&(s(t),a(null),f.current)){let t=f.current;f.current=null,l(!1);let i=p.current??{doc:n(),meta:{pageTitle:e??`Playground`}};p.current=null;try{await r.reset(i.doc,i.meta)}catch(e){Z({title:`Could not save reset snapshot`,description:e instanceof Error?e.message:`Your partial results are kept — try resetting again.`,variant:`destructive`})}finally{t()}}},[r,n,e]),_=(0,V.useCallback)(async t=>{let a=t??n(),o={pageTitle:e??`Playground`};try{if(r.run&&!r.recorded&&i){if(r.pendingResults)return await r.finalize(r.pendingResults.results,!1),await r.reset(a,o),!0;p.current={doc:a,meta:o},l(!0);let e=Promise.withResolvers();return f.current=e.resolve,await e.promise,!0}return await r.reset(a,o),!0}catch(e){return Z({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try resetting again.`,variant:`destructive`}),!1}},[r,n,e,i]);return{fullscreen:i,startRun:h,closeRun:m,completedResults:o,runState:(0,V.useMemo)(()=>({isReconnect:!1,onReconnect:()=>{},onRun:()=>{h()}}),[h]),handleWorkoutComplete:g,run:r.run,recorded:r.recorded,pendingResults:r.pendingResults,resetRequested:c,resetRun:_}}function bH({initialSource:e,initialSourceKey:t,contentOverride:n}){let[r,i]=(0,V.useState)(e),[a,o]=(0,V.useState)(1),[s,c]=(0,V.useState)(!1),[l,u]=(0,V.useState)(t),[d,f]=(0,V.useState)(e),p=(0,V.useRef)(e),m=(0,V.useRef)(null),h=(0,V.useRef)(new Map([[t,{original:e,current:e}]])),g=(0,V.useRef)(void 0),_=(0,V.useCallback)(()=>{requestAnimationFrame(()=>m.current?.focus())},[]),v=(0,V.useCallback)((e,t=e)=>{let n=h.current.get(t),r=n?.current??e,a=n?.original??e;if(n||h.current.set(t,{original:e,current:e}),u(t),f(a),_(),r===p.current){c(!1);return}clearTimeout(g.current),c(!0),o(0),g.current=setTimeout(()=>{p.current=r,i(r),o(1),c(!1),g.current=void 0,_()},180)},[_]),y=(0,V.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,V.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,V.useCallback)(e=>{m.current=e},[]),S=(0,V.useCallback)(()=>p.current,[]),C=(0,V.useRef)(void 0);return(0,V.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 xH=`wodwiki.quests.v1`;function SH(){try{let e=window.localStorage.getItem(xH);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 CH(e){try{window.localStorage.setItem(xH,JSON.stringify(e))}catch(e){console.error(`Failed to write quest progress:`,e)}}function wH(e){return SH()[e]??{}}function TH(e,t){let n=SH();n[e]=t,CH(n),window.dispatchEvent(new StorageEvent(`storage`,{key:xH}))}function EH(e,t){let n=wH(e);n[t]||(n[t]=!0,TH(e,n))}function DH(e,t){let n=wH(e);n[t]=!n[t],TH(e,n)}function OH(e,t){let[n,r]=(0,V.useState)(()=>wH(e));(0,V.useEffect)(()=>{let t=t=>{t.key===`wodwiki.quests.v1`&&r(wH(e))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)},[e]);let i=(0,V.useCallback)(t=>{EH(e,t),r(wH(e))},[e]),a=(0,V.useCallback)(t=>{DH(e,t),r(wH(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 kH({pageRoute:e,quests:t,completedResults:n,enabled:r=!0}){let{markComplete:i}=OH(e,t),a=(0,V.useRef)(new Set),o=t.map(e=>e.id).join(`|`);(0,V.useEffect)(()=>{a.current.clear()},[e,o]);let s=t.filter(e=>e.validation?.type===`workout-complete`);return(0,V.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 AH({pageRoute:e,quests:t,initialSource:n,currentSource:r,enabled:i=!0}){let{markComplete:a}=OH(e,t),o=t.some(e=>e.id===`qs-arrive`),s=t.some(e=>e.id===`qs-edit`),c=(0,V.useRef)(n);c.current=n;let l=(0,V.useRef)(r);l.current=r,(0,V.useEffect)(()=>{!i||!o||a(`qs-arrive`)},[i,o,a]),(0,V.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 jH(e){let[t,n]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(e).matches);return(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=e=>n(e.matches);return t.addEventListener?(t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)):(t.addListener(r),()=>t.removeListener(r))},[e]),t}var MH=(0,V.createContext)(null);function NH(){return(0,V.useContext)(MH)}function PH({title:e,subtitle:t,children:n,onReset:r,headerActions:i,className:a}){let o=NH();return(0,H.jsxs)(`div`,{className:U(`flex flex-col w-full h-full rounded-2xl lg:rounded-3xl border border-border shadow-2xl bg-background`,a),children:[(0,H.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,H.jsxs)(`div`,{className:`flex gap-1.5`,children:[r?(0,H.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,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-red-500/30`}),(0,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-amber-500/30`}),(0,H.jsx)(`div`,{className:`size-2.5 rounded-full bg-emerald-500/30`})]}),(0,H.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[o?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`flex min-w-0 flex-1 justify-end`,children:o.status}),o.pips]}):(0,H.jsxs)(`span`,{className:`text-[9px] font-black text-muted-foreground uppercase tracking-[0.2em]`,children:[e,t&&(0,H.jsxs)(`span`,{className:`ml-1.5 font-medium normal-case tracking-normal text-muted-foreground/50`,children:[`· `,t]})]}),i,r&&(0,H.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,H.jsx)(Dn,{className:`size-3`}),`Reset`]})]})]}),(0,H.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden rounded-b-2xl lg:rounded-b-3xl`,children:n})]})}function FH(){return Ow.of(async()=>{let[e,t,n]=await Promise.all([X.getAllTagTypes(),X.getAllTags(),UH()]);return{types:e.map(e=>e.name),tags:t,efforts:n.efforts.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]})),equipment:n.equipment.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]}))}})}var IH=null;function LH(e,t,n){return Cz(e===`effort`?{id:t,kind:`effort`,sourceCatalog:`efforts`,sourceItem:t,title:n,date:null,effort:{slug:t,label:n}}:{id:t,kind:`equipment`,sourceCatalog:`equipment`,sourceItem:t,title:n,date:null})}function RH(e){return{resolve:(t,n)=>e.resolve(t,n),resolveEffort:t=>e.resolveEffort(t),resolveEquipment:t=>e.resolveEquipment(t),openHref:(e,t)=>LH(e,t,t),createHref:e=>e===`effort`?`/e/new?mode=create`:`/equipment/new?mode=create`}}function zH(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 BH(){let e=IE(),t=fk();if(!e.isInitialized()||!t.isInitialized())return null;let n={efforts:[...e.list()],equipment:[...t.list()]},r=zH(n);if(!IH||IH.signature!==r){let e=kc(n);IH={index:e,provider:RH(e),signature:r}}return IH.provider}function VH(){return BH(),IH?.index??null}function HH(){let e=Vr.fromClass(class{view;channel=null;onSeed=()=>{this.view.dispatch({effects:Aw.of(null)})};constructor(e){this.view=e,typeof BroadcastChannel<`u`&&(this.channel=new BroadcastChannel(z_),this.channel.onmessage=this.onSeed)}destroy(){this.channel?.close()}});return[kw.of(BH),e]}async function UH(){return{efforts:[...IE().list()],equipment:[...fk().list()]}}function WH(e){let{meta:t}=s_(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 GH(e,t){return{id:`reference:${e}`,label:e===`effort`?`Effort`:`Equipment`,search:async n=>{let r=await UH(),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 KH(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 qH(e){let t=KH(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 JH(e,t){let n=qH(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 YH(e,t){return t||(e.current||=new Mj,e.current)}function XH(e,t){return Er.domEventHandlers({drop:(n,r)=>{let i=n.dataTransfer?.files;if(!i||i.length===0)return!1;n.preventDefault();let a=r.posAtCoords({x:n.clientX,y:n.clientY});return a!==null&&(Array.from(i).forEach(async n=>{let i=C(),o=new FileReader;o.onload=async()=>{let s=o.result;if(e)try{await t.mutateNote(e,{attachments:{add:[{id:i,file:new File([s],n.name,{type:n.type})}]}})}catch(e){uF(`NoteEditor`,`Attachment persist skipped:`,e)}let c=`\n${n.type.startsWith(`image/`)?`!`:``}[${n.name}](${i})\n`;r.dispatch({changes:{from:a,insert:c},selection:{anchor:a+c.length}})},o.readAsArrayBuffer(n)}),!0)}})}function ZH(e){let t=e?.split(`:`,1)[0];return t===`time`||t===`log`?Ls:null}var QH={[G.Duration]:`cm-metric-underline-duration`,[G.Rep]:`cm-metric-underline-rep`,[G.Effort]:`cm-metric-underline-effort`,[G.Rounds]:`cm-metric-underline-rounds`,[G.Distance]:`cm-metric-underline-distance`,[G.Resistance]:`cm-metric-underline-resistance`,[G.Action]:`cm-metric-underline-action`};function $H(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=VH();return r?Is({references:r,defaults:WH(t.doc.toString())}).read(n,e.sport).statements:Is().read(n,e.sport).statements}catch{return null}}function eU(e,t,n,r){let i=[];for(let a of e){if(a.contentFrom===void 0||a.contentTo===void 0)continue;let e=$H(a,r);if(e)for(let o of e){let e=a.startLine+(o.meta?.line??0),s=t===a&&e===n;for(let e of o.metrics){let t=QH[e.type===G.Choice?e.alternatives[0]?.type:e.type];if(!t)continue;let n=o.metricMeta?.get(e);if(!n)continue;let c=a.contentFrom+n.startOffset,l=a.contentFrom+n.endOffset;if(!Number.isFinite(c)||!Number.isFinite(l)||c>=l||c<0||l>r.doc.length)continue;let u=s?t:`${t}-dim`;i.push(Br.mark({class:u}).range(c,l))}}}return i.sort((e,t)=>e.from-t.from),Br.set(i)}function tU(e){let{sections:t}=e.field(ZC),{head:n}=e.selection.main,r=e.doc.lineAt(n).number,i=t.filter(e=>e.type===`time`||e.type===`log`),a=i.find(e=>r>=e.startLine+1&&r<e.endLine)??null,o=null,s=null,c=-1,l=null;if(a){let t=e.doc.line(r);l=$H(a,e);let i=r-a.startLine;c=l?.findIndex(e=>e.meta?.line===i&&e.metrics.some(t=>{let r=e.metricMeta.get(t),i=n-(a.contentFrom??0);return r&&i>=r.startOffset&&i<=r.endOffset}))??-1,c<0&&(c=l?.findIndex(e=>e.meta?.line===i)??-1),s=c>=0&&l?l[c]:null,o={sectionId:a.id,section:a,statement:s,statementIndex:c,cursorLine:r,docLine:r,lineFrom:t.from,lineTo:t.to,focusedMetric:null,focusedMetricIndex:-1,allStatements:l??[]}}let u=null,d=-1;if(a&&s&&a.contentFrom!==void 0)for(let e=0;e<s.metrics.length;e++){let t=s.metrics[e];if(t.type===G.Sound||t.type===G.System)continue;let r=s.metricMeta?.get(t);if(!r)continue;let i=a.contentFrom+r.startOffset,o=a.contentFrom+r.endOffset;if(n>=i&&n<=o){u=t,d=e;break}}o&&(o.focusedMetric=u,o.focusedMetricIndex=d);let f=eU(i,a,r,e);return{focus:o,decos:f}}var nU=si.define({create(e){return tU(e)},update(e,t){return t.effects.some(e=>e.is(Aw))?tU(t.state):!t.docChanged&&t.startState.selection.eq(t.state.selection)?e:tU(t.state)},provide:e=>Er.decorations.from(e,e=>e.decos)});function rU(e){try{return e.field(nU).focus}catch{return null}}function iU(e,t){let n=rU(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=$H(r,e.state)??[],s=[];for(let e of o)for(let t of e.metrics){if(t.type===G.Sound||t.type===G.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 aU=fi.high(yr.of([{key:`Ctrl-ArrowRight`,run:e=>iU(e,1)},{key:`Ctrl-ArrowLeft`,run:e=>iU(e,-1)}])),oU=[nU,Er.baseTheme({".cm-metric-underline-duration":{borderBottom:`2px solid hsl(var(--metric-time))`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep":{borderBottom:`2px solid hsl(var(--metric-rep))`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort":{borderBottom:`2px solid hsl(var(--metric-effort))`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds":{borderBottom:`2px solid hsl(var(--metric-rounds))`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance":{borderBottom:`2px solid hsl(var(--metric-distance))`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance":{borderBottom:`2px solid hsl(var(--metric-resistance))`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action":{borderBottom:`2px solid hsl(var(--metric-action))`,color:`hsl(var(--metric-action))`},".cm-metric-underline-duration-dim":{borderBottom:`2px solid hsl(var(--metric-time) / 0.2)`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep-dim":{borderBottom:`2px solid hsl(var(--metric-rep) / 0.2)`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort-dim":{borderBottom:`2px solid hsl(var(--metric-effort) / 0.2)`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds-dim":{borderBottom:`2px solid hsl(var(--metric-rounds) / 0.2)`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance-dim":{borderBottom:`2px solid hsl(var(--metric-distance) / 0.2)`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance-dim":{borderBottom:`2px solid hsl(var(--metric-resistance) / 0.2)`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action-dim":{borderBottom:`2px solid hsl(var(--metric-action) / 0.2)`,color:`hsl(var(--metric-action))`}}),aU],sU={frontmatter:120,code:60,widget:220,embed:180},cU={frontmatter:280,code:140,widget:220,embed:280},lU=({view:e,widths:t,activeSectionId:n,renderSlot:r,cursorLine:i})=>{let a=(0,V.useRef)(null),o=(0,V.useRef)(null),[s,c]=(0,V.useState)(()=>e?.plugin(hw)?.rects??[]),[l,u]=(0,V.useState)(0),[d,f]=(0,V.useState)({left:0,right:0}),[p,m]=(0,V.useState)(()=>e?.plugin(hw)?.docVersion??0),[h,g]=(0,V.useState)(void 0),[_,v]=(0,V.useState)(void 0);(0,V.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,V.useEffect)(()=>{if(!e)return;let t=e.plugin(hw);if(t)return t.addListener((e,t)=>{c(e),m(t)})},[e]),(0,V.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,V.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(hw)?.rects??[]).filter(e=>{let n=t.get(e.sectionId);return n&&n.effectiveWidth>0});return!e||y.length===0?null:(0,H.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,H.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?cU:sU)[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,H.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)})})})},uU={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 dU(e,t=uU){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 fU(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 pU={typeOverrides:{},sectionOverrides:{}};function mU(e,t,n=uU){let[r,i]=(0,V.useReducer)(fU,pU);return{widths:(0,V.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=dU({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,V.useCallback)((e,t)=>i({type:`SET_SECTION_WIDTH`,sectionId:e,width:t}),[]),setTypeWidth:(0,V.useCallback)((e,t)=>i({type:`SET_TYPE_WIDTH`,sectionType:e,width:t}),[]),clearSectionOverride:(0,V.useCallback)(e=>i({type:`CLEAR_SECTION_OVERRIDE`,sectionId:e}),[])}}function hU(e,t){let{sections:n}=e.state.field(ZC);return n.find(e=>e.id===t)}function gU(e,t){return t.contentFrom===void 0||t.contentTo===void 0?``:e.state.doc.sliceString(t.contentFrom,t.contentTo)}var _U=({props:e,isActive:t})=>{let n=e.source_url||e.website||``,r=e.title||e.label||`Link`,i=!t;return(0,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,H.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,H.jsx)(`span`,{className:`truncate text-xs font-medium`,children:r})]}),(0,H.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,H.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.`})]})},vU=({sectionId:e,section:t,view:n,isActive:r})=>{let i=(0,V.useMemo)(()=>t||hU(n,e),[n,e,t]),a=i?gU(n,i):``,o=(0,V.useMemo)(()=>Nb(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=Pb(t);if(e)return(0,H.jsx)(yU,{videoId:e,title:n,isActive:r})}return(0,H.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,H.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,H.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,H.jsx)(`span`,{className:`text-xs font-medium truncate`,children:n||`Untitled`})]}),(0,H.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mb-3`,children:t}),i.embed.isImage&&(0,H.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=Pb(c);if(e)return(0,H.jsx)(yU,{videoId:e,title:o.title||`YouTube Video`,isActive:r})}return o.source_url||o.website||s===`strava`?(0,H.jsx)(_U,{props:o,isActive:r}):null},yU=({videoId:e,title:t,isActive:n})=>(0,H.jsxs)(`div`,{className:U(`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,H.jsx)(`div`,{className:`relative flex-1 min-h-0`,children:(0,H.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,H.jsx)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground truncate border-t border-border bg-popover/90`,children:t})]});function bU(e,t,n,r){let[i,a]=(0,V.useState)([]),[o,s]=(0,V.useState)(!0),c=wF(e=>e.currentEntry),l=wF(e=>e.getNote),u=n??c?.extendedResults;return(0,V.useEffect)(()=>{if(!e||!t){a([]),s(!1);return}let n=!1;async function r(){if(Array.isArray(u)){let r=u.filter(n=>n.noteId===e&&n.blockId===t);if(r.length>0&&!n){a(r.sort((e,t)=>t.createdAt-e.createdAt)),s(!1);return}}if(typeof l!=`function`){n||(a([]),s(!1));return}try{let r=await l(e,{projection:`history-detail`,resultSelection:{mode:`all-for-section`,blockId:t}});n||a((r?.extendedResults??[]).sort((e,t)=>t.createdAt-e.createdAt))}catch{n||a([])}finally{n||s(!1)}}return r(),()=>{n=!0}},[e,t,u,l,r]),{results:i,loading:o}}function xU(e){let t=e.metrics?.find(e=>e.type===G.Elapsed);return t?.value!==void 0&&typeof t.value==`number`?t.value:0}function SU(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+xU(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 CU(e,t){return(0,V.useMemo)(()=>{if(t===void 0||e.length===0)return null;let n=SU(e,t);return n.resultCount>0?n:null},[e,t])}function wU(e,t){if(t){t(e.action,e);return}e.action.type===`call`&&e.action.handler()}var TU=({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,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:()=>wU(e,o),className:U(`flex items-center gap-2 transition-colors active:scale-95`,n===`xs`&&`gap-0 sm:gap-2`,l?U(`bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest`,f):U(`hover:bg-accent hover:text-accent-foreground text-muted-foreground font-medium`,u)),children:[s&&(0,H.jsx)(s,{className:U(`shrink-0`,l?`size-4 fill-current sm:size-3`:`size-4 sm:h-4 sm:w-4`)}),(0,H.jsx)(`span`,{className:a,children:e.label})]}),(0,H.jsx)(`div`,{className:U(`self-stretch`,l?`w-px bg-primary-foreground/20 my-2 sm:my-1`:`w-px bg-border/60`)}),(0,H.jsx)(`button`,{type:`button`,title:t.label,"aria-label":t.label,onClick:()=>wU(t,o),className:U(`flex items-center justify-center transition-colors active:scale-95`,l?U(`bg-primary text-primary-foreground hover:bg-primary/90`,p):U(`hover:bg-accent hover:text-accent-foreground text-muted-foreground`,d)),children:c?(0,H.jsx)(c,{className:U(`shrink-0`,l?`size-4 sm:size-3.5`:`size-4 sm:h-4 sm:w-4`)}):(0,H.jsx)(`span`,{className:`sr-only`,children:t.label})})]})},EU=new Fs;function DU(e,t){let{sections:n}=e.state.field(ZC);return n.find(e=>e.id===t)??null}function OU(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 EU.read(n,t.sport).statements}catch{return[]}}function kU(e,t,n){if(!e.length)return null;let r=n-t.startLine;return e.find(e=>e.meta?.line===r)??null}function AU(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 jU={[G.Duration]:{label:`Timer`,icon:`⏱`,color:`bg-metric-time/10 text-metric-time`},[G.Rep]:{label:`Reps`,icon:`✕`,color:`bg-metric-rep/10 text-metric-rep`},[G.Effort]:{label:`Exercise`,icon:`🏋`,color:`bg-metric-effort/10 text-metric-effort`},[G.Rounds]:{label:`Rounds`,icon:`↻`,color:`bg-metric-rounds/10 text-metric-rounds`},[G.Distance]:{label:`Distance`,icon:`📏`,color:`bg-metric-distance/10 text-metric-distance`},[G.Resistance]:{label:`Weight`,icon:`⚖`,color:`bg-metric-resistance/10 text-metric-resistance`},[G.Action]:{label:`Action`,icon:`⚡`,color:`bg-metric-action/10 text-metric-action`}};function MU(e){return e.metrics.filter(e=>e.type!==G.Sound&&e.type!==G.System).map(e=>{let t=jU[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 NU=({summary:e})=>{let t=e.entries.slice(0,3);return(0,H.jsxs)(`div`,{className:`px-3 py-2 border-t border-border/30 bg-muted/20`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1.5`,children:[(0,H.jsx)(S,{className:`h-3 w-3 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`text-[10px] font-semibold text-muted-foreground uppercase tracking-wider`,children:`History`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-muted-foreground`,children:[e.totalHits,`× across `,e.resultCount,` run`,e.resultCount===1?``:`s`]})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t.map(e=>(0,H.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,H.jsx)(`span`,{className:`font-mono font-medium text-foreground`,children:AU(e.elapsedMs)}),e.hitCount>1&&(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[`×`,e.hitCount]}),(0,H.jsx)(`span`,{className:`text-muted-foreground/60`,children:HP(new Date(e.createdAt))})]},e.createdAt)),e.entries.length>3&&(0,H.jsxs)(`span`,{className:`text-[10px] text-muted-foreground self-center`,children:[`+`,e.entries.length-3,` more`]})]})]})};function PU(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 FU(e){return function({className:t}){return V.isValidElement(e)?V.cloneElement(e,{className:U(e.props.className,t)}):(0,H.jsx)(`span`,{className:U(`flex items-center`,t),children:e})}}var IU=({cmd:e,block:t})=>{let[n,r]=(0,V.useState)(!1),i=(0,V.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),a=(0,V.useMemo)(()=>FU(e.icon),[e.icon]),o=(0,V.useMemo)(()=>FU(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),s=(0,V.useMemo)(()=>({id:e.id,label:e.label,icon:a,action:{type:`call`,handler:()=>e.onClick(t)}}),[e,t,a]),c=(0,V.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:o,action:{type:`call`,handler:i}}),[e.id,o,i]),l=(0,V.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);return e.onSplitClick?(0,H.jsx)(`div`,{onClick:l,onMouseDown:l,onPointerDown:l,children:(0,H.jsx)(TU,{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,H.jsxs)(W,{variant:e.primary?`default`:`secondary`,className:U(`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`),title:e.label,"aria-label":e.label,onClick:n=>{l(n),e.onClick(t)},onMouseDown:l,onPointerDown:l,children:[(0,H.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:e.icon}),(0,H.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})},LU=({commands:e,section:t,view:n,compact:r})=>{if(!e.length)return null;let i=PU(n,t);return r?(0,H.jsx)(`div`,{className:`flex flex-row items-center gap-1 p-0 sm:p-1.5`,children:e.map(e=>(0,H.jsx)(IU,{cmd:e,block:i},e.id))}):(0,H.jsx)(`div`,{className:`flex items-center gap-1.5 p-2 border-t border-border/50 flex-wrap`,children:e.map(e=>(0,H.jsx)(IU,{cmd:e,block:i},e.id))})},RU=({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,V.useMemo)(()=>DU(n,t),[n,t,u]),{results:h}=bU(p,t,f,m?.contentId),g=(0,V.useMemo)(()=>m?OU(n,m):[],[n,m?.id,u]),_=V.useRef(null),v=m&&a!==void 0&&a>=m.startLine&&a<=m.endLine;v&&a!==void 0&&(_.current=a);let y=v?a:s?_.current??null:null,b=r?i:y??i,x=!(m&&(b===m.startLine||b===m.endLine))&&(r||y!==null),S=(0,V.useMemo)(()=>m&&x?kU(g,m,b):null,[m,b,x,g]),C=(0,V.useMemo)(()=>S?g.filter(e=>e.meta?.line===S.meta.line).flatMap(MU):[],[S,g]),w=CU(h,S?.meta?.line);if(!m)return null;let T=S?.meta?.raw??``,E=b-m.startLine,D=typeof window<`u`&&window.matchMedia(`(max-width: 639px)`).matches?44:28,O;if(c!==void 0){let e=c-l.top-100,t=o+D+4,n=l.height-200;O=Math.max(t,Math.min(e,Math.max(t,n)))}else O=o+D+4;return(0,H.jsxs)(`div`,{className:`relative w-full h-full`,style:{pointerEvents:`none`},children:[(0,H.jsx)(`div`,{className:`absolute inset-x-0 flex items-center justify-end gap-1 px-2 pointer-events-auto
155
+ bg-background/70 backdrop-blur-sm border-l border-b border-border/40 rounded-bl-md`,style:{top:o,height:D},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h.length>0&&(0,H.jsxs)(H.Fragment,{children:[(0,H.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,H.jsx)(ee,{className:`h-3 w-3`}),(0,H.jsx)(`span`,{children:h.length})]}),(0,H.jsx)(`div`,{className:`h-3 w-[1px] bg-border/40 mx-0.5`})]}),(0,H.jsx)(LU,{commands:d,section:m,view:n,compact:!0})]})}),x&&(0,H.jsxs)(`div`,{className:`absolute inset-x-0 flex flex-col bg-popover/95 backdrop-blur-md
156
+ border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:O,maxHeight:200},children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,H.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,H.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,H.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,E]}),(0,H.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,H.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:T,children:T||(0,H.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,H.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:C.length>0?(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:C.map((e,t)=>(0,H.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,H.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,H.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,H.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),w&&(0,H.jsx)(NU,{summary:w}),(0,H.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,H.jsx)(LU,{commands:d,section:m,view:n})})]})]})},zU=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,V.useMemo)(()=>{let t=n.state.field(ZC).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,H.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,H.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,H.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,H.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,H.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})};function BU(e,t,n,r,i){switch(t.type){case`fixed-field`:return VU(e,t);case`metric-type`:return HU(e,t);case`derived`:return UU(e,t,n,r,i);case`fallback`:return WU(e,t,n,r,i);default:return}}function VU(e,t){return e[t.field]}function HU(e,t){return e.cells.get(t.metricType)}function UU(e,t,n,r,i){let a=new Map;if(t.dependencies&&r)for(let o of t.dependencies){if(i?.includes(o))throw Error(`Circular dependency detected in column '${o}': ${(i??[]).join(` -> `)} -> ${o}`);let t=r.get(o);if(t){let s=BU(e,t.source,n,r,[...i??[],o]);a.set(o,s)}}let o={...n,allRows:n?.allRows??[e],rowIndex:n?.rowIndex??0,columnDef:n?.columnDef??{id:`unknown`,label:``,source:t,format:{type:`text`}},dependencies:a,...t.context};return t.compute(e,o)}function WU(e,t,n,r,i){return GU(e,t,n,r,i)}function GU(e,t,n,r,i){if(!(!t.sources||t.sources.length===0))switch(t.semantics){case`first-present`:return KU(e,t.sources,n,r,i);case`all-present-joined`:return qU(e,t.sources,t.joinString,n,r,i);case`all-present-combined`:return JU(e,t.sources,n,r,i);default:return}}function KU(e,t,n,r,i){for(let a of t){let t=BU(e,a,n,r,i);if(t!=null)return t}}function qU(e,t,n,r,i,a){let o=[];for(let n of t){let t=BU(e,n,r,i,a);if(t==null)return;o.push(t)}let s=n??` `;return o.map(e=>XU(e)).join(s)}function JU(e,t,n,r,i){let a=[];for(let o of t){let t=BU(e,o,n,r,i);if(t==null)return;a.push(t)}return a}function YU(e){if(e==null)return``;let t=Array.isArray(e)?e:e instanceof K?e.toArray():[];if(t.length===0)return``;let n=t[0];if(typeof n==`object`&&n){if(`image`in n&&typeof n.image==`string`)return n.image;if(`value`in n&&n.value!==void 0)return String(n.value)}return String(n)}function XU(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`&&`metrics`in e){let t=YU(e.metrics);if(t.length>0)return t}return String(e)}function ZU(e,t,n,r){if(!t.sort)return``;let i=BU(e,t.source,n,r);return(t.sort.type===`custom`?typeof i==`number`||typeof i==`string`?i:String(i??``):t.sort.extractor(i))??``}function QU(e,t){if(typeof e==`number`&&typeof t==`number`)return Number.isNaN(e)&&Number.isNaN(t)?0:Number.isNaN(e)?1:Number.isNaN(t)?-1:e-t;let n=String(e??``),r=String(t??``),i=parseFloat(n),a=parseFloat(r);return!Number.isNaN(i)&&!Number.isNaN(a)&&n===String(i)&&r===String(a)?i-a:n.localeCompare(r)}function $U(e,t,n,r){if(!t.graph)return;let i=BU(e,t.source,n,r);return t.graph.extractor(i)}function eW(e,t,n,r){if(!t.filter)return``;let i=BU(e,t.source,n,r);return t.filter.extractor(i)??``}function tW(e,t,n,r,i){if(!n||n.trim().length===0||!t.filter)return!0;let a=eW(e,t,r,i),o=t.filter.caseInsensitive===!1?n.trim():n.trim().toLowerCase(),s=t.filter.caseInsensitive===!1?a:a.toLowerCase();return t.filter.matcher?t.filter.matcher(s,o):s.includes(o)}var nW=({metric:e})=>{let t=e.origin===`hinted`||e.image===`?`,n=(0,V.useMemo)(()=>PB(_o.present(e,`review-grid-cell`)),[e]);return(0,H.jsxs)(`span`,{className:[`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium border transition-all`,t?`bg-warning/10 border-warning/40 text-warning animate-pulse-opacity`:`${n.colorClasses} ${n.originClasses}`].join(` `),title:t?`Missing value - click to fill`:n.tooltip,children:[t&&(0,H.jsx)(`span`,{className:`mr-0.5 text-[10px]`,children:`◉`}),n.label,n.userEntered&&!t&&(0,H.jsx)(`span`,{className:`text-[10px] opacity-70 ml-0.5`,children:`👤`})]})},rW=({columnDef:e,row:t,allRows:n,rowIndex:r,indent:i=0,onDoubleClick:a,className:o,style:s,definitionMap:c})=>{let l=(0,V.useRef)(null),u=(0,V.useMemo)(()=>{if(!(!n||r===void 0))return{allRows:n,rowIndex:r,columnDef:e,dependencies:new Map}},[n,r,e]),d=(0,V.useMemo)(()=>BU(t,e.source,u,c),[t,e.source,u,c]),f=e.source.type===`metric-type`,p=(0,V.useCallback)(n=>{if(n.stopPropagation(),f&&a&&l.current){let n=l.current.getBoundingClientRect();a(t.sourceBlockKey,e.source.metricType,n)}},[f,e.source,t.sourceBlockKey,a]),m=(0,V.useMemo)(()=>iW(d,e.format,i,t),[d,e.format,i,t]);return(0,H.jsx)(`td`,{ref:l,className:U(`py-1 px-2`,f&&`cursor-cell`,o),style:s,onDoubleClick:p,children:m})};function iW(e,t,n,r){if(e==null)return(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[_W(n),(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]});switch(t.type){case`text`:return aW(e,t,n);case`time`:return oW(e,t);case`number`:return sW(e,t);case`badge`:return cW(e,t);case`pill`:return lW(e,t);case`combined`:return dW(e,t,n);case`custom`:return pW(e,t,r);default:return hW(e,n)}}function aW(e,t,n){let r=t.transform?t.transform(e):vW(e);return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center gap-1`,t.className),children:[_W(n),r]})}function oW(e,t){let n=yW(e);if(n==null||!Number.isFinite(n))return(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r;switch(t.style){case`long`:r=Zz(n);break;case`precise`:r=`${n.toFixed(2)}s`;break;default:r=Xz(n)}return t.transform&&(r=t.transform(r)),(0,H.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:r})}function sW(e,t){let n=yW(e);if(n==null||!Number.isFinite(n))return(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r=t.decimals??0,i=n.toFixed(r)+(t.unit??``);return t.transform?(0,H.jsx)(`span`,{children:t.transform(i)}):(0,H.jsx)(`span`,{children:i})}function cW(e,t){let n=t.styleResolver(e),r=t.textResolver(e);return(0,H.jsxs)(`span`,{className:U(`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium`,n.className),title:n.title,children:[n.icon&&(0,H.jsx)(`span`,{className:`mr-0.5`,children:n.icon}),r]})}function lW(e,t){let n=t.transform?t.transform(e):vW(e),r=t.backgroundColor??`bg-muted`,i=t.borderRadius??`rounded`;return(0,H.jsx)(`span`,{className:U(`inline-block px-1.5 py-0.5 text-xs font-medium`,r,i),children:n})}var uW={primary:`text-sm font-semibold text-foreground`,secondary:`text-xs text-muted-foreground`,tertiary:`text-[11px] text-muted-foreground opacity-80`};function dW(e,t,n,r){let[i,a,o]=Array.isArray(e)?e:[e],s=i===void 0?null:fW(i,t.primaryFormat??{type:`text`},r,`primary`),c=a===void 0?null:fW(a,t.secondaryFormat??{type:`text`},r,`secondary`),l=o===void 0?null:fW(o,t.tertiaryFormat??{type:`text`},r,`tertiary`),u=t.layout===`horizontal`;return(0,H.jsxs)(`div`,{className:U(`inline-flex`,u?`flex-row items-center gap-1`:`flex-col items-start gap-0.5`,t.containerClassName),children:[_W(n),s,c&&(0,H.jsxs)(H.Fragment,{children:[u&&t.separator&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),c]}),l&&(0,H.jsxs)(H.Fragment,{children:[u&&t.separator&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),l]})]})}function fW(e,t,n,r){let i=iW(e,t,0,n);return r?(0,H.jsx)(`span`,{className:U(`inline-flex items-center`,uW[r]),children:i}):i}function pW(e,t,n){let r=n?{...t.context,row:n}:t.context;return t.render(e,r)}function mW(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function hW(e,t){return e?.metrics?gW(e,t):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[_W(t),vW(e)]})}function gW(e,t){let n=mW(e);return n.length===0?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[_W(t),(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]}):(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1 items-center`,children:[_W(t),n.map((e,t)=>(0,H.jsx)(nW,{metric:e},t))]})}function _W(e){return e<=0?null:(0,H.jsx)(`div`,{className:`flex-shrink-0 mr-1 border-l-2 border-muted h-4`,style:{width:`${e*1.25}rem`,marginLeft:`2px`}})}function vW(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);let t=mW(e);if(t.length>0){let e=t[0];if(e?.image)return e.image;if(e?.value!==void 0)return String(e.value)}return String(e)}function yW(e){if(e==null)return;if(typeof e==`number`)return e;if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}let t=mW(e);if(t.length>0&&typeof t[0]?.value==`number`)return t[0].value}var bW=e=>e;function xW(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function SW(e){let t=xW(e);if(t.length===0)return;let n=t[0];return typeof n?.value==`number`?n.value:n?.image?n.image:String(n?.value??``)}function CW(e){let t=xW(e);for(let e of t)if(typeof e?.value==`number`)return e.value}function wW(e){return xW(e).map(e=>e.image??String(e.value??``)).join(`, `)}function TW(e){return e==null?``:Array.isArray(e)?e.map(e=>TW(e)).filter(Boolean).join(` — `):typeof e==`string`?e:typeof e==`number`?String(e):wW(e)}function EW(e){switch(e){case G.Duration:case G.Rep:case G.Distance:case G.Rounds:case G.Resistance:case G.Increment:case G.Metric:case G.Volume:case G.Intensity:case G.Load:case G.Work:case G.CurrentRound:case G.Calculated:return!0;default:return!1}}function DW(e){switch(e){case G.Duration:return`s`;case G.Rep:return`reps`;case G.Distance:return`m`;case G.Rounds:return`rounds`;case G.Resistance:return`kg`;case G.Increment:return`Δ`;case G.Calculated:case G.Custom:return``;default:return``}}function OW(e,t){let n=po(e),r=gB(e)??void 0,i=t?.graphable??EW(e);return{id:e,label:n,icon:r,source:{type:`metric-type`,metricType:e},format:{type:`custom`,render:e=>gW(e,0)},sort:EW(e)?{type:`numeric`,extractor:e=>CW(e)}:{type:`text`,extractor:e=>{let t=SW(e);return t===void 0?void 0:String(t)}},graph:i?{extractor:e=>CW(e),axisLabel:n,unit:DW(e)}:void 0,filter:{extractor:e=>wW(e),caseInsensitive:!0},meta:{defaultVisible:t?.defaultVisible??!0,debugOnly:t?.debugOnly,tags:[e]}}}function kW(e){switch(e){case`segment`:return`bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-200`;case`milestone`:return`bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-200`;case`system`:return`bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400`;case`event`:return`bg-purple-100 text-purple-800 dark:bg-purple-900/50 dark:text-purple-200`;case`group`:return`bg-indigo-100 text-indigo-800 dark:bg-indigo-900/50 dark:text-indigo-200`;case`load`:return`bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-200`;case`compiler`:return`bg-pink-100 text-pink-800 dark:bg-pink-900/50 dark:text-pink-200`;default:return`bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300`}}function AW(e,t){if(!e||e.length===0)return``;let n=e=>Xz(e);if(t===0)return n(e[0].started);let r=n(e[0].started),i=e[e.length-1];if(i.ended===void 0)return r;let a=n(i.ended);return r===a?r:`${r} — ${a}`}function jW(e,t=!0){if(e===void 0||e===0)return``;let n=new Date(e),r=n.getHours().toString().padStart(2,`0`),i=n.getMinutes().toString().padStart(2,`0`),a=n.getSeconds().toString().padStart(2,`0`);return t?`${r}:${i}:${a}.${n.getMilliseconds().toString().padStart(3,`0`)}`:`${r}:${i}:${a}`}function MW({value:e}){let t=e.match(/^(-?)(\d+)(:\d{2})(?::\d{2})?(\.\d+)?$/);if(!t)return(0,H.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:e});let[,n,r,i,a,o]=t,s=i.slice(1);return(0,H.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap inline-flex items-baseline`,children:[n&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:n}),(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:r}),(0,H.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`:`,s]}),a&&(0,H.jsx)(`span`,{className:`text-muted-foreground/40`,children:a}),o&&(0,H.jsx)(`span`,{className:`text-muted-foreground/30 text-[10px]`,children:o})]})}function NW({elapsed:e,duration:t}){let n=Xz(e);return(0,H.jsxs)(`span`,{className:`inline-flex items-baseline gap-0.5`,children:[(0,H.jsx)(MW,{value:n}),t!==void 0&&t>0&&t!==e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-muted-foreground/40 mx-0.5`,children:`/`}),(0,H.jsx)(`span`,{className:`opacity-60`,children:(0,H.jsx)(MW,{value:Xz(t)})})]})]})}var PW={id:`#`,label:`#`,source:{type:`derived`,compute:e=>({index:e.index,outputType:e.outputType,sourceBlockKey:e.sourceBlockKey})},format:{type:`custom`,render:e=>{let{index:t,outputType:n,sourceBlockKey:r}=e??{};return(0,H.jsx)(`span`,{className:U(`font-mono text-[11px] w-8 text-right inline-block`,kW(n)),title:`Type: ${n}\nBlock: ${r}`,children:t})}},sort:{type:`numeric`,extractor:e=>bW(e)?.index||0},meta:{tags:[`layout`],defaultVisible:!0,width:`40px`,resizable:!1}},FW={id:`timestamp`,label:`Timestamp`,source:{type:`fixed-field`,field:`absoluteStartTime`},format:{type:`custom`,render:(e,t)=>{let n=e,r=bW(t)?.hideMs!==!1;return(0,H.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-24 whitespace-nowrap`,children:jW(n,r)})},context:{hideMs:!1}},sort:{type:`numeric`,extractor:e=>bW(e)?.absoluteStartTime??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},IW={id:`spans`,label:`Time`,source:{type:`derived`,compute:e=>({spans:e.spans,duration:e.duration})},format:{type:`custom`,render:e=>{let{spans:t,duration:n}=e??{};return(0,H.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-40 whitespace-nowrap`,children:AW(t,n)})}},sort:{type:`numeric`,extractor:e=>(bW(e)?.spans)?.[0]?.started??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},LW={id:`timeSpan`,label:`Time`,source:{type:`derived`,compute:e=>({timestamp:e.absoluteStartTime,elapsed:e.elapsed,duration:e.duration})},format:{type:`custom`,render:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{};return n===void 0?(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`}):(0,H.jsxs)(`div`,{className:`flex flex-col items-start gap-0 leading-tight`,children:[t!==void 0&&t>0&&(0,H.jsx)(`span`,{className:`text-muted-foreground/50 font-mono text-[10px] whitespace-nowrap`,children:jW(t,!1)}),(0,H.jsx)(NW,{elapsed:n,duration:r})]})}},sort:{type:`numeric`,extractor:e=>bW(e)?.elapsed??0},graph:{extractor:e=>bW(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`},filter:{extractor:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{},i=[];return t!==void 0&&t>0&&i.push(jW(t,!1)),n!==void 0&&i.push(Xz(n)),r!==void 0&&r>0&&r!==n&&i.push(Xz(r)),i.join(` `)},caseInsensitive:!0},meta:{tags:[`timing`,`compound`],defaultVisible:!0,width:`100px`,subsumes:[`duration`,`elapsedTotal`]}},RW={id:`blockKey`,label:`Block`,source:{type:`fixed-field`,field:`sourceBlockKey`},format:{type:`text`,className:`truncate max-w-[160px] text-sm`},sort:{type:`text`,extractor:e=>bW(e)?.sourceBlockKey??``},filter:{extractor:e=>bW(e)?.sourceBlockKey??``,caseInsensitive:!0},meta:{tags:[`layout`],defaultVisible:!1}},zW={id:`outputType`,label:`Type`,source:{type:`fixed-field`,field:`outputType`},format:{type:`custom`,render:e=>{let t=String(e??``);return(0,H.jsx)(`span`,{className:U(`text-xs px-1.5 py-0.5 rounded font-medium`,kW(t)),children:t})}},sort:{type:`text`,extractor:e=>bW(e)?.outputType??``},filter:{extractor:e=>bW(e)?.outputType??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1}},BW={id:`stackLevel`,label:`Depth`,source:{type:`fixed-field`,field:`stackLevel`},format:{type:`text`,className:`text-muted-foreground font-mono text-xs text-center w-12`},sort:{type:`numeric`,extractor:e=>bW(e)?.stackLevel??0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},VW={id:`elapsedTotal`,label:`Elapsed`,source:{type:`derived`,compute:e=>({elapsed:e.elapsed,total:e.total})},format:{type:`custom`,render:e=>{let{elapsed:t,total:n}=e??{};if(t===void 0||n===void 0)return``;let r=t===n?Xz(t):`${Xz(t)} / ${Xz(n)}`;return(0,H.jsx)(`span`,{className:`text-foreground font-mono text-xs text-right w-32 whitespace-nowrap`,children:r})}},sort:{type:`numeric`,extractor:e=>bW(e)?.elapsed??0},graph:{extractor:e=>bW(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`,color:`#14b8a6`},meta:{tags:[`timing`],defaultVisible:!1}},HW={id:`completionReason`,label:`Reason`,source:{type:`fixed-field`,field:`completionReason`},format:{type:`text`,className:`text-muted-foreground text-xs truncate max-w-[120px]`},sort:{type:`text`,extractor:e=>bW(e)?.completionReason??``},filter:{extractor:e=>bW(e)?.completionReason??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},UW=OW(G.Effort,{defaultVisible:!1}),WW=OW(G.Duration,{debugOnly:!0}),GW=OW(G.Rep),KW=OW(G.Rounds,{defaultVisible:!1}),qW=OW(G.Distance),JW=OW(G.Resistance),YW=OW(G.Action),XW=OW(G.Increment),ZW=OW(G.Metric),QW=OW(G.Calculated),$W=OW(G.Custom,{defaultVisible:!1}),eG=OW(G.Group,{defaultVisible:!1}),tG=OW(G.System,{defaultVisible:!1}),nG=OW(G.Label,{defaultVisible:!1}),rG=OW(G.Text),iG=OW(G.CurrentRound,{defaultVisible:!1}),aG=OW(G.Volume),oG=OW(G.Intensity),sG=OW(G.Load),cG=OW(G.Work),lG=[PW,LW,FW,IW,RW,zW,BW,VW,HW,{id:`exercise`,label:`Exercise`,icon:gB(G.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`fallback`,semantics:`all-present-combined`,sources:[{type:`metric-type`,metricType:G.Effort},{type:`metric-type`,metricType:G.Text}]},{type:`metric-type`,metricType:G.Text},{type:`metric-type`,metricType:G.Label},{type:`metric-type`,metricType:G.Effort}]},format:{type:`combined`,layout:`vertical`,primaryFormat:{type:`text`,className:`font-medium text-foreground`},secondaryFormat:{type:`text`,className:`text-muted-foreground text-xs`},containerClassName:`items-start`},sort:{type:`text`,extractor:e=>TW(e)},filter:{extractor:e=>TW(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`grouping`,`fallback`,`descriptor`],subsumes:[`effort`,`text`,`label`]}},{id:`descriptor`,label:`Descriptor`,icon:gB(G.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:G.Effort},{type:`metric-type`,metricType:G.Label},{type:`metric-type`,metricType:G.Rounds},{type:`metric-type`,metricType:G.CurrentRound}]},format:{type:`custom`,render:e=>gW(e,0)},sort:{type:`text`,extractor:e=>TW(e)},filter:{extractor:e=>TW(e),caseInsensitive:!0},meta:{defaultVisible:!0,subsumes:[`effort`,`label`,`rounds`,`current-round`]}},UW,rG,nG,WW,{id:`pace`,label:`Pace`,icon:`⏱️`,source:{type:`derived`,dependencies:[`distance`,`duration`],compute:(e,t)=>{let n=CW(t.dependencies.get(`distance`)),r=CW(t.dependencies.get(`duration`));if(!(!n||!r))return n/r}},format:{type:`custom`,render:e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return(0,H.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`});let t=1e3/e;return(0,H.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:[Xz(t),`/km`]})}},sort:{type:`numeric`,extractor:e=>typeof e==`number`?e:void 0},graph:{extractor:e=>typeof e==`number`?e:void 0,axisLabel:`Pace`,unit:`m/s`},filter:{extractor:e=>typeof e!=`number`||!Number.isFinite(e)||e<=0?``:`${Xz(1e3/e)}/km`,caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`endurance`,`derived`]}},GW,KW,qW,JW,YW,XW,ZW,QW,$W,iG,aG,oG,{id:`loadFocus`,label:`Load`,icon:gB(G.Load)??gB(G.Resistance)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:G.Load},{type:`metric-type`,metricType:G.Resistance}]},format:{type:`custom`,render:e=>gW(e,0)},sort:{type:`numeric`,extractor:e=>CW(e)},graph:{extractor:e=>CW(e),axisLabel:`Load`,unit:`kg`},filter:{extractor:e=>wW(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`strength`,`fallback`]}},sG,cG,eG,tG],uG={outputTypes:[`segment`,`milestone`,`group`,`analytics`]},dG={definitions:lG,presets:{default:{label:`Default`,filters:uG,visibleColumnIds:[`#`,`timeSpan`,`descriptor`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`]},debug:{label:`Debug`,filters:{},visibleColumnIds:[`#`,`timeSpan`,`timestamp`,`spans`,`blockKey`,`outputType`,`stackLevel`,`descriptor`,`duration`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`,`group`,`system`,`elapsedTotal`,`completionReason`]},strength:{label:`Strength`,filters:uG,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`rep`,`loadFocus`,`volume`,`intensity`,`load`,`work`,`elapsedTotal`]},endurance:{label:`Endurance`,filters:uG,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`distance`,`duration`,`pace`,`rounds`,`increment`,`work`,`elapsedTotal`]}},defaultPreset:`default`},fG=new class{config;definitionMap;constructor(e){this.config=e,this.definitionMap=new Map(e.definitions.map(e=>[e.id,e]))}getVisibleColumns(e){return this.getOrderedCandidates(e).filter(t=>this.computeVisibility(t.id,e))}getAvailableColumns(e){let t=new Set(this.getVisibleColumns(e).map(e=>e.id));return this.config.definitions.filter(n=>!t.has(n.id)&&this.isColumnAvailable(n,e))}getGraphableColumns(e){return this.getVisibleColumns(e).filter(e=>e.graph!==void 0)}getGraphTaggedColumns(e){let t=e.graphTaggedColumnIds;return!t||t.size===0?[]:this.getVisibleColumns(e).filter(e=>t.has(e.id))}isColumnVisible(e,t){return this.getDefinition(e)?this.computeVisibility(e,t):!1}getDefinition(e){return this.definitionMap.get(e)}getPreset(e){return this.config.presets[e]??this.config.presets[this.config.defaultPreset]}getAllDefinitions(){return this.config.definitions}get definitions(){return this.definitionMap}resolveColumnValue(e,t,n,r){let i=this.getDefinition(t);if(!i)return;let a={allRows:n,rowIndex:r??n.findIndex(t=>t.id===e.id),columnDef:i,dependencies:new Map};return BU(e,i.source,a,this.definitionMap)}getOrderedCandidates(e){let t=this.getPreset(e.activePresetId),n=[],r=new Set,i=e=>{if(r.has(e))return;let t=this.getDefinition(e);t&&(n.push(t),r.add(e))};for(let e of t.visibleColumnIds)i(e);for(let e of this.config.definitions)i(e.id);if(e.addedColumnIds)for(let t of e.addedColumnIds)i(t);return n}computeVisibility(e,t,n){if(t.visibilityOverrides&&e in t.visibilityOverrides)return t.visibilityOverrides[e];if(t.addedColumnIds?.has(e))return!0;let r=this.getDefinition(e);if(!r||r.meta?.debugOnly&&!t.isDebugMode||!n&&this.isColumnSubsumed(e,t))return!1;let i=this.getPreset(t.activePresetId).visibleColumnIds.includes(e),a=this.hasDataInRows(r,t.rows);switch(r.source.type){case`fixed-field`:return i;case`derived`:return i;case`metric-type`:return a;case`fallback`:return i&&a;default:return i}}isColumnSubsumed(e,t){for(let n of this.config.definitions)if(n.meta?.subsumes?.length&&this.getPreset(t.activePresetId).visibleColumnIds.includes(n.id)&&n.meta.subsumes.includes(e))return!0;return!1}isColumnAvailable(e,t){return e.meta?.debugOnly&&!t.isDebugMode?!1:this.getPreset(t.activePresetId).visibleColumnIds.includes(e.id)?!this.computeVisibility(e.id,t):e.source.type===`fixed-field`||e.source.type===`derived`||this.hasDataInRows(e,t.rows)}hasDataInRows(e,t){if(t.length===0)return!1;switch(e.source.type){case`fixed-field`:return!0;case`metric-type`:{let{metricType:n}=e.source;return t.some(e=>e.cells.has(n))}case`derived`:return!0;case`fallback`:{let{sources:n}=e.source;return t.some(e=>n.some(t=>this.sourceHasDataInRow(t,e)))}default:return!0}}sourceHasDataInRow(e,t){switch(e.type){case`fixed-field`:return t[e.field]!==void 0&&t[e.field]!==null;case`metric-type`:return t.cells.has(e.metricType);case`derived`:return!0;case`fallback`:return e.sources.some(e=>this.sourceHasDataInRow(e,t));default:return!1}}}(dG);function pG(e){let{segments:t,userOutputOverrides:n,presetId:r,isDebugMode:i,sortConfigs:a,filterOverrides:o,graphTaggedColumns:s,extraMetricTypes:c,columnVisibilityOverrides:l,addedColumnIds:u}=e,d=(0,V.useMemo)(()=>mG(t,n),[t,n]),f=(0,V.useMemo)(()=>{let e=new Set(u??[]);for(let t of c??[])e.add(t);return e},[u,c]),p=(0,V.useMemo)(()=>({rows:d,activePresetId:r,isDebugMode:i,graphTaggedColumnIds:s,visibilityOverrides:l,addedColumnIds:f}),[d,r,i,s,l,f]),m=(0,V.useMemo)(()=>fG.getVisibleColumns(p),[p]),h=(0,V.useMemo)(()=>fG.getAvailableColumns(p),[p]),g=(0,V.useMemo)(()=>({...fG.getPreset(r).filters??{},...o}),[r,o]);return{rows:(0,V.useMemo)(()=>vG(_G(d,g,m,fG.definitions),a,m,fG.definitions),[d,g,a,m]),visibleColumns:m,availableColumns:h,graphTaggedColumnIds:(0,V.useMemo)(()=>Array.from(s??[]),[s])}}function mG(e,t){return e.map((e,n)=>{let r=new Map;if(e.metrics)for(let t of e.metrics)gG(r,t);let i=hG(e),a=i?t.get(i):void 0;if(a)for(let e of a)gG(r,e);for(let[,e]of r)e.hasUserOverride=e.metrics.some(e=>e.origin===`user`);let o=e.context?.outputType??e.type;return{id:e.id,index:n+1,sourceBlockKey:i??`segment-${e.id}`,sourceStatementId:e.context?.sourceStatementId,outputType:o,stackLevel:e.depth,absoluteStartTime:e.absoluteStartTime,duration:e.duration,elapsed:e.elapsed,total:e.total,spans:e.spans?[...e.spans]:[],completionReason:e.context?.completionReason,cells:r}})}function hG(e){let t=e.context;return t?.sourceBlockKey?t.sourceBlockKey:e.name}function gG(e,t){let n=t.type;if(n===G.Sound)return;let r=e.get(n);r?e.set(n,{metrics:r.metrics.clone().add(t),hasUserOverride:r.hasUserOverride}):e.set(n,{metrics:K.empty(n).add(t),hasUserOverride:!1})}function _G(e,t,n,r){let i=e;if(t.outputTypes&&t.outputTypes.length>0){let e=new Set(t.outputTypes);i=i.filter(t=>e.has(t.outputType))}if(t.origins&&t.origins.length>0){let e=new Set(t.origins);i=i.filter(t=>{for(let[,n]of t.cells)if(n.metrics.some(t=>t.origin&&e.has(t.origin)))return!0;return!1})}if(t.searchText&&t.searchText.trim().length>0){let a=t.searchText.trim().toLowerCase();i=i.filter(t=>{for(let i of n)if(i.filter&&eW(t,i,{allRows:e,rowIndex:e.indexOf(t),columnDef:i,dependencies:new Map},r).toLowerCase().includes(a))return!0;return!1})}if(t.columnFilters)for(let[a,o]of Object.entries(t.columnFilters)){if(!o||o.trim().length===0)continue;let t=n.find(e=>e.id===a);t&&(i=i.filter(n=>{let i={allRows:e,rowIndex:e.indexOf(n),columnDef:t,dependencies:new Map};return tW(n,t,o,i,r)}))}return i}function vG(e,t,n,r){if(t.length===0)return e;let i=[...e];return i.sort((i,a)=>{for(let o of t){let t=n.find(e=>e.id===o.columnId);if(!t||!t.sort)continue;let s={allRows:e,rowIndex:e.indexOf(i),columnDef:t,dependencies:new Map},c={allRows:e,rowIndex:e.indexOf(a),columnDef:t,dependencies:new Map},l=QU(ZU(i,t,s,r),ZU(a,t,c,r));if(l!==0)return o.direction===`asc`?l:-l}return i.index-a.index}),i}function yG(e,t){return{id:e,label:t.label,filters:t.filters??{},visibleColumns:[...t.visibleColumnIds],isDefault:e===dG.defaultPreset}}var bG=Object.fromEntries(Object.entries(dG.presets).map(([e,t])=>[e,yG(e,t)])),xG=bG.default;bG.debug,bG.strength,bG.endurance;function SG(e){return bG[e]??xG}var CG=({activePreset:e,onPresetChange:t,searchText:n,onSearchChange:r,showFilters:i,onToggleFilters:a,totalRows:o,visibleRows:s})=>(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2 border-b border-border bg-muted/10 dark:bg-muted/5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`label`,{className:`text-xs text-muted-foreground font-medium`,children:`View:`}),(0,H.jsx)(`select`,{className:`text-xs rounded border border-border bg-background text-foreground px-1.5 py-1 focus:outline-none focus:ring-1 focus:ring-primary/40`,value:e.id,onChange:e=>t(e.target.value),children:Object.values(bG).map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,H.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,H.jsx)(`div`,{className:`flex items-center flex-1 max-w-md`,children:(0,H.jsxs)(`div`,{className:`flex w-full group`,children:[(0,H.jsx)(`input`,{type:`text`,className:`flex-1 px-2.5 py-1 text-xs rounded-l border border-r-0 border-border bg-background text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-primary/40 focus:z-10`,placeholder:`Filter results…`,value:n,onChange:e=>r(e.target.value)}),(0,H.jsxs)(`button`,{className:`px-2.5 py-1 text-xs rounded-r border border-border bg-muted/30 text-muted-foreground hover:bg-muted/50 hover:text-foreground transition-colors flex items-center gap-1.5 border-l-0`,title:`Filter results`,children:[(0,H.jsx)(`span`,{children:`🔍`}),(0,H.jsx)(`span`,{className:`font-medium`,children:`Search`})]})]})}),(0,H.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,H.jsx)(`button`,{className:[`text-xs px-2 py-1 rounded border transition-colors`,i?`bg-primary/10 border-primary/30 text-primary`:`bg-muted/30 border-border text-muted-foreground hover:text-foreground`].join(` `),onClick:a,title:i?`Hide column filters`:`Show column filters`,children:`🔽 Filters`}),(0,H.jsx)(`div`,{className:`ml-auto text-xs text-muted-foreground tabular-nums`,children:s===o?`${o} rows`:`${s} / ${o} rows`})]}),wG={"#":`40px`,exercise:`180px`,text:`160px`,notes:`160px`,completionReason:`160px`,rep:`72px`,rounds:`72px`,"current-round":`72px`,duration:`96px`,distance:`96px`,resistance:`96px`,load:`96px`,volume:`96px`,intensity:`96px`,metric:`96px`,work:`96px`,elapsedTotal:`96px`,action:`96px`,increment:`96px`,timestamp:`96px`,spans:`96px`,blockKey:`180px`,outputType:`96px`,stackLevel:`72px`,elapsed:`96px`},TG=`48px`;function EG(e){return e.meta?.width??wG[e.id]??`96px`}function DG(){return TG}var OG=({columns:e,sortConfigs:t,onSort:n,onToggleGraph:r,showFilters:i,columnFilters:a,onColumnFilterChange:o,availableToAdd:s,onAddColumn:c,graphTaggedColumnIds:l})=>(0,H.jsxs)(`thead`,{className:`bg-muted/50 dark:bg-muted/30 sticky top-0 z-10`,children:[(0,H.jsxs)(`tr`,{className:`border-b border-border`,children:[e.map(e=>(0,H.jsx)(kG,{column:e,sortConfig:t.find(t=>t.columnId===e.id),onSort:n,onToggleGraph:r,isGraphed:l?.has(e.id)??!1},e.id)),c&&(0,H.jsx)(`th`,{className:`py-2 px-1`,style:{minWidth:DG()},children:(0,H.jsx)(MG,{availableToAdd:s??[],onAddColumn:c})})]}),i&&(0,H.jsxs)(`tr`,{className:`border-b border-border/50 bg-muted/20 dark:bg-muted/10`,children:[e.map(e=>(0,H.jsx)(jG,{column:e,value:a[e.id]??``,onChange:o},e.id)),c&&(0,H.jsx)(`th`,{className:`py-1 px-1`,style:{minWidth:DG()}})]})]}),kG=({column:e,sortConfig:t,onSort:n,onToggleGraph:r,isGraphed:i})=>{let a=e.sort!==void 0,o=e.graph!==void 0,s=(0,V.useCallback)(t=>{a&&n(e.id,t.shiftKey)},[e.id,a,n]),c=(0,V.useCallback)(t=>{t.stopPropagation(),r(e.id)},[e.id,r]);return(0,H.jsx)(`th`,{className:[`py-1.5 px-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap select-none`,a?`cursor-pointer hover:text-foreground transition-colors`:``].join(` `),style:{minWidth:EG(e)},onClick:s,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.icon&&(0,H.jsx)(`span`,{className:`text-sm`,children:e.icon}),(0,H.jsx)(`span`,{children:e.label}),t&&(0,H.jsx)(AG,{direction:t.direction}),o&&(0,H.jsx)(`button`,{className:[`ml-auto text-sm opacity-40 hover:opacity-100 transition-opacity`,i?`opacity-100 text-primary`:``].join(` `),onClick:c,title:i?`Remove from graph`:`Add to graph`,children:`📊`})]})})},AG=({direction:e})=>(0,H.jsx)(`span`,{className:`text-primary text-[10px] ml-0.5`,children:e===`asc`?`▲`:`▼`}),jG=({column:e,value:t,onChange:n})=>e.filter?(0,H.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:EG(e)},children:(0,H.jsx)(`input`,{type:`text`,className:`w-full px-1.5 py-0.5 text-xs rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/40`,placeholder:`Filter…`,value:t,onChange:t=>n(e.id,t.target.value)})}):(0,H.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:EG(e)}}),MG=({availableToAdd:e,onAddColumn:t})=>{let[n,r]=(0,V.useState)(!1),i=(0,V.useRef)(null),a=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&a.current&&!a.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]),e.length===0?null:(0,H.jsxs)(`div`,{className:`relative flex items-center justify-center`,children:[(0,H.jsx)(`button`,{ref:a,title:`Add metric column`,onClick:e=>{e.stopPropagation(),r(e=>!e)},className:[`flex items-center justify-center w-5 h-5 rounded text-[11px] font-bold transition-all`,`text-muted-foreground hover:text-foreground hover:bg-primary/10 hover:border-primary/40`,`border border-dashed border-muted-foreground/40`,n?`bg-primary/10 border-primary/40 text-foreground`:``].join(` `),children:`+`}),n&&(0,H.jsxs)(`div`,{ref:i,className:`absolute right-0 top-full mt-1 z-50 min-w-[160px] max-h-64 overflow-y-auto
157
+ bg-popover border border-border rounded-md shadow-xl py-1`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`div`,{className:`px-3 py-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider border-b border-border/50 mb-1`,children:`Add metric column`}),e.map(e=>{let n=gB(e)??`•`,i=_o.columnLabel(e);return(0,H.jsxs)(`button`,{onClick:()=>{t(e),r(!1)},className:`w-full flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-muted text-foreground transition-colors`,children:[(0,H.jsx)(`span`,{className:`text-sm w-4 text-center`,children:n}),(0,H.jsx)(`span`,{children:i})]},e)})]})]})},NG=({row:e,allRows:t,rowIndex:n,columns:r,isSelected:i,onSelect:a,isHovered:o,onHover:s,onCellDoubleClick:c})=>{let l=t=>{a(e.id,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},u=e.outputType===`group`;return(0,H.jsx)(`tr`,{className:U(`border-b border-border transition-colors cursor-pointer`,u?`bg-muted/50 font-bold`:``,i?`bg-accent dark:bg-accent/20`:o?`bg-muted/50 dark:bg-muted/40`:`hover:bg-muted/30 dark:hover:bg-muted/20`),onClick:l,onMouseEnter:()=>s(e.sourceBlockKey),onMouseLeave:()=>s(null),children:r.map(r=>{let i=r.source.type===`metric-type`&&r.source.metricType===G.Effort;return(0,H.jsx)(rW,{columnDef:r,row:e,allRows:t,rowIndex:n,indent:i?e.stackLevel:0,onDoubleClick:c,style:{minWidth:EG(r)}},r.id)})})};function PG(e){let{rows:t,columns:n,graphTaggedColumnIds:r,definitionMap:i}=e,a=(0,V.useMemo)(()=>FG(r,n),[r,n]),o=(0,V.useMemo)(()=>IG(t,r,n,i),[t,r,n,i]);return{data:o,graphConfigs:a,hasData:a.length>0&&o.length>0}}function FG(e,t){let n=[];for(let r of e){let e=t.find(e=>e.id===r);e&&n.push({id:r,label:e.label,unit:BG(e),color:LG(e),dataKey:r,icon:e.icon})}return n}function IG(e,t,n,r){return t.length===0?[]:e.map((i,a)=>{let o={index:i.index,label:i.sourceBlockKey};for(let s of t){let t=n.find(e=>e.id===s);if(!t||!t.graph){o[s]=0;continue}o[s]=$U(i,t,{allRows:e,rowIndex:a,columnDef:t,dependencies:new Map},r)??0}return o})}function LG(e){if(e.graph?.color)return e.graph.color;let t=RG(e);return t?zG[t]??`#888888`:`#888888`}function RG(e){if(e.source.type===`metric-type`)return e.source.metricType}var zG={[G.Time]:`#3b82f6`,[G.Rep]:`#22c55e`,[G.Effort]:`#eab308`,[G.Distance]:`#14b8a6`,[G.Rounds]:`#a855f7`,[G.Resistance]:`#ef4444`,[G.Increment]:`#6366f1`,[G.Action]:`#ec4899`};function BG(e){if(e.graph?.unit)return e.graph.unit;let t=RG(e);if(!t)return``;switch(t){case G.Time:return`ms`;case G.Rep:return`reps`;case G.Distance:return`m`;case G.Rounds:return`rounds`;case G.Resistance:return`kg`;case G.Increment:return`Δ`;default:return``}}var VG=({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r,onSelectRow:i})=>{let[a,o]=(0,V.useState)(!1),{data:s,graphConfigs:c,hasData:l}=PG({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r}),u=(0,V.useCallback)(t=>{if(!t?.activePayload?.[0])return;let n=t.activePayload[0].payload,r=e.find(e=>e.index===n.index);r&&i&&i(r.id)},[e,i]);return n.length===0?null:(0,H.jsxs)(`div`,{className:`border-b border-border bg-background`,children:[(0,H.jsxs)(`button`,{className:`w-full flex items-center justify-between px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/20 transition-colors`,onClick:()=>o(e=>!e),children:[(0,H.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{children:`📊`}),(0,H.jsxs)(`span`,{children:[`Graph — `,c.map(e=>e.label).join(`, `)]})]}),(0,H.jsx)(`span`,{className:`text-[10px]`,children:a?`▼`:`▲`})]}),!a&&(0,H.jsx)(`div`,{className:`px-3 pb-3`,children:l?(0,H.jsx)(`div`,{className:`w-full bg-muted/30 rounded-lg border border-border p-2`,style:{height:220},children:(0,H.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,H.jsxs)(An,{data:s,onClick:u,children:[(0,H.jsx)(Ee,{strokeDasharray:`3 3`,stroke:`hsl(var(--border))`,vertical:!1}),(0,H.jsx)(tt,{dataKey:`index`,stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},label:{value:`Row #`,position:`insideBottom`,offset:-5,fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,H.jsx)(re,{stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},domain:[`auto`,`auto`]}),(0,H.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>`Row ${e}`,formatter:(e,t)=>{let n=c.find(e=>e.dataKey===t);return[`${typeof e==`number`?e.toLocaleString():e}${n?.unit?` ${n.unit}`:``}`,n?.label??t]}}),(0,H.jsx)(bn,{verticalAlign:`top`,height:24,wrapperStyle:{fontSize:`11px`}}),c.map(e=>(0,H.jsx)(at,{type:`monotone`,dataKey:e.dataKey,name:e.label,stroke:e.color,strokeWidth:2,dot:{r:3,fill:e.color},activeDot:{r:5,stroke:e.color,strokeWidth:2}},e.id))]})})}):(0,H.jsx)(`div`,{className:`h-32 flex items-center justify-center text-sm text-muted-foreground`,children:`No numeric data available for the tagged columns.`})})]})},HG=({isOpen:e,blockKey:t,metricType:n,existingFragments:r,existingUserValue:i,anchorRect:a,onSave:o,onRemove:s,onClose:c})=>{let[l,u]=(0,V.useState)(``),d=(0,V.useRef)(null),f=(0,V.useRef)(null);(0,V.useEffect)(()=>{e&&(u(i===void 0?``:String(i)),setTimeout(()=>d.current?.focus(),0))},[e,i]),(0,V.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&c()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,c]),(0,V.useEffect)(()=>{if(!e)return;let t=e=>{f.current&&!f.current.contains(e.target)&&c()},n=setTimeout(()=>{document.addEventListener(`mousedown`,t)},100);return()=>{clearTimeout(n),document.removeEventListener(`mousedown`,t)}},[e,c]);let p=(0,V.useCallback)(()=>{if(l.trim()===``)return;let e=Number(l.trim()),r=!isNaN(e)&&l.trim()!==``?e:l.trim();o(t,n,r,String(r)),c()},[l,t,n,o,c]),m=(0,V.useCallback)(()=>{s(t,n),c()},[t,n,s,c]),h=(0,V.useCallback)(e=>{e.key===`Enter`&&(e.preventDefault(),p())},[p]);if(!e)return null;let g=gB(n),_=mB(n),v=i!==void 0,y=r.filter(e=>e.origin!==`user`),b=a?{position:`fixed`,top:a.bottom+4,left:Math.max(8,Math.min(a.left,window.innerWidth-280)),zIndex:50}:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,zIndex:50};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`fixed inset-0 bg-black/20 dark:bg-black/40 z-40`}),(0,H.jsxs)(`div`,{ref:f,className:`w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-lg`,style:b,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[g&&(0,H.jsx)(`span`,{className:`text-sm`,children:g}),(0,H.jsx)(`span`,{className:`text-sm font-medium capitalize`,children:n}),(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground ml-auto truncate max-w-[100px]`,title:t,children:t})]}),y.length>0&&(0,H.jsxs)(`div`,{className:`px-3 py-1.5 border-b border-border/50 bg-muted/10`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1 uppercase tracking-wider`,children:`Current`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:y.map((e,t)=>(0,H.jsx)(`span`,{className:`inline-flex items-center px-1.5 py-0.5 rounded text-xs border ${_}`,children:e.image??String(e.value??e.type)},t))})]}),(0,H.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,H.jsx)(`label`,{className:`text-[10px] text-muted-foreground uppercase tracking-wider mb-1 block`,children:v?`Update override`:`Enter value`}),(0,H.jsx)(`input`,{ref:d,type:`text`,className:`w-full px-2 py-1.5 text-sm rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/40`,placeholder:`Enter ${n} value…`,value:l,onChange:e=>u(e.target.value),onKeyDown:h})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-t border-border/50`,children:[(0,H.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors`,onClick:c,children:`Cancel`}),v&&(0,H.jsx)(`button`,{className:`px-2 py-1 text-xs rounded border border-destructive/30 text-destructive hover:bg-destructive/10 transition-colors`,onClick:m,title:`Remove user override`,children:`Clear`}),(0,H.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,onClick:p,disabled:l.trim()===``,children:`Save`})]})]})]})},UG=({segments:e,selectedSegmentIds:t,onSelectSegment:n,userOutputOverrides:r=new Map,gridViewPreset:i=`default`,onPresetChange:a,hoveredBlockKey:o,onHoverBlockKey:s})=>{let{isDebugMode:c}=ty(),[l,u]=(0,V.useState)([]),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)({}),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(new Set),[y,b]=(0,V.useState)({}),[x,S]=(0,V.useState)(new Set),{overrides:C,setOverride:w,removeOverride:T}=BV(!0),[E,D]=(0,V.useState)({isOpen:!1,blockKey:``,type:`Time`,anchorRect:null,existingFragments:[]}),O=(0,V.useMemo)(()=>{let e=new Map;for(let[t,n]of r)e.set(t,n instanceof K?n:K.from(n,t));for(let[t,n]of C)e.set(t,n);return e},[r,C]),k=c?`debug`:i,A=(0,V.useMemo)(()=>SG(k),[k]),{rows:j,visibleColumns:M,availableColumns:N,graphTaggedColumnIds:P}=pG({segments:e,userOutputOverrides:O,presetId:k,isDebugMode:c,sortConfigs:l,filterOverrides:(0,V.useMemo)(()=>({searchText:d||void 0,columnFilters:Object.keys(p).length>0?p:void 0}),[d,p]),graphTaggedColumns:_,extraMetricTypes:x,columnVisibilityOverrides:y,addedColumnIds:x}),F=M,I=e.length,ee=(0,V.useMemo)(()=>j.map(e=>e.id),[j]),te=(0,V.useCallback)((e,t)=>{u(n=>{let r=n.find(t=>t.columnId===e);return t?r?r.direction===`asc`?n.map(t=>t.columnId===e?{...t,direction:`desc`}:t):n.filter(t=>t.columnId!==e):[...n,{columnId:e,direction:`asc`}]:r?r.direction===`asc`?[{columnId:e,direction:`desc`}]:[]:[{columnId:e,direction:`asc`}]})},[]),ne=(0,V.useCallback)(e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),re=(0,V.useCallback)((e,t)=>{m(n=>{if(!t){let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),ie=(0,V.useCallback)(e=>{b({}),m({}),f(``),a?.(e)},[a]),ae=(0,V.useCallback)(e=>{S(t=>{let n=new Set(t);return n.add(e),n})},[]),oe=(0,V.useMemo)(()=>N.filter(e=>e.source.type===`metric-type`).map(e=>e.source.metricType),[N]),se=(0,V.useCallback)((e,t)=>{n(e,t,ee)},[n,ee]),ce=(0,V.useCallback)(e=>{s?.(e)},[s]),L=(0,V.useCallback)(e=>{n(e,{ctrlKey:!1,shiftKey:!1},ee)},[n,ee]),le=(0,V.useCallback)((e,t,n)=>{let r=(j.find(t=>t.sourceBlockKey===e)?.cells.get(t))?.metrics.toArray()??[],i=r.find(e=>e.origin===`user`),a=i?.value==null?void 0:String(i.value);D({isOpen:!0,blockKey:e,type:t,anchorRect:n,existingFragments:r,existingUserValue:a})},[j]),ue=(0,V.useCallback)((e,t,n,r)=>{w(e,t,n,r),D(e=>({...e,isOpen:!1}))},[w]),R=(0,V.useCallback)(()=>{T(E.blockKey,E.type),D(e=>({...e,isOpen:!1}))},[E.blockKey,E.type,T]),de=(0,V.useCallback)(()=>{D(e=>({...e,isOpen:!1}))},[]);return(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-background`,children:[(0,H.jsx)(CG,{activePreset:A,onPresetChange:ie,searchText:d,onSearchChange:f,showFilters:h,onToggleFilters:()=>g(e=>!e),totalRows:I,visibleRows:j.length}),(0,H.jsx)(VG,{rows:j,columns:M,graphTaggedColumnIds:P,selectedIds:t,onSelectRow:L}),(0,H.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,H.jsxs)(`table`,{className:`text-left text-sm border-collapse min-w-[700px]`,children:[(0,H.jsx)(OG,{columns:F,sortConfigs:l,onSort:te,onToggleGraph:ne,showFilters:h,columnFilters:p,onColumnFilterChange:re,availableToAdd:oe,onAddColumn:ae,graphTaggedColumnIds:_}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border`,children:j.length===0?(0,H.jsx)(`tr`,{children:(0,H.jsx)(`td`,{colSpan:F.length,className:`py-8 text-center text-muted-foreground text-sm`,children:e.length===0?`Finish or stop the timer — results land here`:`No rows match the current filters.`})}):j.map((e,n)=>(0,H.jsx)(NG,{row:e,allRows:j,rowIndex:n,columns:F,isSelected:t.has(e.id),onSelect:se,isHovered:o===e.sourceBlockKey,onHover:ce,onCellDoubleClick:le},e.id))})]})}),(0,H.jsx)(HG,{isOpen:E.isOpen,blockKey:E.blockKey,metricType:E.type,existingFragments:E.existingFragments,existingUserValue:E.existingUserValue,anchorRect:E.anchorRect??void 0,onSave:ue,onRemove:R,onClose:de}),(0,H.jsxs)(`div`,{className:`px-3 py-1.5 border-t border-border bg-muted/10 text-xs text-muted-foreground flex items-center justify-between`,children:[(0,H.jsx)(`span`,{children:t.size>0?`${t.size} selected`:`Click a row to select`}),(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[j.length,` / `,I,` rows`]})]})]})};Yt();var WG=({title:e,onClose:t,children:n,closeButtonClassName:r,floatingClose:i=!1,variant:a=`default`,actions:o,closeLabel:s})=>{(0,V.useEffect)(()=>(document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=``}),[]);let c=a===`minimal`,l=(0,H.jsx)(`button`,{onClick:t,className:r??`rounded-pill transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${c?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${s?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`p-2`}`,title:s??`Close`,"data-testid":sB.FOCUSED_DIALOG_CLOSE,children:s??(0,H.jsx)(Te,{className:`h-5 w-5`})});return aS.createPortal((0,H.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex flex-col bg-background text-foreground animate-in fade-in duration-200`,children:[i||c&&!e?(0,H.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[o,l]}):e?(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${c?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,H.jsx)(`h2`,{className:`text-lg ${c?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[o,l]})]}):null,(0,H.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:n})]}),document.body)},GG=(0,V.createContext)({updateFromSegments:()=>{},clear:()=>{}}),KG=({children:e,chromecastSubscription:t=null})=>(0,H.jsx)(GG.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),qG=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?IV(e.analyticsSegments):RV(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 JG(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 YG=()=>{let e=OV(),[t,n]=(0,V.useState)(e.state),[r,i]=(0,V.useState)(!1),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(null),[l,u]=(0,V.useState)(null),d=(0,V.useRef)(null),f=cF,p=(0,V.useRef)(f.getActiveHandle()),m=(0,V.useRef)(!1),h=(0,V.useCallback)(e=>{let t=p.current;p.current=null,t&&f.dispose(e),qO(null),u(null),c(null),i(!1)},[f]),g=(0,V.useCallback)(async e=>{if(!m.current){m.current=!0;try{let t=JI.getState().subscriptionManager,n=f.connect(e,t);p.current=n,u(n),c(n.subscription),i(!0),qO(n.transport),n.eventProvider.onEvent(e=>{let t=JI.getState();AV(e,{onNext:()=>{t.handles.handleNext&&t.handles.handleNext(),t.runtime&&(!t.handles.handleNext||t.handles.handleNext===_F.handleNext)&&(t.runtime.handle(new mf(void 0,t.runtime.nowProvider)),t.execution.status!==`running`&&t.execution.start())},onStart:()=>{t.handles.handleStart&&t.handles.handleStart(),t.execution&&(!t.handles.handleStart||t.handles.handleStart===_F.handleStart)&&t.execution.start()},onPause:()=>{t.handles.handlePause&&t.handles.handlePause(),t.execution&&(!t.handles.handlePause||t.handles.handlePause===_F.handlePause)&&t.execution.pause()},onStop:()=>{t.handles.handleStop&&t.handles.handleStop(),t.execution&&(!t.handles.handleStop||t.handles.handleStop===_F.handleStop)&&t.execution.stop()}})});let r=JI.getState(),a=qG.resolve({viewMode:r.viewMode,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:r.analyticsSegments,selectedBlock:r.selectedBlock,documentItems:r.documentItems});n.pushInitialWorkbench(a)}finally{m.current=!1}}},[f]),_=(0,V.useRef)(!1),v=(0,V.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:`,JG(t)),h(!1),e.endSession()}finally{_.current=!1}}},[e,g,h,f]);(0,V.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,V.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,V.useEffect)(()=>{let e=()=>{f.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[f]),(0,V.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=JG(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):console.error(`[CastButtonRpc] Cast failed:`,t),h(!1)}};return t.addEventListener(`click`,n),()=>t.removeEventListener(`click`,n)},[e,g,h]);let y=(0,V.useRef)(t);y.current=t;let b=(0,V.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,H.jsx)(W,{variant:`ghost`,size:`icon`,disabled:!0,className:`opacity-20 cursor-not-allowed`,children:(0,H.jsx)(On,{className:`h-5 w-5`})}):(0,H.jsx)(QO,{transport:l?.transport??null,children:(0,H.jsx)(KG,{chromecastSubscription:s,children:(0,H.jsx)(W,{ref:d,variant:`ghost`,size:`icon`,disabled:D,onClick:()=>{},className:U(`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,H.jsx)(F,{className:`h-5 w-5`}):(0,H.jsx)(On,{className:`h-5 w-5`})})})})};function XG(){let{isEnabled:e,toggleAudio:t}=tk();return(0,H.jsxs)(W,{variant:`ghost`,size:`icon`,onClick:t,className:`h-9 w-9 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,H.jsx)(fe,{className:`h-[1.2rem] w-[1.2rem]`}):(0,H.jsx)(ne,{className:`h-[1.2rem] w-[1.2rem]`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}var ZG=({block:e,prepareRun:t,view:n,onClose:r,onCompleteWorkout:i,autoStart:a,onRuntimeReady:o,onRunStarted:s,externalStop:c})=>{let[l,u]=(0,V.useState)(t?null:e),[d,f]=(0,V.useState)(null),p=(0,V.useRef)(!1),m=(0,V.useCallback)(async()=>{if(!(!t||p.current)){p.current=!0,f(null);try{u(await t())}catch(e){f(e instanceof Error?e.message:String(e))}finally{p.current=!1}}},[t]);(0,V.useEffect)(()=>{m()},[m]);let[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(new Set),{isDebugMode:y}=ty(),b=(0,V.useRef)(Date.now()),x=(0,V.useRef)(typeof document<`u`?document.title:`Wod.Wiki`);(0,V.useEffect)(()=>{let t=e.label||e.id,n=h!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,window.gtag?.(`event`,`page_view`,{page_title:r,page_path:i,page_location:typeof window<`u`?`${window.location.origin}${i}`:i}),n?window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):(oH.record(`runtime:dialog_loaded`,{workout_label:t,block_type:e.blockType}),window.gtag?.(`event`,`runtime_dialog_loaded`,{workout_label:t,block_type:e.blockType}))},[e.id,e.label,e.blockType,h]),(0,V.useEffect)(()=>{let t=x.current,n=e.label||e.id;return()=>{let e=Date.now()-b.current;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:n,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label]);let S=(0,V.useRef)(!1),C=(0,V.useRef)(!1),w=(0,V.useRef)(!1),[T,E]=(0,V.useState)(!1),D=(0,V.useRef)(!1),O=(0,V.useRef)(!1),k=(0,V.useRef)(null),[A,j]=(0,V.useState)(`idle`),[M,N]=(0,V.useState)(null),[P,F]=(0,V.useState)(!1),I=async()=>{let e=k.current;if(!e||D.current)return;D.current=!0,O.current=!1,j(`saving`),N(null);let t;try{t=i?.(e.blockId,e.results),await t}catch(e){O.current=!0,N(e instanceof Error?e.message:String(e)),j(`error`),D.current=!1;return}D.current=!1,j(`idle`),F(!0);let{results:n}=e;if(n.completed&&n.logs&&n.logs.length>0)try{let{segments:e}=BP(n.logs,n.startTime);g(e)}catch{g([])}else n.completed?g([]):w.current&&r()},ee=(0,V.useCallback)(()=>{S.current=!0,s?.()},[s]),te=()=>{if(D.current||O.current){w.current=!0;return}if(h!==null||C.current||!S.current){r();return}w.current=!0,E(!0)},ne=(e,t)=>{C.current||(C.current=!0,k.current={blockId:e,results:t},I())},re=(e,t,n)=>{v(r=>{let i=new Set(r);if(t?.ctrlKey)i.has(e)?i.delete(e):i.add(e);else if(t?.shiftKey&&n){let t=Array.from(r).pop();if(t!==void 0){let r=n.indexOf(t),a=n.indexOf(e);if(r!==-1&&a!==-1){let e=Math.min(r,a),t=Math.max(r,a);for(let r=e;r<=t;r++)i.add(n[r])}else i.add(e)}else i.add(e)}else i.clear(),i.add(e);return i})},ie=A===`idle`?null:(0,H.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:[A===`saving`&&(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),A===`error`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,M?` — ${M}`:``]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>void I(),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 l?h===null?(0,H.jsx)(WG,{onClose:te,title:`Workout`,closeLabel:`Exit`,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,onClick:te,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,H.jsx)(YG,{}),(0,H.jsx)(XG,{})]}),children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[ie,d?(0,H.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,d]}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void m(),children:`Retry starting workout`})]}):l?null:(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,H.jsx)(eH,{block:l,view:n,onClose:te,onComplete:ne,isExpanded:!0,autoStart:a,onRuntimeReady:o,onRunStarted:ee,externalStop:c||T})})]})}):(0,H.jsx)(WG,{title:`Workout Complete`,onClose:te,actions:(0,H.jsxs)(H.Fragment,{children:[P&&(0,H.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,H.jsx)(YG,{}),(0,H.jsx)(XG,{})]}),children:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[ie,(0,H.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,H.jsx)(UG,{runtime:null,segments:h,selectedSegmentIds:_,onSelectSegment:re,groups:[],gridViewPreset:y?`debug`:`default`})})]})}):(0,H.jsx)(WG,{title:`Starting workout`,onClose:r,children:d?(0,H.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,d,` Your draft is kept.`]}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void m(),children:`Retry start`})]}):(0,H.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},QG={play:!0,"add-to-today":!0,schedule:!0},$G=`log`;function eK(e,t){return e.filter(e=>e.id===$G?t===`log`:!QG[e.id]||t===`run`)}function tK(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 nK(e){return function({className:t}){return V.isValidElement(e)?V.cloneElement(e,{className:U(e.props.className,t)}):(0,H.jsx)(`span`,{className:U(`flex items-center`,t),children:e})}}var rK=({cmd:e,block:t})=>{let[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(!1),o=(0,V.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,V.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,V.useMemo)(()=>nK(i?e.successIcon??e.icon:e.icon),[e.icon,e.successIcon,i]),l=(0,V.useMemo)(()=>nK(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),u=(0,V.useMemo)(()=>({id:e.id,label:e.label,icon:c,action:{type:`call`,handler:()=>s()}}),[e.id,e.label,c,s]),d=(0,V.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:l,action:{type:`call`,handler:o}}),[e.id,l,o]),f=(0,V.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);if(!e.onSplitClick){let t=i?e.successIcon??e.icon:e.icon;return(0,H.jsxs)(W,{variant:e.primary?`default`:`secondary`,className:U(e.iconOnly?`h-11 w-11 rounded-full p-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:rounded-sm sm:px-1.5 sm:py-0.5 text-[10px] font-medium shadow-sm`:`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`,i&&`text-emerald-600 bg-emerald-500/15 dark:text-emerald-400 dark:bg-emerald-500/20 border-emerald-500/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`?sB.EDITOR_START_WORKOUT:void 0,onClick:e=>{f(e),s()},onMouseDown:f,onPointerDown:f,children:[(0,H.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:t}),!e.iconOnly&&(0,H.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})}return(0,H.jsx)(`div`,{onClick:f,onMouseDown:f,onPointerDown:f,children:(0,H.jsx)(TU,{primary:u,secondary:d,size:`xs`,variant:e.primary?`primary`:`default`,className:`rounded-full sm:rounded-sm`,labelClassName:`sr-only sm:not-sr-only sm:inline`})})},iK=({view:e,commands:t})=>{let[n,r]=(0,V.useState)(()=>e?.plugin(hw)?.rects??[]),[i,a]=(0,V.useState)(0);(0,V.useEffect)(()=>{if(!e)return;let t=e.plugin(hw);t&&(r([...t.rects]),t.addListener(e=>r([...e])))},[e]),(0,V.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n=null,r=()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,a(t.scrollTop)}))};return t.addEventListener(`scroll`,r,{passive:!0}),a(t.scrollTop),()=>{n!==null&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,r)}},[e]);let o=e?e.plugin(hw):null,s=(n.length>0?n:o?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(s.length===0)return null;let{sections:c}=e.state.field(ZC),l=new Map(c.map(e=>[e.id,e]));return(0,H.jsx)(H.Fragment,{children:s.map(n=>{let r=l.get(n.sectionId);if(!r)return null;let a=tK(e,r),o=eK(t,ba(r.type));return o.length===0?null:(0,H.jsx)(`div`,{className:`absolute right-1 z-10 flex items-end gap-1 pointer-events-auto`,style:{top:n.top-i,height:n.firstLineHeight},children:o.map(e=>(0,H.jsx)(rK,{cmd:e,block:a},e.id))},n.sectionId)})})},aK=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=ZO(),a=(0,V.useRef)(``);return(0,V.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(`
146
158
  `).filter(e=>e.trim().length>0),i=r.slice(0,3).join(`
147
- `),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,V.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,V.useEffect)(()=>{t||(a.current=``)},[t]),(0,V.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},YG={[G.Duration]:{label:`Timer`,icon:`⏱`,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[G.Rep]:{label:`Reps`,icon:`✕`,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[G.Effort]:{label:`Exercise`,icon:`🏋`,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[G.Rounds]:{label:`Rounds`,icon:`↻`,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[G.Distance]:{label:`Distance`,icon:`📏`,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[G.Resistance]:{label:`Weight`,icon:`⚖`,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[G.Equipment]:{label:`Equipment`,icon:`🧰`,textClass:`text-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border/50`},[G.Action]:{label:`Action`,icon:`⚡`,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[G.Label]:{label:`Label`,icon:`🏷`,textClass:`text-muted-foreground`,bgClass:`bg-muted/30`,borderClass:`border-border/40`}},XG={[G.Rep]:`reps`,[G.Effort]:`movement`,[G.Resistance]:`weight`},ZG=({metric:e,tooltip:t,isFocused:n,onClick:r})=>{let i=YG[e.type],a=e.type===G.Hint,o=e.image??(e.value===void 0?``:String(e.value)),s=i?.label??String(e.type);return(0,H.jsxs)(`span`,{title:t,onClick:r,className:U(`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium`,`pointer-events-auto transition-opacity hover:opacity-80`,i?.bgClass??`bg-muted/30`,i?.textClass??`text-muted-foreground`,i?.borderClass??`border-border/40`,r&&`cursor-pointer`,n&&`font-bold shadow-sm`),children:[(0,H.jsx)(`span`,{children:a?e.icon:i?.icon??`•`}),!a&&(0,H.jsx)(`span`,{children:s}),!a&&o&&(0,H.jsx)(`span`,{className:`font-semibold`,children:o})]})};function QG(e){let t=fa(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function $G(e,t){try{let n=e.coordsAtPos(t);if(!n)return null;let r=e.dom?.getBoundingClientRect?.()??{top:0,left:0},i=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:0};return{top:n.bottom-r.top,left:i.left-r.left,width:i.width}}catch{return null}}var eK=({view:e,cursorVersion:t,getCursorFocusState:n})=>{let[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(null),s=(0,V.useRef)(null),c=(0,V.useCallback)(()=>{if(!e){o(null),i(null);return}let t=(n??KH)(e.state);o(t),i(t?$G(e,t.lineFrom):null)},[e,n]);if((0,V.useEffect)(()=>{c()},[c,t]),(0,V.useEffect)(()=>{if(!e)return;let t=()=>c();return window.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t,!0),()=>{window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t,!0)}},[e,c]),!r||!a?.section)return null;let l=a.allStatements?.filter(e=>e.meta?.line===a.cursorLine-a.section.startLine)??(a.statement?[a.statement]:[]),u=l.flatMap(e=>e.metrics.toArray()).filter(e=>e.type!==G.Sound&&e.type!==G.System&&!(e.type===G.Hint&&!e.icon)),d=wB(u,`runtime-badge`),f=l.flatMap(e=>e.metrics.toArray()),p=[],m=[],h=[];for(let e of f){let t=QG(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;p.includes(t)||(p.push(t),m.push(e))}h.push(...t.diagnostics)}let g=typeof e?.state?.facet==`function`?e.state.facet(kw)?.()??null:null,_=typeof e?.state?.doc?.sliceString==`function`?IH(e.state.doc.sliceString(a.lineFrom,a.lineTo)):null,v=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&_?.equipment.includes(e.token)?`equipment`:`effort`,y=e=>typeof e==`string`&&e.trim()?e:null,b=async t=>{if(!e)return;let n=e.state.doc.sliceString(a.lineFrom,a.lineTo),r=UR.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort…`,sources:[PH(`effort`)]});if(t.dismissed)return;let i=y(t.item.payload);if(!i)return;e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:LH(n,{effort:i})}});return}let i=[..._?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)…`:`Set equipment…`,sources:[PH(`equipment`)]});if(e.dismissed)break;let t=y(e.item.payload);t&&!i.includes(t)&&i.push(t)}((_?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:LH(n,{equipment:i})}})},x=async()=>{if(!e)return;let t=e.state.doc.sliceString(a.lineFrom,a.lineTo),n=UR.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)…`,sources:[PH(`effort`)]});i.dismissed||(r=y(i.item.payload)??void 0);let o=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)…`,sources:[PH(`equipment`)]});if(e.dismissed)break;let t=y(e.item.payload);t&&!o.includes(t)&&o.push(t)}!r&&o.length===0||e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:LH(t,{effort:r,equipment:o})}})},S=async t=>{if(!e||!t.token)return;let n=v(t),r=await UR.getState().open({placeholder:`Replace “${t.token}”…`,sources:[PH(n,t.candidates)]});if(r.dismissed)return;let i=y(r.item.payload);if(!i)return;let o=e.state.doc.sliceString(a.lineFrom,a.lineTo).indexOf(t.token);o<0||e.dispatch({changes:{from:a.lineFrom+o,to:a.lineFrom+o+t.token.length,insert:i}})},C=t=>{let n=XG[t.type];if(!n||!e)return;let r=t.type===G.Effort?`effort`:t.type===G.Equipment?`equipment`:null;if(r&&_?.jsonFrom!==void 0&&_.jsonFrom>=0){b(r);return}cn(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-BIBCbahc.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:t})=>{t(a,e,n)})};return(0,H.jsxs)(`div`,{ref:s,className:U(`cm-metric-inline-panel`,`absolute z-50 pointer-events-none`,`flex items-center gap-2 px-3 h-[28px]`,`bg-background/90 backdrop-blur-sm`,`border-l border-r border-border/50`,`transition-opacity duration-100`),style:{top:r.top,left:r.left,width:r.width,maxWidth:r.width},"aria-live":`polite`,"aria-label":`Metric inline panel`,children:[u.length>0?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-medium shrink-0 select-none`,children:`Metrics:`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[u.map((e,t)=>(0,H.jsx)(ZG,{metric:e,tooltip:e.type===G.Hint?String(e.value??``):d[t]?.tooltip,isFocused:a.focusedMetric===e,onClick:XG[e.type]?()=>C(e):void 0},`${e.type}-${t}`)),m.map(e=>(0,H.jsxs)(`span`,{title:`${e.kind===`effort`?`Effort`:`Equipment`} · click to change source`,onClick:()=>void b(e.kind),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium cursor-pointer hover:opacity-80 bg-muted/40 text-foreground border-border/50`,children:[(0,H.jsx)(`span`,{children:e.kind===`effort`?`🏋`:`🧰`}),(0,H.jsx)(`span`,{className:`font-semibold`,children:e.label}),g&&(0,H.jsx)(`a`,{href:g.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`${e.kind}:${e.slug}`)),_?.malformed&&(0,H.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:`Reference JSON on this line does not parse — fix it in the raw text.`,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,H.jsx)(`span`,{children:`⚠`}),(0,H.jsx)(`span`,{children:`Malformed reference JSON`})]}),h.map((e,t)=>{let n=v(e);return(0,H.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,H.jsx)(`span`,{children:`⚠`}),(0,H.jsx)(`span`,{children:e.token??e.reason}),(0,H.jsx)(`button`,{type:`button`,className:`underline cursor-pointer`,onClick:()=>void S(e),children:`Select existing`}),g&&(0,H.jsx)(`a`,{href:g.createHref(n),className:`underline hover:text-foreground`,children:`Create page`})]},`${e.reason}-${t}`)}),(0,H.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void x(),className:`pointer-events-auto inline-flex items-center px-1.5 py-0.5 rounded border border-dashed border-border/60 text-[10px] text-muted-foreground hover:text-foreground hover:border-primary/50 cursor-pointer`,children:`+ Metric`})]})]}):(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/50 italic select-none`,children:`No metrics on this line`}),(0,H.jsx)(`span`,{className:`ml-auto text-[9px] text-muted-foreground/40 shrink-0 select-none`,children:`Ctrl+↑↓ · adjust value`})]})},tK=new ui,nK=new ui,rK=new ui;async function iK(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 aK(e){let t=await iK(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function oK(e){let t=await iK(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${Yy()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var sK=({noteId:e,noteBlocks:t,sourceRevision:n=0,onIdentityChange:r,onSaved:i,beforeRun:a,onSaveRequest:o,onCommitChange:s,value:c,onChange:l,onDocUpdate:u,onCursorPositionChange:d,onBlur:f,theme:p=`vs`,readonly:m=!1,className:h=``,onStartWorkout:g,onCompleteWorkout:_,onBlocksChange:v,onAddToPlan:y,notePersistence:b,onViewCreated:x,mode:S=`edit`,lineWrapping:w=!0,showLineNumbers:T=!0,enablePreview:E=!0,showFrontmatter:D=!0,enableLinting:O=!0,enableOverlay:A=!1,commands:j,hideDefaultCommands:M=!1,enableInlineRuntime:N=!0,extensions:P,widgetComponents:F,activeSectionId:I,scrollToSectionId:ee,results:te,placeholder:ne})=>{let re=(0,V.useRef)(null),ie=(0,V.useRef)(null),ae=(0,V.useRef)(null),oe=(0,V.useRef)(``);(0,V.useEffect)(()=>{let e=async e=>{if(e.view!==ie.current||!cK(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=lK(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)&&cK(r,n)};if(!r)return null;let{propertyKey:o,from:s}=r,c={"metrics.effort":`effort`,"metrics.equipment":`equipment`,equipment:`equipment`}[o.toLowerCase()];if(c){let e=await MH();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=lK(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}}let l=i.find(e=>e.name.toLowerCase()===o.toLowerCase());if(!l)return null;let u=a.filter(e=>e.type?.toLowerCase()===l.name.toLowerCase());return u.length===0?null:{from:s,options:u.map(e=>({label:e.label,detail:l.label,type:`constant`})),validFor:(e,t,n,r)=>{let i=lK(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}};return dw(e),()=>{fw(e)}},[]);let se=p===`dark`||p===`vs-dark`,ce=RH(ae,b),[L,le]=(0,V.useState)(null),[ue,R]=(0,V.useState)([]),[de,fe]=(0,V.useState)(1),[pe,me]=(0,V.useState)(0),he=I??L,ge=rU(ue,he),[_e,ve]=(0,V.useState)(null),[ye,be]=(0,V.useState)(null),[xe,Se]=(0,V.useState)(!1),Ce=(0,V.useRef)(null),we=(0,V.useRef)(!1),Te=(0,V.useRef)(n??0);(0,V.useEffect)(()=>{Te.current=n??0},[n]);let[Ee,De]=(0,V.useState)(null),Oe=(0,V.useRef)(null),ke=(0,V.useCallback)(async(t,n=!1)=>{let r=ie.current;if(!(!r||we.current)){we.current=!0,De(null);try{let o=await a?.();typeof o==`number`&&(Te.current=o);let s=r.state.field(ZC),c=await hF({noteId:e??C(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:Te.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,C(),e?void 0:`playground`,ce);Ce.current=c,Oe.current=null,Te.current=c.note.sourceRevision,r.dispatch({effects:UC.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),Se(n),be(c.block)}catch(e){De(e instanceof Error?e.message:String(e))}finally{we.current=!1}}},[e,ce,i,a]),Ae=(0,V.useCallback)(()=>{be(null),Se(!1)},[]),je=(0,V.useCallback)(e=>{N&&ke(e,!0)},[N,ke]),Me=(0,V.useRef)(null),Ne=(0,V.useCallback)((e,t)=>{let n=Me.current,r=n!==null&&n.results===t,i=Ce.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(Oe.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&ie.current){let t=ie.current,n=KT(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[Er.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(Me.current={results:t,resultId:a,runBlock:o});let s;try{s=CV(ce).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>_?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{Me.current?.results===t&&(Me.current=null),Oe.current=a},()=>{}),s},[l,_,ce]),Pe=(0,V.useMemo)(()=>{if(M)return[];if(j&&j.length>0)return j;let e=[];return N?e.push({id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:ke}):g&&e.push({id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:g}),e.push({id:`playground`,label:`Playground`,icon:(0,H.jsx)(k,{className:`h-3 w-3`}),splitIcon:(0,H.jsx)(nt,{className:`h-3 w-3`}),splitSuccessIcon:(0,H.jsx)(Zn,{className:`h-3 w-3`}),onClick:e=>{aK(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await oK(e.content);await navigator.clipboard.writeText(t)}}),y&&e.push({id:`plan`,label:`Plan`,icon:(0,H.jsx)(Kt,{className:`h-3 w-3`}),onClick:y}),e},[j,g,y,N,M,ke]),Fe=(0,V.useMemo)(()=>hi({codeLanguages:BH}),[]),Ie=(0,V.useMemo)(()=>[...T?[Qr(),Hr()]:[],Wr(),pi(),kr(),mi(),...w?[Er.lineWrapping]:[],ri.allowMultipleSelections.of(!0),Dr(),Ti(),Ur(),yi(),fi.highest(yr.of([{key:`Tab`,run:e=>Rr(e.state)!==null&&(Ei(e),!0)},{key:`Enter`,run:e=>{let t=e.state.selection.main,n=lK(e.state,t.head),r=e.state.doc.lineAt(t.head);return!t.empty||n?.value.trim()!==``||r.text.slice(t.head-r.from).trim()?!1:(xr(e),ei(e))}}])),yr.of([...Lr,...$r,...li,...ci,...wi,...di,ti,{key:`Mod-s`,run:()=>(o?.(),!0)},{key:`Ctrl-.`,run:e=>{let t=KH(e.state);if(!t?.focusedMetric)return!1;let n=t.focusedMetric.type;return!new Set([`duration`,`rep`,`rounds`,`distance`,`resistance`]).has(n)&&(cn(()=>Promise.resolve().then(()=>HR).then(()=>{cn(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-BIBCbahc.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:n})=>{n(t,e)}).catch(()=>{UR.getState().open({placeholder:`Modify metric…`,sources:[]})})}),void 0),!0)}}]),QT,ZC,BC.of({blocks:t??Aa(c,{sourceRevision:Math.max(1,n),registeredWidgets:F?[...F.keys()]:wa}),sourceRevision:Math.max(1,n),rawContent:c}),VC.of(F?[...F.keys()]:wa),QC,jw.of(D),...E||!D?[iT]:[],...E?[ww,Dw,wH(),jH(),xT,hT(),MT]:[],...O?[rw]:[],pw,lw,cw,...A?[$T]:[],hw,zC,YH,...RT,FC,...F&&F.size>0?[jE(F)]:[],sE({executor:XF,onResultSaved:xV,readOnly:m,noteHref:e=>Cz(`blockContentId`in e||`dataType`in e?hI(e):lI(e))}),zH(e,ce),Er.domEventHandlers({blur:()=>(f?.(),!1)}),Er.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(ZC);r?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision}),l(t.rawContent),u?.(e),dK(e.state,v,oe),e.transactions.some(e=>e.isUserEvent(`input`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||s?.()}if(e.selectionSet||e.docChanged){me(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Rr(e.startState)!==null&&Rr(e.state)===null&&lK(e.state,e.state.selection.main.head)?.value===``&&queueMicrotask(()=>{e.view.state===e.state&&ii(e.view)});let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);d?.(n.number,t-n.from+1);let r=ew(e.state);le(r?.id??null),fe(n.number);let{sections:i}=e.state.field(ZC);R(i)}}),ri.readOnly.of(m),Er.editable.of(!m),...ne?[bi(ne)]:[]],[l,d,f,u,v,r,m,o,s,T,w,E,D,O,A,e,ce,F,ne]);return(0,V.useEffect)(()=>{let e=re.current;if(!e)return;let t=ri.create({doc:c,extensions:[...Ie,tK.of(PC(se)),nK.of(Fe),rK.of([]),...P??[]]}),n=new Er({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{n.hasFocus&&i?.scale===1&&i.height<window.innerHeight&&n.dispatch({effects:Er.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})})})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),ie.current=n,ve(n),e.__codemirrorView=n,x?.(n);let{sections:s}=n.state.field(ZC);R(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;fe(l);let u=ew(n.state);le(u?.id??null);let d=n.state.field(ZC);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),dK(n.state,v,oe),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,ve(null),n.destroy()}},[]),(0,V.useEffect)(()=>{let e=ie.current;if(!e)return;let r=e.state.field(ZC);c===r.rawContent?t&&n!==r.sourceRevision&&e.dispatch({effects:UC.of({blocks:t,sourceRevision:n})}):e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},...t?{effects:WC.of({rawContent:c,blocks:t,sourceRevision:n})}:{}})},[c,t,n]),(0,V.useEffect)(()=>{ie.current&&ie.current.dispatch({effects:tK.reconfigure(PC(se))})},[se]),(0,V.useEffect)(()=>{if(ie.current){let e=[];ie.current.dispatch({effects:[Xr.reconfigure.of([...Ie,tK.of(PC(se)),nK.of(Fe),rK.of(e),...P??[]])]})}},[Ie,P,S,se,Fe]),(0,V.useEffect)(()=>{m||ie.current?.focus()},[m]),(0,V.useEffect)(()=>{if(ee&&ie.current){let e=ie.current,t=e.state.doc.toString().split(`
148
- `),n=-1,r=ee.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,`-`)===ee}return!1}),n>=0&&n<t.length){let t=e.state.doc.line(n+1).from;e.dispatch({selection:{anchor:t,head:t},effects:[Er.scrollIntoView(t,{y:`start`,yMargin:20})]})}}},[ee]),(0,H.jsxs)(`div`,{ref:re,className:`cm-note-editor relative w-full min-w-0 ${h}`,children:[A&&(0,H.jsx)(QH,{view:_e??ie.current,widths:ge.widths,activeSectionId:he,renderSlot:t=>{if(!D&&t.sectionType===`frontmatter`)return null;if(t.sectionType===`time`||t.sectionType===`log`)return(0,H.jsx)(DU,{noteId:e,sectionId:t.sectionId,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,cursorLine:de,docVersion:t.docVersion,commands:Pe,extendedResults:te,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(ZC),n=e.find(e=>e.id===t.sectionId);return(0,H.jsx)(sU,{sectionId:t.sectionId,section:n,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,docVersion:t.docVersion})}return t.sectionType===`widget`&&t.widgetName?(0,H.jsx)(OU,{sectionId:t.sectionId,widgetName:t.widgetName,view:t.view,registry:F??new Map,docVersion:t.docVersion}):(0,H.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,H.jsx)(`div`,{className:`font-medium text-foreground`,children:t.sectionType})})},cursorLine:de}),Ee&&(0,H.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[`Workout not started. `,Ee,` Your draft is kept.`]}),!A&&Pe.length>0&&(0,H.jsx)(qG,{view:_e??ie.current,commands:Pe}),(0,H.jsx)(eK,{view:_e??ie.current,cursorVersion:pe}),ye&&ie.current&&(0,H.jsx)(BG,{block:ye,view:_e??ie.current,onClose:Ae,onCompleteWorkout:Ne,autoStart:xe}),(0,H.jsx)(JG,{sections:ue,isRuntimeActive:ye!==null,editorState:(_e??ie.current)?.state??null,onSelectBlock:je})]})};function cK(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 lK(e,t){if(!cK(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 uK(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=Is().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(ZC).noteBlocks[e.id]?.version??1,createdAt:Date.now(),widgetIds:{}}}function dK(e,t,n){if(!t)return;let r=e.field(ZC).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>uK(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 fK({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,V.useRef)([]),E=(0,V.useCallback)(e=>{T.current=e,a?.(e)},[a]),D=(0,V.useCallback)(()=>{v?.onRun(n,T.current[0]??null)},[v,n]),O=(0,H.jsxs)(H.Fragment,{children:[y,v&&(0,H.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,H.jsx)(Ht,{size:11,fill:`currentColor`}),v.label??`Run`]})]});return(0,H.jsx)(CH,{title:e,subtitle:t,onReset:_,headerActions:O,className:S,children:(0,H.jsxs)(`div`,{className:`flex h-full flex-col min-h-0`,children:[b,(0,H.jsxs)(`div`,{ref:w,className:U(`relative flex-1 min-h-0`,C),children:[(0,H.jsx)(sK,{noteId:i,value:n,onChange:r,onBlocksChange:E,theme:o,readonly:s,showLineNumbers:c,enableOverlay:l,enableInlineRuntime:u,enablePreview:d,showFrontmatter:f,enableLinting:p,commands:m,hideDefaultCommands:h,onViewCreated:g,className:`h-full`}),x]})]})})}function pK({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,H.jsx)(`div`,{className:`h-full`,style:{opacity:t,transition:`opacity 180ms ease`},children:(0,H.jsx)(fK,{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,H.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,H.jsx)(`span`,{children:`Try editing this example ↓`}),e===n?null:(0,H.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 mK(e,t){return e>=t?`split`:`stack`}function hK(e,t){let n=(0,V.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:mK(t,n)}},[e]),[r,i]=(0,V.useState)(n);return(0,V.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:mK(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 gK=e=>Math.max(0,Math.min(1,e)),_K=(e,t,n)=>e+(t-e)*n,vK=e=>1-(1-e)**2;function yK(e,t){return e===``||t===e}var bK={id:``,range:[0,1]};function xK(e,t){if(!t||t.length===0)return{index:-1,stage:bK,t:0,ring:null};let n=gK(e),r=t.map(e=>({...e,start:gK(Math.min(e.range[0],e.range[1])),end:gK(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]??bK,o=(a.end??1)-(a.start??0),s=o>0?gK((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 SK(e,t,n){let r=t-n;return{progress:r>0?gK(-e/r):0,reached:e<=0,inView:e<n&&e+t>0}}function CK(e,t){let n=t/2;for(let t of e)if(t.top<=n&&t.bottom>n)return t.id;return null}var wK=(0,V.createContext)(null);function TK(){return(0,V.useContext)(wK)}function EK({children:e}){let t=(0,V.useRef)(new Map),n=(0,V.useRef)(new Map),r=(0,V.useRef)(null),i=(0,V.useRef)(0),[a,o]=(0,V.useState)(null),s=(0,V.useRef)(null),c=(0,V.useCallback)(e=>{r.current?.gateId===e&&(r.current=null,o(null))},[]),l=(0,V.useCallback)((e,t)=>{r.current={gateId:e,segmentId:t},o(e)},[]),u=(0,V.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=CK(l,e);if(u!==s.current){s.current=u;let e=r.current;e&&e.segmentId!==u&&(r.current=null,o(null))}n.current.forEach((t,n)=>{let r=a.get(n);if(!r||r.height-e<=0)return;let i=SK(r.top,r.height,e);t.onMeasure({slice:xK(i.progress,t.getStages()),progress:i.progress,reached:i.reached})})},[]),d=(0,V.useCallback)(()=>{i.current||=requestAnimationFrame(u)},[u]);(0,V.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,V.useCallback)((e,n)=>(t.current.set(e,n),d(),()=>{t.current.delete(e)}),[d]),p=(0,V.useCallback)((e,t)=>(n.current.set(e,t),d(),()=>{n.current.delete(e)}),[d]),m=(0,V.useCallback)(()=>u(),[u]),h=(0,V.useMemo)(()=>({registerAnchor:f,registerDriver:p,resync:m,capturedGateId:a,captureGate:l,releaseGate:c}),[f,p,m,a,l,c]);return(0,H.jsx)(wK.Provider,{value:h,children:e})}function DK(e,t){let n=TK()?.registerAnchor;(0,V.useEffect)(()=>{if(n)return n(e,()=>t.current)},[n,e,t])}function OK({gateId:e,segmentId:t,className:n,children:r}){let i=TK(),a=(0,V.useRef)(null),[o,s]=(0,V.useState)(!1);if((0,V.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,H.jsx)(`div`,{className:n,children:r});let c=i.capturedGateId===e?`captured`:`yield`;return(0,H.jsxs)(`div`,{"data-scroll-gate":c,"data-gate-id":e,className:`${n??``} flex flex-col`,onFocus:n=>{let r=n.target;r instanceof HTMLElement&&r.closest(`input:not([readonly]):not([disabled]), textarea:not([readonly]):not([disabled]), select:not([disabled]), [contenteditable="true"]`)&&i.captureGate(e,t??null)},onBlur:t=>{(!(t.relatedTarget instanceof Node)||!t.currentTarget.contains(t.relatedTarget))&&i.releaseGate(e)},children:[(0,H.jsx)(`div`,{ref:a,className:`relative min-h-0 flex-1`,children:r}),(o||c===`captured`)&&(0,H.jsx)(`button`,{type:`button`,className:`min-h-11 self-start rounded px-3 py-2 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`,"aria-label":`Scroll ${e.replace(/-/g,` `)} content`,"aria-pressed":c===`captured`,onClick:()=>c===`captured`?i.releaseGate(e):i.captureGate(e,t??null),onKeyDown:t=>{t.key===`Escape`&&i.releaseGate(e)},children:c===`captured`?`Scroll page`:`Scroll panel`})]})}function kK({trackRef:e,height:t,stages:n,activeIndex:r,pane:i,captions:a,status:o,segmentId:s,testId:c,className:l}){let[u,d]=(0,V.useState)(null),f=hK(104,u).mode===`split`,p={status:o,pips:(0,H.jsx)(`div`,{className:`flex items-center gap-1.5`,"aria-hidden":`true`,children:n.map((e,t)=>{let n=r===t;return(0,H.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,H.jsx)(`section`,{ref:e,"data-testid":c,className:l?`relative ${l}`:`relative`,style:{height:t},children:(0,H.jsx)(xH.Provider,{value:p,children:(0,H.jsx)(`div`,{className:`sticky top-[65px] flex h-[calc(100dvh-65px)] flex-col overflow-hidden lg:top-[104px] lg:h-[calc(100dvh-104px)]`,children:(0,H.jsxs)(`div`,{ref:d,className:`mx-auto flex min-h-0 w-full max-w-[1500px] 2xl:max-w-[1720px] flex-1 px-5 pt-2 pb-5 lg:px-10 lg:pt-3 xl:px-16 xl:pb-8 2xl:pb-10 ${f?`flex-row items-stretch gap-[clamp(20px,2.5vw,56px)] xl:gap-12 2xl:gap-16`:`flex-col gap-6 xl:gap-8`}`,children:[(0,H.jsx)(`div`,{className:`relative min-h-0 min-w-0 flex-[3_1_0%]`,children:i}),(0,H.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-[2_1_0%] flex-col`,children:s?(0,H.jsx)(OK,{gateId:`${s}-captions`,segmentId:s,className:`relative min-h-0 flex-1`,children:a}):(0,H.jsx)(`div`,{className:`relative min-h-0 flex-1`,children:a})})]})})})})}function AK(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 jK(e,t,n=`smooth`){let r=AK(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 MK(e,t,n,r){let[i,a]=(0,V.useState)(()=>xK(0,n)),[o,s]=(0,V.useState)(!1),c=(0,V.useRef)(0),l=(0,V.useRef)(i),u=(0,V.useRef)(new Set),d=(0,V.useRef)(0),f=(0,V.useRef)(t);f.current=t;let p=TK(),m=p?.registerDriver,h=(0,V.useRef)(p);h.current=p;let g=(0,V.useId)(),_=r??g,v=(0,V.useRef)(n);v.current=n;let y=(0,V.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,V.useCallback)(()=>{if(d.current=0,f.current)return;let t=e.current;if(!t)return;let n=t.getBoundingClientRect(),r=n.height-window.innerHeight;if(r<=0)return;let i=Math.max(0,Math.min(1,-n.top/r));s(n.top<=0),y(xK(i,v.current),i)},[e,y]),x=(0,V.useCallback)(()=>{if(h.current){h.current.resync();return}b()},[b]),S=(0,V.useCallback)(()=>{d.current||=requestAnimationFrame(x)},[x]);(0,V.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,V.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,V.useCallback)(e=>(u.current.add(e),e(l.current,c.current),()=>{u.current.delete(e)}),[]),w=(0,V.useCallback)(()=>{x()},[x]);return{slice:i,progress:c.current,runwayReached:o,subscribe:C,resync:w}}var NK={reference:!0},PK={start:[[`fences`,`first-workout`],[`measurements`,`actions-comments`],[`system`,`try-it`]],protocols:[[`countdown-countup`,`required-rest`],[`amrap`,`emom`],[`tabata-intervals`,`caps`,`distance-intervals`,`try-it`]],structure:[[`rounds`,`rep-schemes`,`sets`],[`nesting`,`rep-math`,`named-sections`,`try-it`]],metrics:[[`planned-vs-recorded`,`custom-metrics`],[`capture`,`session-rpe`],[`calculated`,`try-it`]],clock:[[`run-next`,`pause-skip`],[`capture-prompts`,`casting`,`provenance`,`try-it`]],wql:[[`planes`,`aggregate`,`filters`,`sources`],[`windows`,`grouping-rollup`,`joins`],[`content`,`pipes`,`try-it`]],dashboards:[[`note-frontmatter`,`avg-tis`,`weekly-tonnage`,`widgets`],[`composer`,`cookbook`,`seeded-boards`,`try-it`]],sessions:[[`intent`,`full-session`],[`nested`,`partner`,`swimming`],[`barbell-cycling`,`climbing`,`try-it`]]};function FK(e,t){let n=e.filter(e=>!NK[e.id]),r=e.filter(e=>NK[e.id]);if(n.length===0)return{groups:[],tail:r};let i=t?PK[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 IK(e){let t=Math.max(1,e.length);return e.map((e,n)=>({id:e.id,range:[n/t,(n+1)/t]}))}var LK=[{src:`/images/hero/editing.png`,alt:`WhiteboardScript editor with live syntax highlighting and inline previews`,eyebrow:`Write`,title:`Type your workout in plain Markdown.`,caption:"Movements, reps, time caps, and rounds — fenced in a familiar ```time block. No drag-and-drop. No proprietary DSL."},{src:`/images/hero/timer.png`,alt:`Live runtime timer HUD counting down an interval with active round and rest indicators`,eyebrow:`Run`,title:`Press Run. The compiler takes over.`,caption:`Your Markdown becomes a live wallclock. The JIT engine dispatches rounds, counts reps, and tracks rest — all offline.`},{src:`/images/hero/journal.png`,alt:`Unified Library listing journal notes, Catalog sessions, and dated posts`,eyebrow:`Library`,title:`Browse Notes, Sessions, and Posts in one Library.`,caption:`Your dated journal entries and preloaded Catalog benchmarks live in one unified surface. Search, filter by source, or clone to today’s entry.`},{src:`/images/hero/results.png`,alt:`WQL Metric Explorer displaying volume trends and embedded dashboard blocks`,eyebrow:`Query`,title:`Ask questions with Wod Query Language (WQL).`,caption:`Aggregate volume, track TIS intensity trends, or embed live query and dashboard blocks directly in your Markdown notes.`}];function RK({slides:e=LK,className:t}){let n=(0,V.useRef)(null),[r,i]=(0,V.useState)(0);(0,V.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,H.jsxs)(`div`,{className:U(`relative w-full`,t),children:[(0,H.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,H.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,H.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,H.jsx)(`img`,{src:t.src,alt:t.alt,loading:n===0?`eager`:`lazy`,className:`h-full w-full object-cover`})}),(0,H.jsxs)(`div`,{className:`flex w-full flex-col gap-2 sm:w-1/2 sm:gap-3`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-[0.24em] text-primary/80`,children:t.eyebrow}),(0,H.jsx)(`h3`,{className:`text-2xl font-black tracking-[-0.04em] text-foreground sm:text-3xl`,children:t.title}),(0,H.jsx)(`p`,{className:`text-sm leading-7 text-muted-foreground sm:text-base`,children:t.caption}),(0,H.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground`,children:[(0,H.jsxs)(`span`,{className:`text-primary`,children:[`Step `,n+1]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,H.jsx)(`span`,{children:e.length})]})]})]},t.src))}),(0,H.jsx)(`div`,{className:`mt-4 flex items-center justify-center gap-2`,children:e.map((e,t)=>(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Go to slide ${t+1}: ${e.title}`,"aria-current":t===r?`true`:`false`,className:U(`h-2 rounded-full transition-all`,t===r?`w-8 bg-primary`:`w-2 bg-border hover:bg-muted-foreground/40`)},e.src))})]})}var zK=`wodwiki:text-filter-navigation`,BK=({paramName:e=`q`,placeholder:t=`Search…`,autoFocus:n=!1,className:r,navigationScope:i,inputTestId:a})=>{let[o,s]=Gt(e,{defaultValue:``}),c=i??e,l=(0,V.useRef)(null);return(0,V.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,H.jsxs)(`div`,{className:U(`flex items-center gap-3 px-6 lg:px-10 pb-3`,r),children:[(0,H.jsx)(en,{className:`size-5 text-muted-foreground shrink-0`}),(0,H.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(zK,{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,H.jsx)(`button`,{onClick:()=>s(``),"aria-label":`Clear`,className:`text-muted-foreground hover:text-foreground transition-colors text-lg leading-none`,children:`×`})]})};function VK(e){let t=[],n=!1;for(let r of e){if(r.trim()===`---`){n=!n;continue}n||t.push(r)}return t}function HK(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 UK(e){return new Date(e).toISOString().slice(0,10)}function WK(e,t){let n=t.trim().toLowerCase();return!n||e.name.toLowerCase().includes(n)||e.content.toLowerCase().includes(n)||e.date!==void 0&&UK(e.date).includes(n)}function GK(e){if(!e)return null;let t=VK(Db(e).split(`
149
- `)).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```"))[0];return t?HK(t):null}var KK=({category:e,workoutItems:t,onSelect:n,showSearch:r=!0,variant:i=`card`,className:a,navigationScope:o=`q`,getItemActions:s})=>{let[c]=Gt(`q`,{defaultValue:``}),[l,u]=(0,V.useState)(0),[d,f]=(0,V.useState)(0),p=(0,V.useRef)([]),m=(0,V.useMemo)(()=>t.filter(t=>t.category===e&&t.name.toLowerCase()!==`readme`).filter(e=>WK(e,c)),[t,e,c]),h=(0,V.useMemo)(()=>m.map(e=>({item:e,preview:GK(e.content),actions:s?.(e)??[{id:`open`,label:`Open`,onSelect:n}]})),[m,s,n]);return(0,V.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,V.useEffect)(()=>{p.current=[]},[h]),(0,V.useEffect)(()=>{u(0),f(0)},[c]),(0,V.useEffect)(()=>{(p.current[l]?.[d])?.scrollIntoView({block:`nearest`,inline:`nearest`})},[d,l]),(0,V.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(zK,e),()=>{window.removeEventListener(zK,e)}},[h,o,d,l]),(0,H.jsxs)(`div`,{className:U(`flex flex-col`,i===`card`&&`rounded-3xl border border-border bg-card overflow-hidden shadow-2xl shadow-black/5`,a),children:[r?(0,H.jsx)(`div`,{className:`border-b border-border/60 bg-background/95 backdrop-blur-md`,children:(0,H.jsx)(BK,{placeholder:`Filter collection workouts…`,className:`pt-3`,navigationScope:o})}):null,h.length===0?(0,H.jsx)(`div`,{className:`px-6 py-10 text-sm font-medium text-muted-foreground`,children:`No workouts found.`}):(0,H.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,H.jsx)(`div`,{role:`option`,"aria-selected":n,className:U(`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,H.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:U(`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,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-10 rounded-xl bg-muted flex items-center justify-center transition-colors`,children:(0,H.jsx)(ce,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate uppercase tracking-tight`,children:e.item.displayName??e.item.name}),e.preview?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground font-medium truncate mt-1`,children:e.preview}):null]}),e.item.date===void 0?null:(0,H.jsx)(`span`,{className:`shrink-0 self-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:HP(new Date(e.item.date))}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground shrink-0 transition-opacity`})]}):r.label},r.id)})},e.item.id)})})]})};function qK(){return(0,V.useEffect)(()=>{WF().catch(e=>console.warn(`[queryService] page source population failed`,e))},[]),(0,V.useSyncExternalStore)(qF,KF)}function JK(e,t){let n=e.find(e=>e.key===t&&!e.negate);return n&&n.values.length===1?n.values[0].value:null}function YK(e){let t=e.trim();if(!t.startsWith(`:`))return null;let n=Y(t);if(n.error||!tm(n))return null;let r=`?q=${encodeURIComponent(t)}`;switch(n.target){case`effort`:return`/efforts${r}`;case`session`:case`segment`:case`event`:return`/sessions${r}`;case`note`:case`block`:{let e=JK(n.filters,`notebook`)??JK(n.filters,`catalog`);if(e){let t=xa(e);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:`/c/${encodeURIComponent(t)}${r}`}let t=JK(n.filters,`source`);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:t===`feeds`||t===`notebooks`||t===`notebook`||t===`guides`?`/feeds${r}`:JK(n.filters,`type`)===`dashboard`?`/dashboards${r}`:`/journal${r}`}default:return null}}var XK=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 ZK(e){let t=e.split(`.`).pop()?.split(`?`)[0]?.toLowerCase()??``;return XK.has(t)}function QK(e){return/^https?:\/\//.test(e)||e.startsWith(`//`)}function $K({queryText:e,widgetType:t,widgetError:n}){return qK()?(0,H.jsx)(`div`,{className:`my-5 not-prose`,children:(0,H.jsx)(OC,{query:e,widgetType:t,widgetError:n,executor:XF,readOnly:!0,noteHref:e=>Cz(`blockContentId`in e||`dataType`in e?hI(e):lI(e))})}):(0,H.jsx)(`div`,{className:`my-5 not-prose text-xs text-muted-foreground py-2`,children:`Loading…`})}function eq(e){let{meta:t,body:n}=Sb(e);return Object.keys(t).length===0&&n===e?{fields:null,body:e}:{fields:t,body:n.trim()}}var tq={table({children:e}){return(0,H.jsx)(`div`,{className:`my-6 overflow-x-auto rounded-xl border border-border`,children:(0,H.jsx)(`table`,{className:`w-full text-sm border-collapse`,children:e})})},thead({children:e}){return(0,H.jsx)(`thead`,{className:`bg-muted/50 text-left`,children:e})},tbody({children:e}){return(0,H.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e})},tr({children:e}){return(0,H.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e})},th({children:e}){return(0,H.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,H.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,H.jsxs)(`figure`,{className:`my-6`,children:[(0,H.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,H.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=YK(e);if(r)return(0,H.jsx)(Wn,{to:r,className:`underline underline-offset-2 transition-colors text-primary hover:text-primary/70`,children:t})}let r=QK(n),i=ZK(n);return(0,H.jsxs)(`a`,{href:n,rel:r?`noopener noreferrer`:void 0,target:r||i?`_blank`:void 0,className:U(`underline underline-offset-2 transition-colors`,i?`text-primary font-medium`:`text-primary hover:text-primary/70`),children:[t,r&&(0,H.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`↗`}),i&&!r&&(0,H.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(`
150
- `))return(0,H.jsx)(`code`,{className:`px-1.5 py-0.5 rounded-md bg-muted font-mono text-[0.85em] text-foreground`,children:e});if(n===`query`||n.startsWith(`query:`)||n.startsWith(`query `)){let t=(typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``)).trim(),r=n.replace(/^query[:\s]?/,``).trim(),i=r?Jg(r):void 0;return(0,H.jsx)($K,{queryText:t,widgetType:i?.type,widgetError:i?.error})}return(0,H.jsxs)(`div`,{className:`my-5 rounded-xl overflow-hidden border border-border`,children:[n&&(0,H.jsx)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-muted border-b border-border`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black tracking-widest uppercase text-muted-foreground`,children:n})}),(0,H.jsx)(`pre`,{className:`overflow-x-auto p-4 bg-muted/30`,children:(0,H.jsx)(`code`,{className:`font-mono text-sm text-foreground`,children:e})})]})},h1({children:e,id:t}){return(0,H.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,H.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,H.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,H.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,H.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,H.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,H.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,H.jsx)(`li`,{className:`leading-relaxed`,children:e})},blockquote({children:e}){return(0,H.jsx)(`blockquote`,{className:`my-5 pl-4 border-l-2 border-primary/40 text-muted-foreground italic text-sm`,children:e})},hr(){return(0,H.jsx)(`hr`,{className:`my-8 border-border/50`})},strong({children:e}){return(0,H.jsx)(`strong`,{className:`font-black text-foreground`,children:e})},em({children:e}){return(0,H.jsx)(`em`,{className:`italic text-foreground/80`,children:e})}},nq={...tq,p({children:e}){return(0,H.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=V.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,H.jsxs)(`span`,{className:`flex flex-col select-none mt-4 w-full gap-5 sm:gap-7`,children:[(0,H.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,H.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Markdown`}),`.`]}),(0,H.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,H.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,H.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,H.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Analytics`}),`.`]})]}):(0,H.jsx)(`strong`,{className:`font-black text-foreground`,children:e})}},rq={...tq,p({children:e}){return(0,H.jsx)(`p`,{className:`text-base lg:text-lg font-medium text-foreground/75 leading-relaxed my-4 first:mt-0`,children:e})}},iq=[Un];function aq(e){return e.startsWith(`:`)?e:Pn(e)}function oq(e){return e.type===`text`&&typeof e.value==`string`?e.value:(e.children??[]).map(oq).join(``)}function sq(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu,``).replace(/ /g,`-`).replace(/-+/g,`-`)||`heading`}var cq=()=>e=>{let t=new Map,n=e=>{if(e.tagName&&/^h[1-6]$/.test(e.tagName)){let n=sq(oq(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 lq({fields:e}){let t=Object.entries(e);return t.length===0?null:(0,H.jsxs)(`div`,{className:`my-6 rounded-xl border border-border bg-muted/30 overflow-hidden`,children:[(0,H.jsx)(`div`,{className:`px-4 py-2 border-b border-border bg-muted/50`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black tracking-[0.2em] uppercase text-muted-foreground`,children:`Metadata`})}),(0,H.jsx)(`dl`,{className:`divide-y divide-border/50`,children:t.map(([e,t])=>(0,H.jsxs)(`div`,{className:`flex items-baseline gap-4 px-4 py-2`,children:[(0,H.jsx)(`dt`,{className:`text-[11px] font-semibold text-muted-foreground uppercase tracking-wide min-w-[100px] shrink-0`,children:e}),(0,H.jsx)(`dd`,{className:`text-sm text-foreground break-words`,children:Array.isArray(t)?t.join(`, `):String(t)})]},e))})]})}var uq={default:tq,heroLead:nq,heroBody:rq};function dq({prose:e,className:t,variant:n=`default`}){if(!e)return null;let{fields:r,body:i}=eq(e);return(0,H.jsxs)(`div`,{className:U(`prose-canvas`,t),children:[r&&(0,H.jsx)(lq,{fields:r}),i&&(0,H.jsx)(gn,{remarkPlugins:iq,rehypePlugins:[cq],urlTransform:aq,components:uq[n],children:i})]})}var fq=({activations:e,fullBleed:t,runState:n,deps:r})=>{if(e.length===0)return null;let i=e[0];if(YM(i)&&n){let a=e.slice(1),o=n.isReconnect?(0,H.jsxs)(`button`,{onClick:n.onReconnect,className:U(`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,H.jsx)(Ye,{className:`size-3.5`}),`View`]}):(0,H.jsxs)(`button`,{type:`button`,onClick:n.onRun,className:U(`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||Ht;return(0,H.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,H.jsx)(`span`,{children:i.label})]});return(0,H.jsxs)(`div`,{className:U(`flex flex-wrap items-center gap-4 mt-8`,t&&`justify-center`),children:[o,a.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(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,H.jsx)(`div`,{className:U(`flex flex-wrap gap-4 mt-8`,t&&`justify-center`),children:e.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,r),className:U(`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))})},pq=({examples:e,activeIndex:t,onSelect:n})=>e.length===0?null:(0,H.jsx)(`div`,{className:`mt-6 rounded-2xl border border-border/70 bg-card/80 backdrop-blur-sm`,children:(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-3`,children:e.map((e,r)=>{let i=r===t,a=e.anchor===!0&&!i,o=!!e.badge&&a;return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(r),"aria-current":i?`true`:void 0,className:U(`relative rounded-full px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] transition-all active:scale-95`,i?`bg-primary text-primary-foreground shadow-lg shadow-primary/25`:a?`border border-brand bg-brand/5 text-brand-deep hover:bg-brand/10 dark:text-brand-light`:`border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground`),children:[e.label,o?(0,H.jsx)(`span`,{className:`ml-2 inline-block rounded-pill bg-brand px-1.5 py-0.5 align-middle text-[8px] font-black leading-none tracking-[0.12em] text-background`,children:e.badge}):null]},`${e.label}-${r}`)})})}),mq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`path`,{d:`M35 35 L65 35 L65 45 L45 45 L45 65 L35 65 Z`,fill:`url(#struct-grad)`}),(0,H.jsx)(`path`,{d:`M55 45 L65 45 L65 65 L45 65 L45 55 L55 55 Z`,fill:`url(#struct-grad)`,opacity:`0.7`})]}),hq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`5`,fill:`url(#proto-grad)`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`15`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`2`,strokeDasharray:`4 2`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`25`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`1`,opacity:`0.5`}),(0,H.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:`25`,stroke:`url(#proto-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),gq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`complex-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#F50057`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#D500F9`,stopOpacity:1}})]})}),(0,H.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,H.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)`})]}),_q=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsxs)(`defs`,{children:[(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]}),(0,H.jsxs)(`filter`,{id:`glow`,x:`-20%`,y:`-20%`,width:`140%`,height:`140%`,children:[(0,H.jsx)(`feGaussianBlur`,{stdDeviation:`3`,result:`blur`}),(0,H.jsx)(`feComposite`,{in:`SourceGraphic`,in2:`blur`,operator:`over`})]})]}),(0,H.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,H.jsx)(`path`,{d:`M55 20 L30 55 L45 55 L40 85 L70 45 L55 45 Z`,fill:`url(#basics-grad)`,filter:`url(#glow)`})]}),vq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`text`,{x:`50`,y:`65`,fontFamily:`monospace`,fontSize:`40`,fontWeight:`bold`,fill:`url(#basics-grad)`,textAnchor:`middle`,children:`10`})]}),yq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`rect`,{x:`30`,y:`30`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,H.jsx)(`rect`,{x:`30`,y:`45`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,H.jsx)(`rect`,{x:`30`,y:`60`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`})]}),bq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.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`})]}),xq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.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,H.jsx)(`text`,{x:`50`,y:`30`,fontFamily:`monospace`,fontSize:`12`,fill:`url(#struct-grad)`,textAnchor:`middle`,children:`21-15-9`})]}),Sq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`path`,{d:`M35 35 H65 V55 L50 70 L35 55 Z`,fill:`url(#proto-grad)`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`45`,r:`4`,fill:`#0b1326`})]}),Cq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`rect`,{x:`30`,y:`60`,width:`10`,height:`15`,fill:`url(#metric-grad)`}),(0,H.jsx)(`rect`,{x:`45`,y:`40`,width:`10`,height:`35`,fill:`url(#metric-grad)`}),(0,H.jsx)(`rect`,{x:`60`,y:`25`,width:`10`,height:`50`,fill:`url(#metric-grad)`})]}),wq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,H.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,H.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`})]}),Tq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`dialect-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#76FF03`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00E676`,stopOpacity:1}})]})}),(0,H.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,H.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 Eq(e){switch(e){case`trophy`:return _q;case`dumbbell`:return ce;case`timer`:return hq;case`play`:return Ht;case`blocks`:return mq;case`puzzle`:return gq;case`activity`:return Cq;case`file-text`:return Tq;default:return Ue}}function Dq(e){switch(e){case`basics-movement`:return _q;case`basics-reps`:return vq;case`basics-load`:return yq;case`structure-rounds`:case`complex-rounds`:case`protocols-rounds`:return bq;case`structure-repscheme`:return xq;case`protocols-timer`:case`complex-time`:return hq;case`protocols-tag`:return Sq;case`metrics-custom`:return Cq;case`metrics-calc`:return wq;case`dialects-log`:case`dialects-climb`:return Tq;default:return null}}function Oq({quest:e,onClick:t,className:n,compact:r=!1,disabled:i=!1}){let a=Dq(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:U(`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,H.jsxs)(H.Fragment,{children:[a?(0,H.jsxs)(`span`,{className:U(`relative shrink-0 mt-0.5`,r?`size-5`:`size-6`),children:[(0,H.jsx)(a,{className:`w-full h-full`}),e.isCompleted&&(0,H.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,H.jsx)(Zn,{className:`size-2`,strokeWidth:3})})]}):(0,H.jsx)(`span`,{className:U(`mt-0.5 shrink-0`,e.isCompleted?`text-primary`:`text-muted-foreground/50`),"aria-hidden":`true`,children:e.isCompleted?(0,H.jsx)(yn,{className:r?`size-3.5`:`size-4`}):(0,H.jsx)(Pt,{className:r?`size-3.5`:`size-4`})}),(0,H.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`p`,{className:U(`font-semibold`,e.isCompleted?`text-foreground line-through decoration-primary/40`:`text-foreground`,r&&`text-xs`),children:e.label}),e.desc&&!r&&(0,H.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:e.desc}),(0,H.jsx)(`p`,{"data-testid":`challenge-hint-${e.id}`,className:U(`mt-1 text-xs`,e.isCompleted||e.result?.pass?`text-primary/80`:`text-muted-foreground`),children:s})]})]});return t?(0,H.jsx)(`button`,{type:`button`,onClick:t,disabled:i,...c,children:l}):(0,H.jsx)(`div`,{...c,children:l})}function kq(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 Aq=({section:e,idx:t,prose:n,blockId:r,keySuffix:i,showHeading:a=!0,showEyebrow:o=!0,renderButtons:s=!0,isActive:c=!1,hasViewDef:l=!1,runState:u,deps:d,onExampleSelect:f,selectedExampleIndex:p,chapters:m=[],challengeQuests:h=[],isCollection:g=!1,collectionSlug:_=null,workoutItems:v=[],handleSelectWorkout:y,onScrollToSection:b,variant:x=`default`})=>{let S=!!e.isFullBleed,C=!!e.isDark&&x!==`caption`,w=e.density,T=tP[e.theme||`slate`]??tP.slate,E=e.examples??[],D=t===-1,O=V.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`?kq(a.text.trim()):{lead:``,rest:``},c=e.proseChunks.slice(n+1);return(0,H.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,H.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,H.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,H.jsxs)(`div`,{className:`relative max-w-2xl w-full text-center`,children:[o&&(0,H.jsx)(dq,{prose:o,variant:`heroLead`,className:`mb-5`}),s&&(0,H.jsx)(dq,{prose:s,variant:`heroBody`,className:`mb-2`}),c.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,H.jsx)(dq,{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,H.jsx)(`div`,{className:`my-4 flex justify-center`,children:(0,H.jsx)(Oq,{quest:n,onClick:()=>b?.(r),compact:!0})},`hero-challenge-${t}`):null}return null}),t.length>0&&(0,H.jsx)(fq,{activations:t.map((e,t)=>JM(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,H.jsxs)(`div`,{id:r,"data-section-id":i==="default"||i===`before-workouts`?e.id:void 0,className:U(`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,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`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,H.jsx)(`div`,{className:U(`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,H.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,H.jsxs)(`div`,{className:U(`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,H.jsx)(`div`,{className:`mb-4 flex items-center gap-2 select-none min-h-[14px]`,children:O.quest.isCompleted?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse`}),`Challenge Complete`]}):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-muted-foreground/80 bg-muted/60 px-2 py-0.5 rounded-full border border-border/50`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500`}),O.chapterTitle,`: Challenge Pending`]})}),a?(0,H.jsx)(`h2`,{className:U(`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,H.jsx)(dq,{prose:n,className:t===0?`mb-6`:`mt-4 mb-6`},`prose-${t}`):null}if(e.kind===`button`)return(0,H.jsx)(fq,{activations:[JM(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,H.jsx)(`div`,{className:`my-6`,children:(0,H.jsx)(RK,{})},`hero-carousel-${t}`);if(e.widget===`workouts-list`&&g&&_&&y)return(0,H.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card my-6`,children:(0,H.jsx)(`div`,{className:`w-full mx-auto`,children:(0,H.jsx)(KK,{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,H.jsx)(`div`,{className:`my-4`,children:(0,H.jsx)(Oq,{quest:n,onClick:()=>b?.(r),compact:!0})},`challenge-${t}`):null}return null}),E.length>0?(0,H.jsx)(pq,{examples:E,activeIndex:Math.min(p,E.length-1),onSelect:t=>f(e,t)}):null,s&&A?(0,H.jsx)(fq,{activations:e.buttons.map((e,t)=>JM(e,t)),fullBleed:S,runState:l?u:void 0,deps:d}):null]})]},`${e.id}-${i}`)};function jq({sections:e,activeIndex:t,part:n,args:r}){return(0,H.jsx)(`div`,{className:`h-full min-h-0 pr-1`,"data-testid":`guide-captions-${n}`,children:e.map((e,n)=>{let i=n===t;return(0,H.jsx)(`div`,{className:`absolute inset-0 min-h-0 overflow-y-auto transition-opacity duration-300 ${i?`opacity-100`:`pointer-events-none invisible opacity-0`}`,"aria-hidden":!i,children:(0,H.jsx)(Aq,{section:e,idx:n,blockId:`guide-caption-${e.id}`,keySuffix:`caption`,variant:`caption`,isActive:i,hasViewDef:r.hasViewDef??!0,runState:r.runState,deps:r.deps,onExampleSelect:r.onExampleSelect,selectedExampleIndex:r.selectedExamples[e.id]??0,chapters:r.chapters,challengeQuests:r.challengeQuests,onScrollToSection:r.onScrollToSection})},e.id)})})}function Mq({sections:e,part:t,partCount:n,title:r,pane:i,cardArgs:a,onActivateSection:o}){let s=(0,V.useRef)(null),c=(0,V.useMemo)(()=>IK(e),[e]),{slice:l,subscribe:u}=MK(s,!1,c),d=(0,V.useRef)(e);d.current=e;let[f,p]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=s.current;if(!e||typeof IntersectionObserver>`u`){p(!0);return}let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(p(!0),t.disconnect())},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let m=()=>{let e=s.current;if(!e)return!1;let{top:t,bottom:n}=e.getBoundingClientRect();return t<=0&&n>window.innerHeight},[h,g]=(0,V.useState)(!1);(0,V.useEffect)(()=>u(()=>{let e=m();g(t=>t===e?t:e)}),[u]);let _=(0,V.useRef)(!1),v=(0,V.useRef)(-1),y=(0,V.useRef)(o);y.current=o,(0,V.useEffect)(()=>{let e=_.current,t=v.current;if(_.current=h,v.current=l.index,!h||e&&t===l.index)return;let n=d.current[l.index];n&&y.current(n)},[h,l.index]);let b=e[l.index]??null;return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`header`,{"data-testid":`guide-runway-header-${t}`,className:`mx-auto w-full max-w-[1500px] px-6 pt-12 pb-6 lg:px-12`,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[`Part `,t,` / `,n]}),(0,H.jsx)(`h2`,{className:`mt-1 text-xl font-black uppercase tracking-tight text-foreground`,children:r})]}),(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(kK,{trackRef:s,height:`${(e.length+1)*100}vh`,stages:c,activeIndex:l.index,pane:f?i:null,captions:(0,H.jsx)(jq,{sections:e,activeIndex:l.index,part:t,args:a}),status:(0,H.jsxs)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[String(l.index+1).padStart(2,`0`),b?` — ${b.heading}`:``]}),testId:`guide-runway-${t}`}),e.map((t,n)=>(0,H.jsx)(`span`,{id:t.id,"data-section-id":t.id,"aria-hidden":`true`,className:`pointer-events-none absolute left-0 h-px w-px`,style:{top:`calc((100% - 100vh) * ${n/e.length} + 50vh + 120px)`}},t.id))]})]})}function Nq({sections:e,groupKey:t,title:n,pane:r,cardArgs:i,onActivateSection:a}){let{groups:o,tail:s}=FK(e,t);return(0,H.jsxs)(H.Fragment,{children:[o.map((e,t)=>(0,H.jsx)(Mq,{sections:e,part:t+1,partCount:o.length,title:n,pane:r,cardArgs:i,onActivateSection:a},e[0]?.id??t)),s.length>0&&(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] px-6 lg:px-12`,"data-testid":`guide-static-tail`,children:(0,H.jsx)(`div`,{className:`lg:max-w-[50%]`,children:s.map((e,t)=>(0,H.jsx)(Aq,{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 Pq(){let e=jP(),{pathname:t}=mt(),n=(0,V.useMemo)(()=>qN(e).flatMap(e=>e.action?.type===`route`?[{id:e.id,label:e.label,to:e.action.to}]:[]),[e]);if(n.length===0)return null;let r=n.findIndex(e=>e.to===t),i=r>=0,a=i&&n.length>1?(r+1)%n.length:-1;return(0,H.jsx)(`nav`,{"aria-label":i?`What’s Next`:`Syntax & Guides`,"data-testid":`guide-index-footer`,className:`border-t border-border px-6 py-12 xl:py-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col rounded-lg border border-border overflow-hidden`,children:[(0,H.jsxs)(`h2`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[i?`What’s Next`:`Syntax & Guides`,` · `,n.length]}),(0,H.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:n.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(Wn,{to:e.to,"aria-current":t===r?`page`:void 0,className:U(`flex flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,t===r&&`bg-muted/50`),children:[(0,H.jsxs)(`span`,{className:`flex w-full items-baseline justify-between gap-3`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.label}),t===a&&(0,H.jsx)(`span`,{className:`text-xs font-semibold text-primary`,"data-testid":`guide-next-marker`,children:`Next →`})]}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.to})]})},e.id))})]})})}var Fq=`22rem`,Iq=`42rem`,Lq=`20rem`,Rq=`calc(100dvh - var(--canvas-sticky-top) - 2rem)`;function zq(e){return{editorWidth:e||`50%`,editorMinWidth:Fq,editorMaxWidth:Iq,editorMinHeight:Lq,editorMaxHeight:Rq}}function Bq(e){let t=Math.max(1,e.split(`
151
- `).length);return`calc(${Math.min(560,Math.max(180,t*22))}px + 3.5rem)`}function Vq(e,t){return{"--canvas-editor-width":e.editorWidth,"--canvas-editor-min-width":e.editorMinWidth,"--canvas-editor-max-width":e.editorMaxWidth,"--canvas-editor-min-height":e.editorMinHeight,"--canvas-editor-max-height":e.editorMaxHeight,"--canvas-editor-preferred-height":Bq(t)}}var Hq=(e,t,n)=>(0,H.jsx)(Aq,{section:e,idx:t,blockId:e.id,keySuffix:`default`,isActive:n.activeSectionId===e.id,hasViewDef:n.hasViewDef,runState:n.runState,deps:n.deps,onExampleSelect:n.handleExampleSelect,selectedExampleIndex:n.selectedExamples[e.id]??0,chapters:n.chapters,challengeQuests:n.challengeQuests,isCollection:n.isCollection,collectionSlug:n.collectionSlug,workoutItems:n.workoutItems,handleSelectWorkout:n.handleSelectWorkout,onScrollToSection:n.onScrollToSection},`${e.id}-default`),Uq=({heroSlot:e,mobilePanel:t,desktopPanel:n,stickyAlign:r=`right`,editorWidth:i=`50%`,contentSections:a,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,activeSectionId:u,selectedExamples:d,runState:f,deps:p,handleExampleSelect:m,hasWorkoutsTag:h,hasViewDef:g,chapters:_=[],challengeQuests:v=[],onScrollToSection:y,editorAppearsAtSectionId:b})=>{let x=b?a.findIndex(e=>e.id===b):-1,S=x>0&&!!n,C={activeSectionId:u,selectedExamples:d,handleExampleSelect:m,hasViewDef:g,runState:f,deps:p,chapters:_,challengeQuests:v,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,onScrollToSection:y},w=S?{width:`calc(100% - ${i})`,flexBasis:`calc(100% - ${i})`,maxWidth:`calc(100% - ${i})`}:{},T=o&&s&&c?(0,H.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card`,children:(0,H.jsx)(`div`,{className:`w-full mx-auto`,children:(0,H.jsx)(KK,{category:s??``,workoutItems:c??[],onSelect:l,showSearch:!1,variant:`flat`})})}):null;if(S){let i=a.slice(0,x),o=a.slice(x);return(0,H.jsxs)(H.Fragment,{children:[e,i.map((e,t)=>Hq(e,t,C)),(0,H.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,H.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[t,o.map((e,t)=>Hq(e,t,C)),T]}),r===`right`&&n]})]})}return(0,H.jsxs)(H.Fragment,{children:[t,(0,H.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,H.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[e,a.map((e,t)=>Hq(e,t,C)),T]}),r===`right`&&n]})]})},Wq=({activations:e,runState:t,deps:n})=>{if(e.length===0)return null;let r=e[0];if(YM(r)&&t){let i=e.slice(1),a=t.isReconnect?(0,H.jsxs)(`button`,{onClick:t.onReconnect,className:`flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full border transition-all active:scale-95 border-amber-500/40 bg-amber-500/15 text-amber-600 hover:bg-amber-500/20 dark:text-amber-400`,children:[(0,H.jsx)(Ye,{className:`size-3.5`}),`View`]}):(0,H.jsxs)(`button`,{type:`button`,onClick:t.onRun,className:`flex items-center gap-2 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest rounded-full shadow-lg shadow-primary/25 min-h-[44px] px-6 py-2 text-xs`,children:[(()=>{let e=r.icon||Ht;return(0,H.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,H.jsx)(`span`,{children:r.label})]});return(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 justify-end pt-3 px-1`,children:[a,i.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full bg-muted border border-border text-foreground hover:bg-muted/80 transition-all active:scale-95`,children:e.label},e.id||t))]})}return(0,H.jsx)(`div`,{className:`flex flex-wrap gap-3 justify-end pt-3 px-1`,children:e.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full transition-all active:scale-95 bg-primary text-primary-foreground shadow-lg shadow-primary/25 hover:scale-[1.04]`,children:e.label},e.id||t))})},Gq=({variant:e,panelTitle:t,panelSubtitle:n,panelContent:r,panelThemeClass:i,headerActions:a,showPanelButtons:o=!1,viewDefButtons:s,runState:c,deps:l,width:u,source:d=``})=>{let f=r,p=o&&s&&s.length>0?(0,H.jsx)(Wq,{activations:s.map((e,t)=>JM(e,t)),runState:c,deps:l}):null;return e===`desktop`?(0,H.jsxs)(`div`,{className:`self-start sticky hidden lg:flex flex-col p-6 pt-8 pb-8 gap-3`,style:{top:`104px`,height:`calc(100vh - 104px)`,width:`clamp(var(--canvas-editor-min-width), var(--canvas-editor-width), var(--canvas-editor-max-width))`,...Vq(zq(u),d)},children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col justify-center py-4`,children:(0,H.jsx)(`div`,{className:`h-[min(var(--canvas-editor-preferred-height),var(--canvas-editor-max-height))] min-h-[var(--canvas-editor-min-height)] max-h-[var(--canvas-editor-max-height)] flex flex-col w-full`,children:f})}),p]}):(0,H.jsx)(`div`,{className:`lg:hidden sticky z-20 shrink-0 px-4 pt-2 pb-1`,"data-page-sticky-boundary":`true`,style:{top:`65px`,height:`min(var(--canvas-editor-preferred-height), calc(100dvh - 65px - 1rem))`,minHeight:`18rem`,"--canvas-editor-preferred-height":Bq(d)},children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 h-full`,children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:f}),p]})})},Kq=({heroSlot:e,children:t})=>(0,H.jsxs)(`section`,{className:`relative border-b border-border/50`,children:[e,t]}),qq=new Set([G.Duration,G.Time]);function Jq(e){return e.metrics.some(e=>e.type===G.Hint&&e.value===`domain.wod`)}function Yq(e){return e?e.filter(e=>!Jq(e)&&e.metrics.some(e=>e.type===G.Effort)).length:0}function Xq(e){if(!e)return 0;let t=0;for(let n of e)if(!Jq(n))for(let e of n.metrics)e.type===G.Rounds&&typeof e.value==`number`&&(t+=e.value);return t}function Zq(e){return e?e.some(e=>!Jq(e)&&e.metrics.some(e=>qq.has(e.type))):!1}function Qq(e){return e?e.some(e=>!Jq(e)&&e.metrics.some(e=>e.type===G.Rep)):!1}function $q(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function eJ(e,t){return typeof e==`string`&&e.length>0?e:typeof e==`number`?String(e):null}var tJ={"has-movement":e=>{let t=Yq(e.statements);return t>0?{pass:!0,detail:`${t} movement${t===1?``:`s`}`}:{pass:!1,reason:"Add at least one movement line (e.g. `10 KB Swings`)."}},"exactly-movements":(e,t)=>{let n=$q(t.count??t.value,`count`);if(n===null)return{pass:!1,reason:"exactly-movements: missing `count`."};let r=Yq(e.statements);return r===n?{pass:!0,detail:String(r)}:{pass:!1,reason:`Expected exactly ${n} movement${n===1?``:`s`}, found ${r}.`}},"has-reps":e=>Qq(e.statements)?{pass:!0}:{pass:!1,reason:"Add a rep count (e.g. `10` reps on a movement line)."},"has-timer":e=>Zq(e.statements)?{pass:!0}:{pass:!1,reason:"Add a timer (e.g. `*:30 Rest` or `5:00 cap`)."},"min-rounds":(e,t)=>{let n=$q(t.count??t.min,`count`);if(n===null)return{pass:!1,reason:"min-rounds: missing `count`."};let r=Xq(e.statements);return r>=n?{pass:!0,detail:`${r} round${r===1?``:`s`}`}:{pass:!1,reason:`Need at least ${n} round${n===1?``:`s`} — found ${r}.`}},"contains-token":(e,t)=>{let n=eJ(t.value??t.token,`value`);return n===null?{pass:!1,reason:"contains-token: missing `value`."}:(e.content??``).includes(n)?{pass:!0,detail:`"${n}"`}:{pass:!1,reason:`Script must include the token "${n}".`}}};function nJ(e,t){if(!t||typeof t.type!=`string`||t.type.length===0)return{pass:!1,reason:`Quest has no validation schema.`};let n=tJ[t.type];return n?n(e,t):{pass:!1,reason:`Unknown validation type "${t.type}".`}}function rJ({pageRoute:e,quests:t,block:n,enabled:r=!0}){let{markComplete:i,quests:a,isComplete:o}=_H(e,t),[s,c]=(0,V.useState)(new Set),l=(0,V.useMemo)(()=>{let e={};if(!r||!n){for(let n of t)e[n.id]={pass:!1,reason:`No active block.`};return e}let i={content:n.content,statements:n.statements??[]};for(let n of t){if(!n.validation){e[n.id]={pass:!1};continue}if(n.validation?.type===`workout-complete`){e[n.id]={pass:!1,reason:`Finish the workout to check this off.`};continue}e[n.id]=nJ(i,n.validation)}return e},[n,t,r]);(0,V.useEffect)(()=>{if(r)for(let e of a)e.isCompleted||s.has(e.id)||l[e.id]?.pass&&(i(e.id),c(t=>{if(t.has(e.id))return t;let n=new Set(t);return n.add(e.id),n}))},[r,a,l,s,i]);let u=(0,V.useMemo)(()=>t.map(e=>e.id).join(`|`),[t]);return(0,V.useEffect)(()=>{c(new Set)},[e,u]),{quests:a.map(e=>{let t=l[e.id]??{pass:!1,reason:`No validator result.`},n=e.isCompleted?{...t,pass:!0,detail:`Completed`}:t;return{...e,result:n}}),isComplete:o,results:l}}function iJ({page:e,wodFiles:t,theme:n,workoutItems:r,onSelect:i,contentOverride:a,panelHeaderActions:o,onPanelActionsReady:s,heroSlot:c,onScrollToSection:l}){let u=Sn(),d=mt(),{sections:f,route:p,chapters:m}=e,h=d.pathname.startsWith(`/p/`)||p.startsWith(`/p/`),g=(0,V.useMemo)(()=>zL(p),[p]),_=e.type===`guide`||p.startsWith(`/guide`);$V(_?p:void 0);let v=p.startsWith(`/collections/`)||p.startsWith(`/c/`),y=bH(`(prefers-reduced-motion: reduce)`),b=_&&!v&&!y,x=v?p.split(`/`).pop()??null:null,S=(0,V.useCallback)(e=>{if(i){i(e);return}u(ZA(e.category,e.name))},[u,i]),C=f.some(e=>e.proseChunks.some(e=>e.kind===`widget`&&e.widget===`workouts-list`)),w=f.slice(1),T=f[0]??null,E=!!T&&(T.proseChunks.some(e=>e.kind===`prose`&&e.text.trim()!==``)||T.buttons.length>0),D=f.find(e=>e.view)?.view??null,O=D?.align??`right`,k=D?.width??`50%`,A=w[0]??f[0]??null,j=p===`/`?`learn`:void 0,M=D?.source?BL(D.source,t):``,N=D?.source||`__initial__`,[P,F]=(0,V.useState)(A?.id??null),[I,ee]=(0,V.useState)(A?.heading??`Whiteboard Script`),[te,ne]=(0,V.useState)(A?.heading??`Whiteboard Script`),re=(0,V.useMemo)(()=>HL(w),[w]),ie=b&&p.split(`/`).pop()||void 0,ae=(0,V.useMemo)(()=>b?FK(w,ie):null,[b,ie,w]),{guideOwnerBySection:oe,guideOwnerSource:se}=(0,V.useMemo)(()=>{if(!b)return{guideOwnerBySection:null,guideOwnerSource:null};let e=new Map,t=new Map,n=null;for(let r of w){let i=r.proseChunks.find(e=>e.kind===`button`&&e.button.pipeline.some(e=>e.action===`set-source`))?.button.pipeline.find(e=>e.action===`set-source`)?.value??r.buttons.find(e=>e.pipeline.some(e=>e.action===`set-source`))?.pipeline.find(e=>e.action===`set-source`)?.value??null;i&&(n=r,t.set(r.id,i)),e.set(r.id,n)}return{guideOwnerBySection:e,guideOwnerSource:t}},[b,w]),[ce,L]=(0,V.useState)(()=>(A??f[0])?.theme??`slate`),[le,ue]=(0,V.useState)({}),{editorSource:R,editorOpacity:de,isEditorLoading:fe,activeOriginalSource:pe,swapSource:me,handleEditorChange:he,resetActiveSource:ge,setEditorView:_e,getSource:ve}=lH({initialSource:M,initialSourceKey:N,contentOverride:a}),ye=(0,V.useRef)(t);ye.current=t;let be=(0,V.useCallback)(()=>Pe.current[0]??null,[]),{startRun:xe,closeRun:Se,handleWorkoutComplete:Ce,resetRun:we,resetRequested:Te,fullscreen:Ee,runState:De,completedResults:Oe}=cH({getBlock:be,getContent:ve,title:e.frontmatter.title}),ke=(0,V.useCallback)(async()=>await we(M)?(ge(),!0):!1,[we,M,ge]),[Ae,je]=(0,V.useState)(null),Me=e.quests??[],Ne=rJ({pageRoute:e.route,quests:Me,block:Ae});vH({pageRoute:e.route,quests:Me,completedResults:Oe}),yH({pageRoute:e.route,quests:Me,initialSource:M,currentSource:R});let Pe=(0,V.useRef)([]),Fe=(0,V.useRef)(re.get(A?.id??``)?.id??null),Ie=(0,V.useCallback)(e=>{F(e.id),ee(e.heading),L(e.theme??`slate`);let t=(oe??re).get(e.id)??null;ne(t?.heading??A?.heading??`Whiteboard Script`);let n=t?.id??null;if(n===Fe.current)return;if(Fe.current=n,!t){me(M,N);return}let r=t.examples??[];if(r.length>0){let e=r[le[t.id]??0]??r[0];e?.source&&me(BL(e.source,ye.current),e.source)}for(let e of t.commands){let t=e.pipeline.filter(e=>!(r.length>0&&e.action===`set-source`)).map(t=>qM(t,e.open??`view`));t.length!==0&&KM(t.length===1?t[0]:{type:`pipeline`,steps:t},He.current)}let i=oe?se?.get(t.id):void 0;i&&me(BL(i,ye.current),i)},[le,me,re,oe,se,A,M,N]),Le=(0,V.useCallback)((e,t)=>{ue(n=>({...n,[e.id]:t})),F(e.id),ee(e.heading),L(e.theme??`slate`),ne(e.heading),Fe.current=e.id;let n=e.examples?.[t];n?.source&&me(BL(n.source,ye.current),n.source)},[me]),[Re,ze]=Gt(`h`,{history:`replace`,shallow:!0}),[Be]=Gt(`q`,{defaultValue:``,shallow:!0}),Ve=(0,V.useMemo)(()=>({navigate:(e,t)=>u(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&ze(n,{history:t?`replace`:`push`})},swapSource:e=>me(BL(e,ye.current),e),setPanelState:e=>{if(e===`track`){let e=be();e&&xe(e)}}}),[u,me,ze,be,xe]),He=(0,V.useRef)(Ve);He.current=Ve;let Ue=(0,V.useCallback)(e=>{ze(e.id,{history:`replace`}),Ie(e)},[Ie,ze]),We=aL(104),Ge=(0,V.useMemo)(()=>`-${We}px 0px -30% 0px`,[We]),Ke=ae?ae.tail.map(e=>e.id):w.map(e=>e.id),qe=(0,V.useRef)(!1);eL({ids:Ke,enabled:Ke.length>0,rootMargin:Ge,threshold:[0,.1,.25,.5,.75],dataAttribute:`data-section-id`,scrollDirection:`topmost-when-up`,debounceMs:50,shouldAcceptChange:()=>qe.current?!0:(qe.current=window.scrollY>0,qe.current),onChange:e=>{let t=w.find(t=>t.id===e);t&&(ze(e,{history:`replace`}),Ie(t))}});let Je=(0,V.useRef)(!1);(0,V.useEffect)(()=>{Je.current||!Re||w.length===0||(Je.current=!0,requestAnimationFrame(()=>{let e=document.querySelector(`[data-section-id="${Re}"]`);if(!e)return;let t=We+8,n=e.getBoundingClientRect().top+window.scrollY-t;window.scrollTo({top:Math.max(0,n),behavior:`smooth`})}))},[w,Re,We]);let Ye=(0,V.useRef)(Be);(0,V.useEffect)(()=>{if(!v){Ye.current=Be;return}let e=Be.trim(),t=Ye.current.trim();if(e&&e!==t){let e=document.getElementById(`collection-workouts`);if(e){let t=e.getBoundingClientRect().top+window.scrollY-We-8;window.scrollTo({top:Math.max(0,t),behavior:`smooth`})}}Ye.current=Be},[Be,v,We]);let Xe=(0,V.useRef)(s);Xe.current=s,(0,V.useEffect)(()=>{Xe.current?.({run:()=>{let e=Pe.current[0]??null;e&&xe(e)},reset:()=>{we()},results:()=>{},fullscreen:()=>{let e=Pe.current[0]??null;e&&xe(e)},getSource:ve})},[xe,we,ve]);let Ze=(0,V.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:e=>{xe(e)}}],[xe]),Qe=tP[ce]??tP.slate,$e=fe?`${I} · loading`:I,et=!fe&&I!==te?te:void 0,tt=(0,V.useCallback)(e=>{let t=e[0]??null;Pe.current=e,je(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),nt=c??(E&&T?(0,H.jsx)(Aq,{section:T,idx:-1,prose:void 0,blockId:T.id,keySuffix:`hero`,showEyebrow:!1,isActive:!1,hasViewDef:!!D,deps:Ve,onExampleSelect:Le,selectedExampleIndex:0,onScrollToSection:l,challengeQuests:Ne.quests}):null),rt=o,it=(0,H.jsx)(pK,{editorSource:R,editorOpacity:de,activeOriginalSource:pe,handleEditorChange:he,onResetToSource:ke,canvasNoteId:g,readonly:h,showFrontmatter:typeof e.frontmatter.showFrontmatter==`boolean`?e.frontmatter.showFrontmatter:!_&&p!==`/`&&!p.startsWith(`/syntax`),theme:n,commands:Ze,onBlocksChange:tt,onViewCreated:_e,panelTitle:$e,panelSubtitle:et,panelThemeClass:Qe.panel,headerActions:rt,onRun:(e,t)=>{t&&xe(t,e)}}),at=D&&(0,H.jsx)(Gq,{variant:`desktop`,panelContent:it,panelTitle:$e,panelSubtitle:et,viewDefButtons:D.buttons,runState:De,deps:Ve,width:k,source:R}),ot=D&&(0,H.jsx)(Gq,{variant:`mobile`,panelContent:it,panelTitle:$e,panelSubtitle:et,viewDefButtons:D.buttons,runState:De,deps:Ve,width:k,source:R});return(0,H.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,children:[Ee?.kind===`timer`&&(0,H.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:We},children:(0,H.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,H.jsx)(UV,{block:Ee.block,onClose:Se,autoStart:!0,externalStop:Te,onComplete:(e,t)=>{Ce(t)}})})}),(0,H.jsx)(Kq,{heroSlot:nt,children:b?(0,H.jsx)(Nq,{sections:w,groupKey:ie,title:String(e.frontmatter.title??``),pane:(0,H.jsx)(`div`,{className:`absolute inset-0`,style:{"--canvas-editor-preferred-height":Bq(R)},children:it}),cardArgs:{activeSectionId:P,selectedExamples:le,onExampleSelect:Le,runState:De,deps:Ve,hasViewDef:!!D,chapters:m,challengeQuests:Ne.quests,onScrollToSection:l},onActivateSection:Ue}):(0,H.jsx)(Uq,{contentSections:w,isCollection:v,collectionSlug:x,workoutItems:r,handleSelectWorkout:S,activeSectionId:P,selectedExamples:le,runState:De,deps:Ve,handleExampleSelect:Le,hasWorkoutsTag:C,hasViewDef:!!D,chapters:m,challengeQuests:Ne.quests,onScrollToSection:l,mobilePanel:ot,desktopPanel:at,stickyAlign:O,editorWidth:k,editorAppearsAtSectionId:j})}),_&&(0,H.jsx)(Pq,{})]})}var aJ={"workout-complete":!0,"run-started":!0};function oJ(e,t,n){let{markComplete:r}=_H(e,t),i=(0,V.useRef)(new Set);i.current=new Set(t.filter(e=>!e.validation||!aJ[e.validation.type]).map(e=>e.id));let a=(0,V.useRef)({}),o={};for(let e of n)e.quest&&(o[e.id]=e.quest);return a.current=o,(0,V.useCallback)(e=>{let t=a.current[e];t&&i.current.has(t)&&r(t)},[r])}function sJ(){let e=bH(`(prefers-reduced-motion: reduce)`),t=bH(`(max-width: ${RL}px)`);return e?`reduced`:t?`mobile`:`desktop`}var cJ=.25;function lJ({sourcesByStageId:e,doc:t,setDoc:n,subscribe:r,enabled:i}){let[a,o]=(0,V.useState)(!1),s=(0,V.useRef)(t),c=(0,V.useRef)(null),l=(0,V.useRef)(t),u=(0,V.useRef)(a),d=(0,V.useRef)(``),f=(0,V.useRef)(null),p=(0,V.useRef)(!1);return l.current=t,u.current=a,(0,V.useEffect)(()=>{let e=d.current;if(c.current!==null){if(t===c.current){s.current=t,c.current=null;return}if(t!==s.current){o(!0);return}}t!==s.current&&t!==e&&o(!0)},[t]),(0,V.useEffect)(()=>{if(!i){c.current=null;return}let t=r(t=>{if(t.stage.id!==f.current&&(f.current=t.stage.id,d.current=e[t.stage.id]??``,s.current=``,c.current=null,o(!1),p.current=!0),u.current||c.current!==null)return;let r=d.current;if(!r)return;let i=t.index===0?r.length:Math.floor(vK(gK(t.t/cJ))*r.length),a=r.slice(0,i),m=l.current;p.current=!1,a!==m&&(c.current=a,n(a))});return()=>{t()}},[i,e,n,r]),{userDiverged:a,complete:(0,V.useCallback)(()=>{if(u.current)return;let e=d.current;e&&(c.current=e,n(e))},[n])}}function uJ({stages:e,activeIndex:t}){return(0,H.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`scroll-captions`,children:e.map((n,r)=>(0,H.jsxs)(`div`,{className:`absolute inset-0 overflow-y-auto transition-opacity duration-300`,style:{opacity:+(r===t)},"aria-hidden":r!==t,inert:r!==t,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:n.accent??`hsl(var(--muted-foreground))`},children:[String(r+1).padStart(2,`0`),` / `,String(e.length).padStart(2,`0`)]}),(0,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:n.id.replace(/-/g,` `)}),n.caption&&(0,H.jsx)(dq,{prose:n.caption,className:`mt-3 text-sm text-muted-foreground`})]},n.id))})}var dJ=(0,V.forwardRef)(function({text:e,accent:t},n){let r=t??`hsl(var(--metric-rounds))`;return(0,H.jsxs)(`div`,{ref:n,className:`pointer-events-none absolute top-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-2.5 whitespace-nowrap rounded-full border bg-card px-5 py-2.5 font-mono text-[10.5px] tracking-[0.04em] opacity-0 shadow-xl`,style:{borderColor:`color-mix(in srgb, ${r} 55%, transparent)`},children:[(0,H.jsx)(`span`,{className:`size-[9px] rounded-sm`,style:{background:r}}),e]})}),fJ=8,pJ=3,mJ=2;function hJ(e,t,n){let r=e.querySelectorAll(`.cm-content .cm-line`),i=Math.max(1,Math.min(n[0],n[1]))-1,a=Math.max(1,Math.max(n[0],n[1])),o=Array.from(r).slice(i,a);if(o.length===0)return null;let s=e.getBoundingClientRect(),c=1/0,l=1/0,u=-1/0,d=-1/0;for(let e of o){let t=e.getBoundingClientRect();c=Math.min(c,t.top),l=Math.min(l,t.left),u=Math.max(u,t.bottom),d=Math.max(d,t.right)}return c-=pJ,l-=fJ,u+=pJ,d+=fJ,t&&(l=Math.max(l,t.left-mJ),d=Math.min(d,t.right+mJ),c=Math.max(c,t.top-mJ),u=Math.min(u,t.bottom+mJ)),{top:c-s.top,left:l-s.left,width:d-l,height:u-c}}function gJ(e,t){if(!t)return null;let n=t.getBoundingClientRect();if(n.width===0||n.height===0)return null;let r=e.getBoundingClientRect();return{top:n.top-r.top-mJ,left:n.left-r.left-mJ,width:n.width+4,height:n.height+4}}function _J({accent:e,lines:t}){let n=e??`hsl(var(--foreground))`,r=(0,V.useRef)(null),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(!1);return(0,V.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let n=requestAnimationFrame(()=>s(!0)),i=e.parentElement;if(!i)return()=>cancelAnimationFrame(n);let o=()=>{let e=i.firstElementChild,n=e?.getBoundingClientRect()??null;a((t?hJ(i,n,t):null)??gJ(i,e))};o();let c=new ResizeObserver(o);return c.observe(i),()=>{cancelAnimationFrame(n),c.disconnect()}},[t]),(0,H.jsx)(`div`,{ref:r,className:`pointer-events-none absolute z-30 transition-all duration-300 ${i?t?`rounded-lg`:`rounded-2xl`:`-inset-1.5 rounded-2xl`}`,style:{boxShadow:`0 0 0 2px ${n}`,opacity:+!!o,...i??{}},"data-testid":`scroll-ring`,"data-ring-lines":t?`${t[0]}-${t[1]}`:void 0})}function vJ({scroll:e,wodFiles:t,theme:n,noteTitle:r=`note.md`,showFrontmatter:i,doc:a,onDocChange:o,onBlocksChange:s,onStageEnter:c,onRun:l,className:u}){let d=e.stages,f=(0,V.useRef)(null),p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useRef)(new Set),g=(0,V.useMemo)(()=>Object.fromEntries(d.map(e=>[e.id,e.source?BL(e.source,t):``])),[d,t]),[_,v]=(0,V.useState)(()=>g[d[0]?.id]??``),y=a??_,b=o??v,[x,S]=(0,V.useState)(!1),{slice:C,subscribe:w,resync:T}=MK(f,x,d),[E,D]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=f.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&D(!0)},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let{userDiverged:O}=lJ({sourcesByStageId:g,doc:y,setDoc:b,subscribe:w,enabled:!x&&e.typewriter}),k=C.stage.id,A=yK(g[k]??``,y);(0,V.useEffect)(()=>{!x&&E&&c?.(k)},[x,k,E,c]),(0,V.useEffect)(()=>{if(!x){let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)}},[x,T]),(0,V.useEffect)(()=>{let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)},[k,T]),(0,V.useEffect)(()=>{O&&S(!0)},[O]),(0,V.useEffect)(()=>{let e=d.flatMap(e=>e.effects??[]);return w(t=>{let n=m.current;if(n){let e=gK((t.t-.04)/.12),r=gK((t.t-.5)/.2);n.style.opacity=String(Math.max(0,e-r)),n.style.transform=`translateX(-50%) translateY(${_K(-14,0,e)}px)`}let r=p.current;if(!r)return;let i=new Set;for(let n of e){if(!n.stages.includes(t.stage.id))continue;i.add(n.target);let[e,a]=n.in??[0,1],o=a>e?gK((t.t-e)/(a-e)):1,s=n.ease===`linear`?o:vK(o);r.querySelectorAll(`[data-effect-target="${n.target}"]`).forEach(e=>{n.opacity&&(e.style.opacity=String(_K(n.opacity[0],n.opacity[1],s))),n.translateY&&(e.style.transform=`translateY(${_K(n.translateY[0],n.translateY[1],s)}px)`)})}for(let e of h.current)i.has(e)||r.querySelectorAll(`[data-effect-target="${e}"]`).forEach(e=>{e.style.opacity=``,e.style.transform=``});h.current=i})},[w,d]);let j=C.stage.accent??`hsl(var(--foreground))`;return(0,H.jsxs)(`div`,{ref:p,className:u,"data-testid":`scroll-runway-section`,children:[(0,H.jsx)(kK,{trackRef:f,height:e.runway,stages:d,activeIndex:C.index,status:(0,H.jsx)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:x?`Playground mode`:C.stage.id.replace(/-/g,` `)}),pane:(0,H.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,H.jsx)(fK,{title:r??``,noteId:`canvas:scroll-runway`,doc:y,onDocChange:b,onBlocksChange:s,theme:n,showFrontmatter:i,run:l?{onRun:l}:void 0,className:`absolute inset-x-2 top-2 bottom-2`,children:C.stage.toast&&(0,H.jsx)(dJ,{ref:m,text:C.stage.toast,accent:j})}),C.ring&&!x&&A&&(0,H.jsx)(_J,{accent:j,lines:C.ring.lines})]}),captions:(0,H.jsx)(uJ,{stages:d,activeIndex:C.index})}),x&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>S(!1),className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-full bg-foreground px-5 py-2.5 font-mono text-[10px] tracking-[0.06em] text-background opacity-95 transition-opacity hover:opacity-100`,children:[`▶ Playground mode — `,O?`your edits are kept`:`editing`,` · tap here to return to the tour`]})]})}function yJ({spec:e,wodFiles:t,onStageEnter:n,className:r}){let i=e.stages,a=(0,V.useMemo)(()=>Object.fromEntries(i.map(e=>[e.id,e.source?BL(e.source,t):``])),[i,t]),o=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=o.current;if(!e)return;let t=new IntersectionObserver(e=>{for(let r of e){if(!r.isIntersecting)continue;let e=r.target.dataset.cardId;e&&(n?.(e),t.unobserve(r.target))}},{threshold:.4});return e.querySelectorAll(`[data-card-id]`).forEach(e=>t.observe(e)),()=>t.disconnect()},[n]),(0,H.jsx)(`section`,{className:r,"data-testid":`runway-reduced`,children:(0,H.jsx)(`div`,{className:`px-6 pt-4 pb-24`,children:(0,H.jsx)(`div`,{ref:o,className:`mx-auto max-w-2xl`,children:i.map((e,t)=>(0,H.jsxs)(`article`,{"data-card-id":e.id,className:`mb-6 rounded-2xl border border-border bg-card p-7`,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:e.accent??`hsl(var(--muted-foreground))`},children:[String(t+1).padStart(2,`0`),` / `,String(i.length).padStart(2,`0`)]}),(0,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:e.id.replace(/-/g,` `)}),e.caption&&(0,H.jsx)(dq,{prose:e.caption,className:`mt-3 text-sm text-muted-foreground`}),a[e.id]&&(0,H.jsx)(`pre`,{className:`mt-5 overflow-x-auto rounded-lg bg-background px-4 py-4 font-mono text-[12px] tracking-[0.04em] text-muted-foreground`,children:a[e.id]})]},e.id))})})})}function bJ(){return sJ()}function xJ({spec:e,formFactor:t,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d}){let f=bJ();return(t??f)===`reduced`?(0,H.jsx)(yJ,{spec:e,wodFiles:n,onStageEnter:l,className:d}):(0,H.jsx)(vJ,{scroll:e,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d})}function SJ({page:e,wodFiles:t,theme:n,onScrollToSection:r}){let i=e.scroll,a=i.stages,o=Sn();$V(e.type===`guide`||e.route.startsWith(`/guide`)?e.route:void 0);let s=(0,V.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,e.source?BL(e.source,t):``])),[a,t]),[c,l]=(0,V.useState)(()=>s[a[0]?.id]??``),u=(0,V.useRef)([]),[d,f]=(0,V.useState)(null),p=oJ(e.route,e.quests,a),m=(0,V.useCallback)(()=>u.current[0]??null,[]),h=cH({getBlock:m,getContent:(0,V.useCallback)(()=>c,[c]),title:e.frontmatter.title}),{startRun:g}=h,_=aL(104),v=rJ({pageRoute:e.route,quests:e.quests,block:d});vH({pageRoute:e.route,quests:e.quests,completedResults:h.completedResults});let[,y]=Gt(`h`,{history:`replace`,shallow:!0}),b=(0,V.useMemo)(()=>({navigate:(e,t)=>o(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&y(n,{history:t?`replace`:`push`})},swapSource:e=>l(BL(e,t)),setPanelState:e=>{if(e===`track`){let e=m();e&&g(e)}}}),[o,y,t,m,g]),x=(0,V.useCallback)((e,n)=>{let r=e.examples?.[n];r?.source&&l(BL(r.source,t))},[t]),S=(0,V.useCallback)(e=>{let t=e[0]??null;u.current=e,f(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),C=(0,V.useCallback)((e,t)=>{t&&g(t,e)},[g]),w=`${e.route.split(`/`).pop()??`note`}.md`,T=e.sections.slice(1).map((e,t)=>(0,H.jsx)(Aq,{section:e,idx:t,blockId:e.id,keySuffix:`scroll`,isActive:!1,hasViewDef:!1,deps:b,onExampleSelect:x,selectedExampleIndex:0,challengeQuests:v.quests,onScrollToSection:r},e.id));return(0,H.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,"data-testid":`scroll-canvas-page`,children:[h.fullscreen?.kind===`timer`&&(0,H.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:_},children:(0,H.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,H.jsx)(UV,{block:h.fullscreen.block,onClose:h.closeRun,autoStart:!0,externalStop:h.resetRequested,onComplete:(e,t)=>{h.handleWorkoutComplete(t)}})})}),(0,H.jsx)(xJ,{spec:i,wodFiles:t,theme:n,noteTitle:w,showFrontmatter:e.frontmatter.showFrontmatter===!0,doc:c,onDocChange:l,onBlocksChange:S,onStageEnter:p,onRun:C}),T]})}var CJ=({timeLabel:e,title:t,subtitle:n,onClick:r})=>(0,H.jsxs)(`button`,{onClick:r,className:`flex items-center gap-4 px-6 py-3 hover:bg-muted/40 transition-colors text-left group w-full`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 w-14 text-right`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,H.jsx)(De,{className:`size-2.5 text-muted-foreground/40`}),(0,H.jsx)(`span`,{className:`text-[10px] font-black text-muted-foreground/60 tabular-nums`,children:e})]})}),(0,H.jsx)(`div`,{className:`flex-shrink-0 size-8 rounded-lg bg-muted flex items-center justify-center group-hover:bg-background transition-colors`,children:(0,H.jsx)(In,{className:`size-3.5 text-signal-positive`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground truncate`,children:t}),n&&(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate`,children:n})]})]});function wJ(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function TJ(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function EJ(e,t){return wJ(e)===wJ(t)}var DJ=(0,V.forwardRef)(({items:e,onSelect:t,onCreateEntry:n,journalEntries:r,onOpenEntry:i,onVisibleDateChange:a,stickyOffset:o=0,className:s,renderNoteCard:c,renderResultRow:l,renderEmptyDate:u,initialDate:d},f)=>{let p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useRef)(null),g=(0,V.useRef)(null),_=(0,V.useRef)(new Map),v=(0,V.useRef)(!1),y=(0,V.useRef)(!1),b=(0,V.useRef)(!1),x=(0,V.useRef)(!1),S=(0,V.useRef)(new Date),C=(0,V.useRef)(new Date),w=(0,V.useRef)(null),T=(0,V.useRef)(null),[E,D]=(0,V.useState)(o);(0,V.useEffect)(()=>{let e=()=>{if(!T.current)return;let e=T.current.getBoundingClientRect(),t=Math.round(e.top+window.scrollY);D(Math.max(o,t))},t=requestAnimationFrame(e);return window.addEventListener(`resize`,e,{passive:!0}),()=>{cancelAnimationFrame(t),window.removeEventListener(`resize`,e)}},[o]);let O=(0,V.useRef)(null),k=(0,V.useRef)(!1),A=(0,V.useRef)(null),j=(0,V.useRef)(``),[M,P]=(0,V.useState)(()=>{let e=new Date;if(d){let t=TJ(e,90);return{start:TJ(d,-14),end:TJ(d,14)>t?t:TJ(d,14)}}return{start:TJ(e,-7),end:e}}),F=(0,V.useMemo)(()=>{let e=[],t=new Date(M.end),n=M.start;for(;t>=n;)e.push(new Date(t)),t=TJ(t,-1);return e},[M]),I=(0,V.useMemo)(()=>{let t=new Map;return e.forEach(e=>{if(!e.date)return;let n=wJ(new Date(e.date)),r=t.get(n)??[];r.push(e),t.set(n,r)}),t},[e]),ee=(0,V.useMemo)(()=>{let t=null;return r?.forEach((e,n)=>{let r=new Date(n+`T00:00:00`);(!t||r<t)&&(t=r)}),e.forEach(e=>{if(!e.date)return;let n=new Date(e.date);(!t||n<t)&&(t=n)}),t},[r,e]),te=(0,V.useRef)(null);(0,V.useEffect)(()=>{te.current=ee},[ee]),(0,V.useLayoutEffect)(()=>{S.current=M.start},[M.start]),(0,V.useLayoutEffect)(()=>{C.current=M.end},[M.end]),(0,V.useLayoutEffect)(()=>{let e=w.current;if(!e)return;w.current=null;let t=_.current.get(e.key);if(!t)return;let n=t.getBoundingClientRect().top-e.top;Math.abs(n)>1&&window.scrollBy(0,n)},[F]);let ne=(0,V.useCallback)(()=>{let e=(e,t)=>{e.current&&t.current&&(e.current.unobserve(t.current),e.current.observe(t.current))};e(h,p),e(g,m)},[]),re=(0,V.useCallback)(()=>{k.current=!0,A.current&&clearTimeout(A.current);let e=()=>{k.current=!1,A.current&&=(clearTimeout(A.current),null),ne()};window.addEventListener(`scrollend`,e,{once:!0});let t=window.scrollY,n=0,r=()=>{if(!k.current)return;let i=window.scrollY;if(i===t){if(n++,n>=2){window.removeEventListener(`scrollend`,e),e();return}}else t=i,n=0;A.current=setTimeout(r,100)};A.current=setTimeout(r,150)},[ne]),ie=(0,V.useCallback)(e=>{let t=e.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:t,behavior:`smooth`})},[E]);(0,V.useImperativeHandle)(f,()=>({scrollToDate(e){let t=wJ(e),n=_.current.get(t);if(n)re(),ie(n);else{let n=TJ(new Date,90);O.current=t,P({start:TJ(e,-14),end:TJ(e,14)>n?n:TJ(e,14)})}}}),[re,ie]),(0,V.useEffect)(()=>{requestAnimationFrame(()=>{if(d&&!EJ(d,new Date)){let e=wJ(d),t=_.current.get(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:Math.max(0,e),behavior:`auto`})}}else window.scrollTo({top:0,behavior:`instant`});b.current=!0,ne()})},[E,d,ne]),(0,V.useEffect)(()=>{let e=O.current;if(!e)return;let t=_.current.get(e);t&&(O.current=null,re(),requestAnimationFrame(()=>{let e=t.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:Math.max(0,e),behavior:`auto`})}))},[F,re,E]),(0,V.useEffect)(()=>{let e=()=>{!b.current||k.current||x.current||(x.current=!0,ne())};return window.addEventListener(`scroll`,e,{passive:!0}),()=>{window.removeEventListener(`scroll`,e)}},[ne]),(0,V.useEffect)(()=>{let e=p.current;if(!e)return;let t=new IntersectionObserver(([e])=>{if(!e.isIntersecting||v.current||!b.current||k.current||!x.current)return;let t=TJ(new Date,90);if(C.current>=t)return;let n=wJ(C.current),r=_.current.get(n);r&&(w.current={key:n,top:r.getBoundingClientRect().top}),v.current=!0,P(e=>{let t=TJ(new Date,90);if(e.end>=t)return e;let n=TJ(e.end,7);return{...e,end:n>t?t:n}})},{rootMargin:`600px 0px 0px 0px`,threshold:0});return t.observe(e),h.current=t,()=>{t.disconnect(),h.current=null}},[]),(0,V.useEffect)(()=>{let e=setTimeout(()=>{v.current=!1,ne()},400);return()=>clearTimeout(e)},[M.end]),(0,V.useEffect)(()=>{let e=m.current;if(!e)return;let t=new IntersectionObserver(([e])=>{if(!e.isIntersecting||y.current||!b.current||k.current)return;let t=te.current,n=t?TJ(t,-14):TJ(new Date,-90);S.current<=n||(y.current=!0,P(e=>{let t=te.current?TJ(te.current,-14):TJ(new Date,-90),n=TJ(e.start,-7);return{...e,start:n<t?t:n}}))},{rootMargin:`0px 0px 400px 0px`,threshold:0});return t.observe(e),g.current=t,()=>{t.disconnect(),g.current=null}},[]),(0,V.useEffect)(()=>{let e=setTimeout(()=>{y.current=!1},400);return()=>clearTimeout(e)},[M.start]);let ae=(0,V.useRef)(E);(0,V.useEffect)(()=>{ae.current=E},[E]),(0,V.useEffect)(()=>{if(!a)return;let e=new Map,t=null,n=new IntersectionObserver(n=>{if(n.forEach(t=>{t.target.id&&(t.isIntersecting?e.set(t.target.id,t.boundingClientRect.top):e.delete(t.target.id))}),k.current||!b.current)return;let r=ae.current+8,i=``,o=1/0;if(e.forEach((e,t)=>{let n=Math.abs(e-r);n<o&&(o=n,i=t)}),i&&i!==j.current){t&&clearTimeout(t);let e=i;t=setTimeout(()=>{e!==j.current&&(j.current=e,a(e))},150)}},{rootMargin:`-${E+8}px 0px -50% 0px`,threshold:[0,.1,.25,.5,.75,1]});return _.current.forEach(e=>e&&n.observe(e)),()=>{n.disconnect(),t&&clearTimeout(t)}},[F,a,E]);let oe=(0,V.useCallback)(e=>t=>{t?_.current.set(e,t):_.current.delete(e)},[]),se=wJ(new Date);return(0,H.jsxs)(`div`,{className:U(`bg-card`,s),"data-testid":`journal-date-scroll`,children:[(0,H.jsx)(`div`,{ref:T,className:`h-0`,"aria-hidden":!0}),(0,H.jsx)(`div`,{ref:p,className:`h-px`,"data-testid":`top-sentinel`}),F.map(e=>{let a=wJ(e),o=(I.get(a)??[]).filter(e=>e.type===`result`),s=r?.get(a),d=a===se,f=e>new Date(se+`T23:59:59`),p=!s&&o.length===0;return(0,H.jsxs)(`div`,{id:a,ref:oe(a),className:`flex flex-col`,style:{scrollMarginTop:E+8},children:[(0,H.jsxs)(`div`,{className:`sticky z-[5] px-6 py-2 bg-muted/80 backdrop-blur-sm border-y border-border flex items-center gap-2`,style:{top:E},children:[(0,H.jsx)(qt,{className:`size-3 text-muted-foreground`}),(0,H.jsxs)(`span`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,children:[VP(e),d&&(0,H.jsx)(`span`,{className:`ml-2 text-primary font-black`,children:`— Today`})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-0 pb-1`,children:[s?(()=>{let e={...s,title:zj(s.title)};return c?c({dateKey:a,entry:e,isToday:d,onOpenEntry:i}):(0,H.jsxs)(`button`,{onClick:()=>i?.(a),className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors`,children:(0,H.jsx)(N,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:U(`text-sm truncate`,e.title?`font-bold text-foreground`:`italic text-muted-foreground`),children:e.title||`Untitled note`}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium`,children:`Note`})]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]})})():null,(()=>{let e=o.filter(e=>e.group!==`playground`),n=o.filter(e=>e.group===`playground`),r=e=>l?l(e,t):(0,H.jsx)(CJ,{timeLabel:e.date?new Date(e.date).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}):`—`,title:e.title,subtitle:e.subtitle,onClick:()=>t(e)},`result-${e.id}`),i=(e,t)=>t.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-6 pt-2 pb-1`,children:[(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/40`}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-[0.2em] text-muted-foreground/50`,children:e}),(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/40`})]}),t.map(r)]});return(0,H.jsxs)(H.Fragment,{children:[i(`Workouts`,e),i(`Playground`,n)]})})(),p&&(u?u({date:e,dateKey:a,isFuture:f,isToday:d,onCreateEntry:n}):f?(0,H.jsx)(`button`,{"data-date":a,"data-testid":`journal-plan-workout`,onClick:()=>n?.(e),className:`flex items-center gap-3 px-6 py-3 text-left hover:bg-muted/30 transition-colors group`,children:(0,H.jsx)(`span`,{className:`text-[11px] text-muted-foreground/50 font-medium group-hover:text-primary transition-colors`,children:`+ Plan a workout`})}):(0,H.jsx)(`div`,{className:`px-6 py-2.5`,children:(0,H.jsx)(`span`,{className:`text-[11px] text-muted-foreground/30 font-medium`,children:`No activity`})}))]})]},a)}),(0,H.jsx)(`div`,{ref:m,className:`h-px`,"data-testid":`bottom-sentinel`}),ee&&M.start<=TJ(ee,-14)&&(0,H.jsxs)(`div`,{className:`flex items-center gap-3 px-6 py-6 select-none`,"aria-hidden":!0,children:[(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/30`}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-[0.2em] text-muted-foreground/40`,children:`Beginning of records`}),(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/30`})]})]})});DJ.displayName=`JournalDateScroll`;async function OJ({workoutName:e,category:t,sourceNoteLabel:n,sourceNotePath:r,wodContent:i,date:a,wrapInWod:o=!0}){let s=Bj(a??new Date),c=r?.trim()||`/collections/${encodeURIComponent(t)}`,l=[`# ${e}`,``];return o?l.push("```time",i.trimEnd(),"```"):l.push(i.trimEnd()),l.push(``),Kj.create({journalDate:s,title:zj(e),rawContent:l.join(`
152
- `),sourceId:c})}function kJ(){let[e,t]=Gt(`s`,{defaultValue:``,shallow:!0,history:`replace`}),n=(0,V.useMemo)(()=>{if(e){let t=new Date(e+`T00:00:00`);if(!isNaN(t.getTime()))return t}return null},[e]),r=(0,V.useCallback)(e=>{if(!e)t(``);else{let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,`0`),i=String(e.getDate()).padStart(2,`0`);t(`${n}-${r}-${i}`)}},[t]),[i,a]=Gt(`feed`,{defaultValue:``,shallow:!0,history:`replace`}),o=(0,V.useCallback)(e=>{a(t=>t===e?``:e)},[a]),s=(0,V.useCallback)(()=>a(``),[a]);return{dateParam:e,selectedDate:n,setSelectedDate:r,setDateParam:t,selectedFeed:i||null,selectFeed:o,clearFeed:s}}function AJ({dateKeys:e,items:t,journalEntries:n,onSelectItem:r,onOpenEntry:i,onAddToToday:a,className:o}){let s=(0,V.useMemo)(()=>{let e=new Map;for(let n of t){let t=e.get(n.feedDate)??[];t.push(n),e.set(n.feedDate,t)}return e},[t]);return e.length===0?(0,H.jsxs)(`div`,{className:U(`flex flex-col items-center justify-center py-20 text-muted-foreground/50`,o),children:[(0,H.jsx)(`p`,{className:`text-sm font-medium`,children:`No feed content found.`}),(0,H.jsx)(`p`,{className:`text-xs mt-1`,children:`Feed workouts will appear here once content is available.`})]}):(0,H.jsx)(`div`,{className:U(`bg-card flex flex-col`,o),"data-testid":`feed-feed`,children:e.map(e=>{let t=new Date(e+`T00:00:00`),o=s.get(e)??[],c=n.get(e);return(0,H.jsxs)(`div`,{id:e,className:`flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`sticky z-[5] px-6 py-2 bg-muted/80 backdrop-blur-sm border-y border-border flex items-center gap-2 top-0`,children:[(0,H.jsx)(qt,{className:`size-3 text-muted-foreground flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,children:VP(t)})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-0 pb-1`,children:[c&&(0,H.jsxs)(`button`,{onClick:()=>i?.(e),className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors`,children:(0,H.jsx)(N,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate`,children:c.title}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium`,children:`Journal note`})]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]}),o.map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/30 transition-colors cursor-pointer group`,onClick:()=>r(e),children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black text-primary`,children:`WOD`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground truncate`,children:e.name}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium mt-0.5`,children:e.feedName})]}),a&&(0,H.jsxs)(`button`,{onClick:t=>{t.stopPropagation(),a(e)},title:`Add to today's journal`,className:U(`flex items-center gap-1 rounded-full border border-border px-2.5 py-1`,`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,`hover:text-primary hover:border-primary/50 transition-colors shrink-0`,`opacity-0 group-hover:opacity-100`),children:[(0,H.jsx)(Kt,{className:`size-3`}),`Today`]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]},e.id))]})]},e)})})}function jJ({feedSlug:e}){let t=Sn(),{dateParam:n}=kJ(),r=n&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:null,i=sD(),a=(0,V.useMemo)(()=>i?pz(i).find(t=>t.id===e):void 0,[i,e]),[o,s]=(0,V.useState)(new Map),[c,l]=(0,V.useState)(!0);(0,V.useEffect)(()=>{let e=!1;async function t(){l(!0);try{if(!a)return;let t=Array.from(new Set(a.items.map(e=>e.feedDate))),n=await Promise.all(t.map(async e=>{let t=await uz.getPage(`journal/${e}`).catch(()=>void 0);return t?[e,{title:t.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??e,updatedAt:t.updatedAt}]:null}));if(e)return;let r=new Map;n.forEach(e=>e&&r.set(e[0],e[1])),s(r)}catch{}finally{e||l(!1)}}return t(),()=>{e=!0}},[a]);let u=(0,V.useMemo)(()=>a?a.items.map(e=>({id:e.id,feedId:a.id,feedName:a.name,feedDate:e.feedDate,name:e.name,content:e.content,path:e.path})):[],[a]),d=(0,V.useMemo)(()=>{if(r)return[r];let e=new Set(u.map(e=>e.feedDate));return Array.from(e).sort().reverse()},[r,u]),f=(0,V.useCallback)(async e=>{try{let n=await OJ({workoutName:e.name,category:e.feedId,sourceNoteLabel:e.feedName,sourceNotePath:`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`,wodContent:e.content,wrapInWod:!1}),r=wJ(new Date);Z({title:`Added to journal`,description:n.journalDate===r?`Added to today's journal`:`Added to ${n.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>t(KA(n.journalDate??r)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[t]),p=(0,V.useCallback)(e=>{t(`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`)},[t]),m=(0,V.useCallback)(e=>{t(`/journal/${e}`)},[t]);return a?c?(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm font-medium text-muted-foreground`,children:`Loading…`}):(0,H.jsx)(AJ,{dateKeys:d,items:u,journalEntries:o,onSelectItem:p,onOpenEntry:m,onAddToToday:f}):(0,H.jsxs)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm text-muted-foreground`,children:[`Feed not found: `,e]})}var MJ=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function NJ(e,t){return new Date(e,t+1,0).getDate()}function PJ(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function FJ(e,t,n){return`${e}-${String(t+1).padStart(2,`0`)}-${String(n).padStart(2,`0`)}`}function IJ(e){return FJ(e.getFullYear(),e.getMonth(),e.getDate())}var LJ=({selectedDate:e,onDateSelect:t,entryDates:n=new Set,disabled:r=!1,className:i})=>{let[a,o]=(0,V.useState)(()=>e||new Date),s=a.getFullYear(),c=a.getMonth();(0,V.useEffect)(()=>{e&&o(t=>t.getFullYear()!==e.getFullYear()||t.getMonth()!==e.getMonth()?new Date(e.getFullYear(),e.getMonth(),1):t)},[e]);let l=e?IJ(e):null,u=(0,V.useMemo)(()=>{let e=NJ(s,c),t=PJ(s,c),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[s,c]),d=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c-1,1))},f=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c+1,1))},p=a.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),m=IJ(new Date);return(0,H.jsxs)(`div`,{className:U(`select-none px-2 py-2`,r&&`opacity-60 cursor-not-allowed`,i),onClick:e=>e.stopPropagation(),"aria-disabled":r||void 0,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,H.jsx)(`button`,{onClick:d,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Previous month`,children:(0,H.jsx)(Tt,{className:`h-4 w-4`})}),(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:p}),(0,H.jsx)(`button`,{onClick:f,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Next month`,children:(0,H.jsx)(Vn,{className:`h-4 w-4`})})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 mb-1`,children:MJ.map(e=>(0,H.jsx)(`div`,{className:`text-center text-[10px] text-muted-foreground font-medium py-0.5 w-8`,children:e},e))}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:u.map((e,i)=>{if(e===null)return(0,H.jsx)(`div`,{className:`w-8 h-8`},`empty-${i}`);let a=FJ(s,c,e),o=n.has(a),u=a===l;return(0,H.jsxs)(`button`,{disabled:r,onClick:n=>{n.stopPropagation(),n.preventDefault(),t(new Date(s,c,e),n.ctrlKey||n.metaKey)},className:U(`w-8 h-8 flex items-center justify-center rounded text-xs transition-colors relative`,`disabled:pointer-events-none`,u?`bg-primary text-primary-foreground font-bold`:a===m?`font-bold text-primary ring-1 ring-primary/40`:o?`font-semibold text-foreground hover:bg-muted`:`text-muted-foreground hover:bg-muted/50`),"aria-label":`${e} ${p}${o?` (has entries)`:``}`,children:[e,o&&!u&&(0,H.jsx)(`span`,{className:`absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary/60`})]},a)})})]})};function RJ({onSave:e,getSnapshotKey:t,onError:n}){let r=(0,V.useRef)(null),i=(0,V.useRef)(null),a=(0,V.useRef)(null),o=(0,V.useRef)(Promise.resolve()),s=(0,V.useRef)({onSave:e,getSnapshotKey:t,onError:n});s.current={onSave:e,getSnapshotKey:t,onError:n};let[c,l]=(0,V.useState)(null),u=(0,V.useCallback)(e=>{let t=o.current.then(async()=>{e.key!==i.current&&(await s.current.onSave(e.value),i.current=e.key,l(null))});return o.current=t.catch(e=>{l(e),s.current.onError?.(e)}),t},[]),d=(0,V.useCallback)(()=>r.current?u(r.current):o.current,[u]),f=(0,V.useCallback)(e=>{let t=s.current.getSnapshotKey?.(e)??(typeof e==`string`?e:JSON.stringify(e));r.current={value:e,key:t}},[]),p=(0,V.useCallback)((e,t)=>{a.current!==null&&a.current!==e&&d().catch(()=>{}),a.current=e},[d]),m=(0,V.useCallback)(()=>{d().catch(()=>{})},[d]);return(0,V.useEffect)(()=>{let e=()=>{d().catch(()=>{})},t=()=>{document.visibilityState===`hidden`&&e()};return window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`pagehide`,e),document.removeEventListener(`visibilitychange`,t),d().catch(()=>{})}},[d]),{onChange:f,onLineChange:p,onBlur:m,flush:d,error:c}}var zJ=8e3;function BJ({category:e,name:t,mdContent:n,seedOnMount:r=!0}){let i=az(e,t),[a,o]=(0,V.useState)(n),[s,c]=(0,V.useState)(!0),[l,u]=(0,V.useState)(),[d,f]=(0,V.useState)({}),[p,m]=(0,V.useState)(0),[h,g]=(0,V.useState)(null),_=(0,V.useRef)({id:i,revision:0}),v=(0,V.useRef)(i);v.current=i;let y=(0,V.useRef)({rawContent:n,noteBlocks:{},sourceRevision:0}),b=(0,V.useCallback)(e=>{_.current.revision=e.sourceRevision,m(e.sourceRevision),y.current.rawContent===e.rawContent&&Object.keys(y.current.noteBlocks).length===Object.keys(e.blocks).length&&Object.values(y.current.noteBlocks).every(t=>{let n=e.blocks[t.id];return n&&n.from===t.from&&n.to===t.to&&n.kind===t.kind})&&(y.current={rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision},f(e.blocks))},[]),x=RJ({onSave:(0,V.useCallback)(async e=>{if(e.routeId===v.current&&h)throw h;let t=await Nj.saveNote({noteId:e.noteId,rawContent:e.rawContent,blocks:e.noteBlocks,expectedSourceRevision:_.current.id===e.noteId?_.current.revision:e.sourceRevision,metadata:{title:e.title},noteType:`playground`});v.current===e.routeId&&(_.current.id=t.id,u(t.id),b({rawContent:t.rawContent,blocks:t.blocks??{},sourceRevision:t.sourceRevision??1}))},[b,h]),getSnapshotKey:e=>JSON.stringify([e.noteId,e.rawContent,Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])});(0,V.useEffect)(()=>{let e=!1;_.current={id:i,revision:0},c(!0),g(null);let a=Aa(n,{sourceRevision:1,registeredWidgets:wa}),s=(e,t,n,r)=>{o(e),f(t),m(n),u(r),_.current={id:r??i,revision:n},y.current={rawContent:e,noteBlocks:t,sourceRevision:n}},l=setTimeout(()=>{e||(e=!0,s(n,a,0),g(Error(`Note load timed out. Reload before saving to avoid overwriting stored content.`)),c(!1))},zJ);return(async()=>{try{let o=await uz.getPage(i);if(e)return;if(o)s(o.content,o.noteBlocks??{},o.sourceRevision??1,o.id);else if(r){let r=await Nj.saveNote({noteId:i,rawContent:n,blocks:a,expectedSourceRevision:0,metadata:{title:t},noteType:`playground`});e||s(r.rawContent,r.blocks??{},r.sourceRevision??1,r.id)}else s(n,a,0)}catch(t){e||(s(n,a,0),g(t))}finally{clearTimeout(l),e||c(!1)}})(),()=>{e=!0,clearTimeout(l)}},[i,n,t,r]);let S=(0,V.useCallback)(e=>{(y.current.rawContent!==e.rawContent||JSON.stringify(Object.values(y.current.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))&&(y.current=e,o(e.rawContent),f(e.noteBlocks),x.onChange({...e,routeId:i,noteId:_.current.id,title:t}))},[x.onChange,i,t]),C=(0,V.useCallback)(e=>{if(o(e),y.current.rawContent===e)return;let t=Aa(e,{sourceRevision:_.current.revision||1,registeredWidgets:wa});S({rawContent:e,noteBlocks:t,sourceRevision:_.current.revision})},[S]),w=(0,V.useCallback)(async()=>{S({rawContent:n,sourceRevision:_.current.revision,noteBlocks:Aa(n,{sourceRevision:_.current.revision||1,registeredWidgets:wa})}),await x.flush()},[n,S,x.flush]),T=(0,V.useCallback)(()=>_.current.revision,[]);return{content:a,loading:s,entryId:l,noteBlocks:d,sourceRevision:p,onIdentityChange:S,onSaved:b,onChange:C,onLineChange:x.onLineChange,onBlur:x.onBlur,flush:x.flush,committedSourceRevision:T,resetToOriginal:w,isModified:a!==n,error:x.error??h}}var VJ=new Map;function HJ(e,t,n){let r=t?e.filter(e=>e.blockId===t):e;if(r.length===0)return{current:[],currentVersion:0,history:new Map};let i=new Map;for(let e of r){let t=e.blockVersion;i.has(t)||i.set(t,[]),i.get(t).push(e)}let a=[],o=0;for(let[e,t]of i)t.some(e=>e.blockContentId===n)&&(e>o?(o=e,a.length=0,a.push(...t)):e===o&&a.push(...t));let s=new Map;for(let[e,t]of i)e!==o&&s.set(e,{version:e,contentId:t[0]?.blockContentId,results:t});return{current:a,currentVersion:o,history:s}}function UJ(e,t,n,r,i){let a=e.map(e=>{if(e.type!==`time`&&e.type!==`log`)return e;let i=parseInt(e.id.replace(`${e.type}-line-`,``),10),a=t.find(e=>e.startLine+1===i),o={};if(r&&a){let{current:e}=HJ(r,a.id,a.contentId);o={hasResult:e.length>0,resultCount:e.length}}return e.type===`log`||!n?{...e,...o}:{...e,...o,onRun:()=>{let e=a||t.find(e=>e.startLine+1===i)||t[0];e&&n(e)}}});if(i){let e=a.findIndex(e=>e.type===`heading`),t=e===-1?0:e;if(a[t])return a.map((e,n)=>n===t?{...e,onRun:i,runIcon:`edit`}:e)}return a}function WJ({content:e,scriptBlocks:t,onStartWorkout:n,results:r,onEditNote:i}){let a=(0,V.useMemo)(()=>UJ(Wz(e),t,n,r,i),[e,t,n,r,i]),{setL3Items:o}=hA();return(0,V.useEffect)(()=>(o(Gz(a)),()=>o([])),[a,o]),a}function GJ(e){switch(e.kind){case`journal`:return KA(e.id);case`playground`:return WA(e.id);case`workout`:return e.category===`effort`?cj(e.id):e.category===`equipment`?ij(e.id):e.category?ZA(e.category,e.id):qA(e.raw)}}function KJ(e){let t=ZF(e);return t.kind===`workout`&&!t.category?qA(e):GJ(t)}var qJ={efforts:[],related:[],backlinks:[]},JJ=8;function YJ(e){let t=e.id,n=e.type===`playground`||e.sourceId===`playground`||t.startsWith(`playground/`),r=ZF(t);if(e.type===`journal`||e.journalDate||!n&&r.kind===`journal`){let n=e.journalDate??(r.kind===`journal`?r.id:void 0);return{zone:`journal`,up:n?{id:n,title:`Journal`,to:GA(n)}:null,stamps:[t]}}if(n||r.kind===`playground`){let e=cI({id:t});return{zone:`playgrounds`,up:{id:`playgrounds`,title:`Playgrounds`,to:nj()},stamps:[`/playground/${e}`]}}if(r.kind===`workout`){if(r.category===`effort`)return{zone:`efforts`,up:{id:`efforts`,title:`Efforts`,to:rj()},stamps:[cj(r.id)]};if(r.category===`equipment`)return{zone:`equipment`,up:{id:`equipment`,title:`Equipment`,to:Q.equipment},stamps:[ij(r.id)]};if(r.category===`feeds`){let[,e,n,r]=t.split(`/`);return{zone:`feeds`,up:e?{id:e,title:e,to:YA(e)}:null,stamps:e&&n&&r?[`/feeds/${e}/${n}/${r}`]:[]}}if(r.category)return{zone:`feeds`,up:{id:r.category,title:r.category,to:XA(r.category)},stamps:[ZA(r.category,r.id)]}}if(e.type===`page`&&(e.pageId??e.slug)){let t=e.pageId??e.slug;return{zone:null,up:{id:t,title:`/p/${t}`,to:tj(t)},stamps:[]}}return{zone:null,up:null,stamps:[]}}function XJ(e){if(!e.startsWith(`/`))return null;let t=e.split(`#`)[0],n=t.replace(/\/+$/,``).split(`/`).filter(Boolean),r=n[n.length-1];if(r)try{r=decodeURIComponent(r)}catch{}return{id:t,title:r||t,to:t}}function ZJ(e,t){let n=new Set,r=[];for(let i of e){if(!i.effortSlug||n.has(i.effortSlug))continue;n.add(i.effortSlug);let e=!t||t.has(i.effortSlug);r.push({id:i.effortSlug,title:i.effortSlug,to:e?cj(i.effortSlug):`${rj()}?q=${encodeURIComponent(i.effortSlug)}`})}return r}function QJ(e,t,n=JJ){let r=new Set(e.filter(e=>e.noteId===t&&e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId));if(r.size===0)return[];let i=new Map;for(let a of e)if(a.dataType===`wod`&&!(!a.blockContentId||!r.has(a.blockContentId)||a.noteId===t)&&!i.has(a.noteId)&&(i.set(a.noteId,{id:a.noteId,title:a.noteTitle||a.noteId,to:KJ(a.noteId)}),i.size>=n))break;return[...i.values()]}function $J(e,t,n){if(t.length===0)return[];let r=e.filter(e=>e.id!==n&&!!e.sourceId&&t.some(t=>e.sourceId===t||e.sourceId.startsWith(`${t}#`)));return r.sort((e,t)=>t.createdAt-e.createdAt),r.map(e=>({id:e.id,title:e.title||e.id,to:KJ(e.id)}))}function eY(e,t){let n=new Map;for(let r of e)r.noteId===t||n.has(r.noteId)||n.set(r.noteId,{id:r.noteId,title:r.noteId,to:KJ(r.noteId)});return[...n.values()]}function tY({noteId:e,stamps:t,effortSlug:n}){let r=t.join(`
153
- `),[i,a]=(0,V.useState)({key:``,data:qJ}),o=`${e}\u0000${r}\u0000${n??``}`,s=i.key===o?i.data:qJ;return(0,V.useEffect)(()=>{let t=!1,i=r?r.split(`
154
- `):[];return Promise.all([X.getAllFromIndex(`block_efforts`,`by-note`,e),X.getAllFromIndex(`block_index`,`by-note`,e),X.getAllNotes(),X.getAllEfforts(),n?X.getAllFromIndex(`block_efforts`,`by-effort`,n):Promise.resolve([])]).then(async([r,a,o,s,c])=>{if(t)return qJ;let l=new Set(s.map(e=>e.slug)),u=[...new Set(a.filter(e=>e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId))],d=await Promise.all(u.map(e=>X.getAllFromIndex(`block_index`,`by-content`,e)));if(t)return qJ;let f=QJ([...a,...d.flat()],e);if(n){let t=new Set(f.map(e=>e.id));for(let n of eY(c,e))t.has(n.id)||(t.add(n.id),f.push(n))}return{efforts:ZJ(r,l),related:f,backlinks:$J(o,i,e)}}).then(e=>{!t&&e&&a({key:o,data:e})}).catch(()=>{}),()=>{t=!0}},[e,r,n,o]),s}function nY({data:e,up:t,source:n,relatedLabel:r=`Related workouts`}){let{setContextNav:i}=hA(),a=mt();return(0,V.useEffect)(()=>{let o=[],s=(e,t,n)=>{n.length!==0&&o.push({kind:`section`,id:e,label:t,entries:n.map(t=>({kind:`link`,id:`${e}:${t.id}`,label:t.title,to:t.to}))})};return s(`note-context-up`,`Up`,t?[t]:[]),s(`note-context-source`,`Source`,n?[n]:[]),s(`note-context-efforts`,`Efforts`,e.efforts),s(`note-context-backlinks`,`Journal copies`,e.backlinks),s(`note-context-related`,r,e.related),i({pathname:a.pathname,spec:o}),()=>i(void 0)},[e,t,n,r,a.pathname,i]),null}function rY(e,t){return(0,V.useMemo)(()=>{let n=[];return t.onPlay&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`play`,label:`Play`,icon:(0,H.jsx)(rn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:t.onPlay}),t.onLog&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`log`,label:`Log`,icon:(0,H.jsx)(Be,{className:`h-3 w-3`}),primary:!0,onClick:t.onLog}),t.onOpenInPlayground&&(e===`journal-plan`||e===`collection-readonly`)&&n.push({id:`open-in-playground`,label:`Playground`,icon:(0,H.jsx)(o,{className:`h-3 w-3`}),onClick:t.onOpenInPlayground}),t.onShare&&n.push({id:`share`,label:`Share`,icon:(0,H.jsx)(g,{className:`h-3 w-3`}),onClick:t.onShare}),t.onAddToToday&&e===`playground`&&n.push({id:`add-to-today`,label:`Today`,icon:(0,H.jsx)(ye,{className:`h-3 w-3`}),onClick:t.onAddToToday}),t.onSchedule&&n.push({id:`schedule`,label:`Schedule`,icon:(0,H.jsx)(Ae,{className:`h-3 w-3`}),onClick:t.onSchedule}),n},[e,t.onPlay,t.onLog,t.onShare,t.onAddToToday,t.onSchedule,t.onOpenInPlayground])}async function iY(e){let t=new TextEncoder().encode(e),n=new CompressionStream(`gzip`),r=n.writable.getWriter(),i=n.readable.getReader();r.write(t),r.close();let a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;let l=``;for(let e=0;e<s.length;e++)l+=String.fromCharCode(s[e]);return btoa(l).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function aY(e,t){let n=e.dialect||`time`,r=await iY(`\`\`\`${e.sport?`${n}:${e.sport}`:n}\n${e.content.trimEnd()}\n\`\`\`\n`),i=`${window.location.origin}${$A({zip:r})}`;return t?`${i}&src=${encodeURIComponent(t)}`:i}async function oY(e,t){let n=await aY(e,window.location.pathname),{pathname:r,search:i}=new URL(n);t(`${r}${i}`)}async function sY(e){let t=await aY(e,window.location.pathname);window.open(t,`_blank`)}async function cY(e){let t=e.dialect||`time`,n=await iY(`\`\`\`${e.sport?`${t}:${e.sport}`:t}\n${e.content.trimEnd()}\n\`\`\`\n`),r=`shared by ${Yy()}`;return`${window.location.origin}/?z=${n}&by=${encodeURIComponent(r)}`}function lY(e){cY(e).then(e=>{navigator.clipboard.writeText(e).then(()=>{Z({title:`Link copied`,description:`Share link copied to clipboard.`})}).catch(()=>{Z({title:`Could not copy`,description:e,variant:`destructive`})})})}function uY(e=`end`){let t=(0,V.useRef)(null),[n,r]=(0,V.useState)(e);return{triggerRef:t,align:n,recompute:(0,V.useCallback)(()=>{let e=t.current;if(!e)return;let{left:n,right:i}=e.getBoundingClientRect(),a=(n+i)/2;r(a>window.innerWidth/2?`end`:`start`)},[])}}function dY(e,t){if(t){t();return}let n=new Blob([e.content],{type:`text/markdown`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.name.replace(/[/\\:*?"<>|]/g,`-`)}.md`,i.click(),URL.revokeObjectURL(r)}function fY({currentWorkout:e,onDownload:t}){return e.content===``?null:(0,H.jsxs)(`button`,{type:`button`,onClick:()=>dY(e,t),className:`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,H.jsx)(Be,{className:`size-4 shrink-0`}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Download Markdown`})]})}function pY(e,t,n){let r=Sn(),{l3Items:i,scrollToSection:a,secondarySpec:o,streamControls:s}=hA(),c=t&&t.length>0?t:i,l=MI(o),u=[];s&&u.push({kind:`custom`,id:`l3-stream-controls`,nav:!0,render:()=>(0,H.jsx)(IL,{streamControls:s})});for(let e of l)if(e.kind===`section`){if(e.entries.length===0)continue;u.push({kind:`heading`,id:e.id,label:e.label,nav:!0});for(let t of e.entries)u.push({kind:`row`,id:t.id,label:t.label,nav:!0,onSelect:()=>{t.onRun?t.onRun():t.to?r(t.to):t.sectionId&&a(t.sectionId)}})}else u.push({kind:`row`,id:e.id,label:e.label,nav:!0,onSelect:()=>{e.onRun?e.onRun():e.to?r(e.to):e.sectionId&&a(e.sectionId)}});if(c.length>0){u.push({kind:`heading`,id:`on-this-page`,label:`On this page`,nav:!0});for(let e of c)u.push({kind:`row`,id:e.id,label:e.label,nav:!0,secondary:e.secondaryAction?{label:e.secondaryAction.label,icon:e.secondaryAction.icon&&(0,H.jsx)(e.secondaryAction.icon,{className:`size-3.5`}),onSelect:()=>{e.secondaryAction?.action.type===`call`&&e.secondaryAction.action.handler()}}:void 0,onSelect:()=>{e.action.type===`call`?e.action.handler():a(e.id)}})}return e.content!==``&&u.push({kind:`row`,id:`download-markdown`,label:`Download Markdown`,icon:(0,H.jsx)(Be,{className:`size-4`}),nav:!1,onSelect:()=>dY(e,n)}),u}function mY({currentWorkout:e,onDownload:t,items:n}){let r=pY(e,n,t),i=e=>e.kind===`heading`?(0,H.jsx)(SL,{children:e.label},e.id):e.kind===`custom`?(0,H.jsx)(`div`,{className:`px-1 py-1`,children:e.render()},e.id):(0,H.jsxs)(yL,{onClick:e.onSelect,className:`gap-2`,children:[e.icon,(0,H.jsx)(`span`,{className:U(`flex-1 truncate`,e.secondary&&`pr-8`),children:e.label}),e.secondary&&(0,H.jsx)(`button`,{className:`ml-auto flex items-center justify-center size-5 rounded text-primary hover:bg-primary/10 transition-colors`,title:e.secondary.label,onClick:t=>{t.stopPropagation(),e.secondary?.onSelect()},children:e.secondary.icon})]},e.id),a=r.filter(e=>e.nav),o=r.filter(e=>!e.nav);return r.length===0?null:(0,H.jsxs)(gL,{children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(W,{variant:`ghost`,size:`icon`,"aria-label":`Page options`,className:U(`text-muted-foreground`,`2xl:hidden`),children:[(0,H.jsx)(ge,{className:`size-5`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Page options`})]})}),(0,H.jsxs)(vL,{align:`end`,className:`min-w-56 max-h-[calc(100dvh-6rem)] overflow-y-auto`,children:[a.length>0&&(0,H.jsxs)(`div`,{className:`2xl:hidden`,children:[a.map(i),(0,H.jsx)(xL,{})]}),o.map(i)]})]})}var hY=Hz("# My Workout\n\n```time\n$CURSOR\n```\n"),gY={content:hY.content,cursorOffset:hY.cursorOffset};function _Y({mode:e,currentWorkout:t,index:n,onReset:r}){let i=Sn(),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(!1),l=tR(),u=UL(),d=l&&u;return d&&e!==`playground`?null:(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[e===`playground`&&(0,H.jsx)(mU,{primary:{id:`new-playground`,label:a?`Creating…`:`New`,icon:ye,action:{type:`call`,handler:async()=>{if(!a){o(!0);try{let e=await iH(gY.content);i(`/playground/${encodeURIComponent(e)}`)}finally{o(!1)}}}}},secondary:{id:`reset-playground`,label:s?`Resetting…`:`Reset to default`,icon:We,action:{type:`call`,handler:async()=>{if(!(!r||s)){c(!0);try{await r()}finally{c(!1)}}}}},size:`sm`}),!d&&(0,H.jsx)(IR,{}),!d&&(0,H.jsx)(RG,{}),!d&&(0,H.jsx)(mY,{currentWorkout:t,items:n&&n.length>0?Gz(n):void 0})]})}function vY({feedSlug:e,feedDate:t,feedItem:n,theme:r,onViewCreated:i}){let a=Sn(),o=sD(),{item:s,feed:c}=(0,V.useMemo)(()=>{if(!o)return{item:void 0,feed:void 0};let r=pz(o).find(t=>t.id===e);return{item:r?.items.find(e=>e.feedDate===t&&e.id===n),feed:r}},[o,e,t,n]),{content:l,noteBlocks:u,sourceRevision:d,onIdentityChange:f,onSaved:p,onChange:m,onLineChange:h,onBlur:g,flush:_}=BJ({category:`feed/${e}/${t}`,name:n,mdContent:s?.content??`# ${n}\n\n*Feed item not found.*\n`,seedOnMount:!1}),[v,y]=(0,V.useState)([]),b=`feed/${e}/${t}/${n}`,x=(0,V.useCallback)(async r=>{try{let i=C(),o=await OJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),l=Object.values(o.blocks??{}).find(e=>e.kind===`wod`);if(!l)throw Error(`The saved journal workout is unavailable.`);VJ.set(i,{block:{...r,id:l.id},noteId:o.id}),a(JA(o.journalDate??``,i))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[c,t,n,e,s,a,b]),S=(0,V.useCallback)(async r=>{try{let i=await OJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),o=wJ(new Date);Z({title:`Added to journal`,description:i.journalDate===o?`Added to today's journal`:`Added to ${i.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>a(KA(i.journalDate??o)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[c,t,n,e,s,a]),[w,T]=(0,V.useState)(null),E=(0,V.useCallback)(async(r,i)=>{let o=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,`0`)}-${String(i.getDate()).padStart(2,`0`)}`;try{await OJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content,date:i}),a(KA(o)),Z({title:`Scheduled`,description:`Added to journal for ${o}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>a(KA(o)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[c,t,n,e,s,a]),D=WJ({content:l,scriptBlocks:v,onStartWorkout:x}),O=`feeds/${e}/${t}/${n}`,k=(0,V.useMemo)(()=>YJ({id:O,type:`collection`}),[O]),A=tY({noteId:O,stamps:k.stamps}),j=rY(`collection-readonly`,{onPlay:x,onShare:lY,onAddToToday:S,onSchedule:T,onOpenInPlayground:e=>oY(e,a)});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fL,{title:s?.name??n,actions:(0,H.jsx)(nR,{label:`Workout actions`,children:(0,H.jsx)(_Y,{mode:`collection-readonly`,currentWorkout:{name:s?.name??n,content:l},index:D})}),editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(nY,{data:A,up:k.up}),(0,H.jsx)(sK,{value:l,onChange:m,onCursorPositionChange:h,onBlur:g,noteId:b,noteBlocks:u,sourceRevision:d,onIdentityChange:e=>f({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:p,onSaveRequest:_,onCommitChange:_,commands:j,enableInlineRuntime:!1,onViewCreated:i,theme:r,showLineNumbers:!1,onBlocksChange:y})]})}),w&&(0,H.jsx)(lS,{open:!0,onClose:()=>T(null),title:`Schedule workout`,children:(0,H.jsx)(LJ,{selectedDate:null,onDateSelect:e=>{E(w,e),T(null)}})})]})}function yY(e,t){if(e.startsWith(`# 👋`))return e;let n=t?.replace(/^shared by:?\s*/i,``).trim();return`${n?`# 👋 ${n} sent you this workout`:`# 👋 Edit Me`}\n\nChange the reps, distance, or load below — this is live.\n\n${e}\n\n> Press **Run** ↑ to start the Clock.\n`}var bY=`wodwiki.homeShared.v1`;function xY(){return typeof window<`u`&&window.localStorage?window.localStorage:null}function SY(e){try{xY()?.setItem(bY,JSON.stringify(e)),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`wodwiki:home-shared`,{detail:e}))}catch{}}function CY(){try{let e=xY()?.getItem(bY);if(!e)return null;let t=JSON.parse(e);return typeof t?.content==`string`?{content:t.content,by:typeof t.by==`string`?t.by:void 0}:null}catch{return null}}function wY(){try{xY()?.removeItem(bY)}catch{}}function TY({pageRoute:e,quests:t,running:n}){let{markComplete:r}=_H(e,t),i=(0,V.useMemo)(()=>t.filter(e=>e.validation?.type===`run-started`),[t]);(0,V.useEffect)(()=>{if(n)for(let e of i)r(e.id)},[n,i,r])}var EY={"session-insights":`qs-tour-analytics`},DY={"workout-complete":!0,"run-started":!0};function OY(e,t){let{markComplete:n}=_H(e,t),r=(0,V.useRef)(new Set);return r.current=new Set(t.filter(e=>!e.validation||!DY[e.validation.type]).map(e=>e.id)),(0,V.useCallback)(e=>{let t=EY[e];t&&r.current.has(t)&&n(t)},[n])}var kY=(0,V.createContext)(null);function AY({children:e}){let t=(0,V.useRef)({"editor.window":null,"editor.wodBlock":null,"editor.runButton":null,"editor.typeahead":null,"timer.floor":null,"timer.nextButton":null,"timer.castButton":null,"metrics.efforts":null,"metrics.data":null,"metrics.compound":null,"analytics.vocab":null,"analytics.table":null,"analytics.graphs":null,"analytics.dashboard":null}),[n,r]=(0,V.useState)(0),i=(0,V.useCallback)((e,n)=>{t.current[e]!==n&&(t.current[e]=n,r(e=>e+1))},[]);return(0,H.jsx)(kY.Provider,{value:{register:i,registry:t,version:n},children:e})}function jY(){return(0,V.useContext)(kY)||{registry:{current:{}},register:()=>()=>{},version:0}}function MY(e){let t=(0,V.useContext)(kY)?.register;return(0,V.useCallback)(n=>t?.(e,n),[e,t])}function NY({ringKey:e,el:t}){let{register:n}=jY();return(0,V.useLayoutEffect)(()=>{n(e,t)},[e,t,n]),null}function PY({target:e,accent:t,canvasRef:n}){let{registry:r,version:i}=jY(),[a,o]=(0,V.useState)(null),s=e?.key??null;return(0,V.useLayoutEffect)(()=>{if(!s){o(null);return}let e=()=>{let e=r.current[s],t=n.current;if(!e||!t){o(null);return}let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),c=Math.round(i.left-a.left),l=Math.round(i.top-a.top),u=Math.round(i.width),d=Math.round(i.height);if(u<=0||d<=0||c+u<0||l+d<0||c>a.width||l>a.height){o(null);return}o({x:c,y:l,w:u,h:d})};e();let t=window.setTimeout(e,120),i=window.setTimeout(e,480),a=null,c=r.current[s];c&&typeof ResizeObserver<`u`&&(a=new ResizeObserver(e),a.observe(c));let l=new MutationObserver(e);return c&&l.observe(c,{attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`resize`,e),()=>{window.clearTimeout(t),window.clearTimeout(i),a?.disconnect(),l.disconnect(),window.removeEventListener(`resize`,e)}},[s,i,r,n]),!e||!a?null:(0,H.jsx)(`div`,{"data-testid":`tour-ring`,className:`pointer-events-none absolute z-30 rounded-2xl transition-all duration-500 ease-out`,style:{left:a.x-6,top:a.y-6,width:a.w+12,height:a.h+12,boxShadow:`0 0 0 2px ${t}`}})}var FY=`hsl(var(--primary))`,IY={ink:`hsl(var(--foreground))`,editor:FY,timer:FY,analytics:FY,library:FY,rounds:FY},LY={editor:`WOD Editor & Autocomplete`,timer:`Clock`,analytics:`WQL Analytics`,metrics:`Own the Metrics`,result:`Run Results`},RY={start:`/guide/start`,protocols:`/guide/protocols`,structure:`/guide/structure`,metrics:`/guide/metrics`,clock:`/guide/clock`,wql:`/guide/wql`,dashboards:`/guide/dashboards`,sessions:`/guide/sessions`,basics:`/guide/start`,"custom-metrics":`/guide/metrics`,dialects:`/guide/sessions#intent`,complex:`/guide/sessions#full-session`};function zY(){return(0,H.jsxs)(`div`,{className:`@container flex w-full flex-col items-center text-center`,children:[(0,H.jsxs)(`h1`,{className:`text-[clamp(32px,6.5cqi,64px)] font-extrabold leading-[1.02] tracking-[-0.04em]`,children:[(0,H.jsxs)(`span`,{className:`block`,children:[(0,H.jsx)(`span`,{className:`mr-[0.35em]`,children:`Write it.`}),(0,H.jsx)(`span`,{children:`Time it.`})]}),(0,H.jsxs)(`span`,{className:`block`,children:[(0,H.jsx)(`span`,{className:`mr-[0.35em]`,children:`Track it.`}),(0,H.jsx)(`span`,{children:`Own it.`})]})]}),(0,H.jsxs)(`p`,{className:`mt-4 xl:mt-6 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[15px] sm:text-base xl:text-lg leading-relaxed text-muted-foreground`,children:[`Plain-text Markdown becomes a step-through workout clock, `,(0,H.jsx)(`br`,{}),`line and splits become queryable training data points.`]})]})}var BY=`https://github.com/bitcobblers/wod-wiki`;function VY(){return(0,H.jsx)(`footer`,{"data-testid":`tour-footer`,className:`border-t border-border px-6 py-8`,children:(0,H.jsxs)(`p`,{className:`mx-auto flex max-w-3xl flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground`,children:[(0,H.jsxs)(`span`,{children:[`© `,new Date().getFullYear(),` WOD Wiki`]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsx)(`a`,{href:BY,target:`_blank`,rel:`noopener noreferrer`,className:`underline-offset-4 transition-colors hover:text-foreground hover:underline`,children:`GitHub repository`})]})})}async function HY(){await xD.wipe();try{for(let e=localStorage.length-1;e>=0;e--){let t=localStorage.key(e);t&&t!==`wodwiki.dataSettings.v1`&&localStorage.removeItem(t)}}catch{}try{sessionStorage.clear()}catch{}}function UY({index:e,before:t,accentText:n,after:r,accent:i,blurb:a}){return(0,H.jsx)(`header`,{className:`flex items-center border-b border-border/60 px-6 py-14 lg:px-12 xl:py-20 2xl:py-24 xl:px-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px]`,children:[(0,H.jsxs)(`h2`,{className:`flex items-baseline gap-4 xl:gap-6 text-[clamp(26px,3.6vw,52px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[(0,H.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:e}),(0,H.jsxs)(`span`,{children:[t,n,r]})]}),(0,H.jsx)(`p`,{className:`mt-3 xl:mt-4 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:a})]})})}var WY=`https://github.com/bitcobblers/wod-wiki`,GY=`https://forms.gle/6YHpxwAJh6PAsyAQ6`,KY=`underline-offset-4 transition-colors hover:text-foreground hover:underline`;function qY(e){let t=`inline-flex items-center gap-1.5 font-medium text-foreground underline-offset-4 transition-colors hover:underline`,n=(0,H.jsxs)(H.Fragment,{children:[e.children,(0,H.jsx)(h,{className:`size-3.5 text-muted-foreground/50`,"aria-hidden":!0})]});return e.href===void 0?e.onClick===void 0?(0,H.jsx)(Wn,{to:e.to,className:t,children:n}):(0,H.jsx)(`button`,{type:`button`,onClick:e.onClick,className:`text-left ${t}`,children:n}):(0,H.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noopener noreferrer`,className:t,children:n})}function JY({children:e}){return(0,H.jsxs)(`li`,{className:`flex gap-2.5 text-sm leading-6 text-muted-foreground`,children:[(0,H.jsx)(`span`,{"aria-hidden":!0,className:`mt-[11px] size-1 shrink-0 rounded-full bg-muted-foreground/50`}),(0,H.jsx)(`span`,{children:e})]})}function YY(){return(0,H.jsx)(`span`,{className:`rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 font-mono text-[11px] font-medium text-emerald-600`,children:`Active`})}function XY(e){let t=e.icon;return(0,H.jsxs)(`article`,{className:`flex flex-col rounded-xl border border-border bg-background p-5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,H.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),e.badge]}),(0,H.jsx)(`h3`,{className:`mt-4 text-base font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.text}),(0,H.jsx)(`div`,{className:`mt-4 flex flex-1 flex-col gap-2 text-sm`,children:e.children})]})}function ZY(){let[e,t]=(0,V.useState)(!1),n=Sn(),[r]=(0,V.useState)(hD),i=async()=>{window.confirm(`Wipe every note, result, and setting stored in this browser? This cannot be undone.`)&&(t(!0),await HY(),window.location.reload())},a=async()=>{let e=Vj(),t=await Kj.create({journalDate:e,title:e,rawContent:``});YV.record(XV.noteCreated),n(qA(t.id))};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`section`,{id:`tour-section-offerings`,"data-testid":`tour-section-offerings`,"aria-label":`You own your data`,children:[(0,H.jsx)(UY,{index:`03`,before:`You `,accentText:`Own the Data`,after:``,accent:IY.library,blurb:`Browser modes run from IndexedDB, with optional backup and sync to your own Turso database. API deployments use a server you choose.`}),(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 pb-16 pt-10 lg:px-12 xl:px-16`,children:[(0,H.jsxs)(`p`,{className:`mx-auto mb-5 flex max-w-5xl flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground`,role:`status`,children:[(0,H.jsx)(`span`,{children:`Current mode: API server`}),(0,H.jsx)(Wn,{to:Q.settingsStorage,className:KY,children:`Configure data storage`})]}),(0,H.jsxs)(`div`,{className:`mx-auto grid max-w-5xl grid-cols-1 gap-5 md:grid-cols-3`,children:[(0,H.jsxs)(XY,{icon:je,title:`Browser only`,badge:void 0,text:`Everything lives in this browser's IndexedDB — the default mode. Works offline, no account, no server copy.`,children:[(0,H.jsx)(qY,{onClick:()=>void a(),children:`Create your journal`}),(0,H.jsx)(qY,{to:Q.playgroundRoot,children:`Start Writing in a Playground`}),(0,H.jsx)(qY,{to:`/feeds`,children:`Explore the notebooks`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(JY,{children:`Offline and fast. Notes and results stay in this browser.`}),(0,H.jsx)(JY,{children:`Tied to this browser — export or back it up before switching browsers or clearing site data.`})]}),(0,H.jsx)(`button`,{type:`button`,onClick:i,disabled:e,className:`mt-1 text-left text-xs text-muted-foreground disabled:opacity-50 ${KY}`,children:e?`Clearing…`:`Clear my data`})]}),(0,H.jsxs)(XY,{icon:ie,title:`Browser + your Turso`,badge:void 0,text:`Same local execution — plus a background backup of your data to a free Turso database you own, so multiple browsers stay in sync.`,children:[(0,H.jsx)(qY,{to:Q.settingsStorage,children:`Configure backup & sync`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(JY,{children:`Queries still run locally in the browser — sync copies committed changes in the background.`}),(0,H.jsx)(JY,{children:`Bring your own free Turso database — URL and auth token, kept in this browser only.`}),(0,H.jsx)(JY,{children:`Sync needs network; without it you keep working locally and changes upload later.`})]})]}),(0,H.jsxs)(XY,{icon:ln,title:`API server`,badge:(0,H.jsx)(YY,{}),text:`Build the app for API storage and run the Wod Wiki server yourself — local or cloud data access through a server you administer.`,children:[(0,H.jsx)(qY,{href:WY,children:`View source`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(JY,{children:`Centralized data for a team or gym — one SQLite, Turso, or Postgres backend.`}),(0,H.jsx)(JY,{children:`You run the server — network required, and server admin is on you.`})]})]})]})]})]}),(0,H.jsxs)(`section`,{id:`tour-section-hosted`,"data-testid":`tour-section-hosted`,"aria-label":`Wod-Wiki hosted`,children:[(0,H.jsx)(UY,{index:`04`,before:`Wod-Wiki `,accentText:`Hosted`,after:``,accent:IY.library,blurb:`Rather hand the caretaking to us? Wod-Wiki hosted is still taking shape — fill out the survey and help shape the plans.`}),(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 pb-16 pt-10 lg:px-12 xl:px-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto grid max-w-5xl grid-cols-1 gap-5 md:grid-cols-2`,children:[(0,H.jsxs)(XY,{icon:vr,title:`Individuals`,text:`For people who don't want dev-level configuration — we host the database for you and keep every device in sync.`,children:[(0,H.jsxs)(`ul`,{className:`space-y-1.5`,children:[(0,H.jsx)(JY,{children:`Managed hosting — we run the database; you just sign in.`}),(0,H.jsx)(JY,{children:`Profile page with a public feed.`}),(0,H.jsx)(JY,{children:`Sync across your apps and devices.`})]}),(0,H.jsxs)(`div`,{className:`mt-auto pt-3`,children:[(0,H.jsx)(qY,{href:GY,children:`Fill out interest survey`}),(0,H.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:`Takes two minutes — tell us what you'd like in a hosted personal account.`})]})]}),(0,H.jsxs)(XY,{icon:Ne,title:`Coaching & gyms`,text:`For gyms and coaches — member accounts, coach views, and your brand on the surface.`,children:[(0,H.jsxs)(`ul`,{className:`space-y-1.5`,children:[(0,H.jsx)(JY,{children:`Member accounts with coach views of athlete data.`}),(0,H.jsx)(JY,{children:`Coaches portal — programming dashboards and leaderboards.`}),(0,H.jsx)(JY,{children:`Athlete portal — private journals that roll up to their coach.`}),(0,H.jsx)(JY,{children:`Gym website hosting, competition timers, and whiteboard displays.`}),(0,H.jsx)(JY,{children:`Website branding — your gym's brand on pages and feeds.`})]}),(0,H.jsxs)(`div`,{className:`mt-auto pt-3`,children:[(0,H.jsx)(qY,{href:GY,children:`Fill out interest survey`}),(0,H.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:`Takes two minutes — help shape our coaching and gym features.`})]})]})]})})]})]})}var QY=({doc:e,onDocChange:t,onBlocksChange:n,onRun:r,theme:i,withRingTargets:a=!1})=>{let o=MY(`editor.wodBlock`),s=MY(`editor.runButton`),c=(0,V.useRef)(null),l=(0,V.useRef)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(null),m=(0,V.useCallback)(()=>{if(!a)return null;let e=c.current;if(!e)return null;let t=null,n=e.querySelector(`.cm-wod-fence-open`),r=e.querySelector(`.cm-wod-fence-close`);if(n&&r){let i=e.getBoundingClientRect(),a=n.getBoundingClientRect(),o=r.getBoundingClientRect();if(a.top>=i.top-2&&o.bottom<=i.bottom+2){let n=e.offsetWidth?i.width/e.offsetWidth:1;t={top:(a.top-i.top)/n,left:(Math.min(a.left,o.left)-i.left)/n,width:(Math.max(a.right,o.right)-Math.min(a.left,o.left))/n,height:(o.bottom-a.top)/n}}}d(t);let i=null,o=e.querySelector(`[data-testid="${sB.EDITOR_START_WORKOUT}"]`);if(o){let t=e.getBoundingClientRect(),n=o.getBoundingClientRect();if(n.width>0&&n.height>0&&n.top>=t.top-2&&n.bottom<=t.bottom+2&&n.left>=t.left-2&&n.right<=t.right+2){let r=e.offsetWidth?t.width/e.offsetWidth:1;i={top:(n.top-t.top)/r,left:(n.left-t.left)/r,width:n.width/r,height:n.height/r}}}return p(i),{block:t,run:i}},[a]);(0,V.useLayoutEffect)(()=>{if(!a)return;let e=c.current;if(!e)return;m();let t=window.setTimeout(m,120),n=window.setTimeout(m,480),r=null;if(typeof ResizeObserver<`u`){r=new ResizeObserver(m),r.observe(e);let t=l.current?.contentDOM;t&&r.observe(t)}let i=new MutationObserver(e=>{e.some(e=>e.target instanceof Element&&e.target.closest(`.cm-note-editor`))&&m()});i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`]});let o=0,s=0,u=()=>{m(),performance.now()-s<3e3&&(o=requestAnimationFrame(u))},d=()=>{s=performance.now(),cancelAnimationFrame(o),o=requestAnimationFrame(u)};d(),document.fonts?.ready?.then(d).catch(()=>{});let f=l.current?.scrollDOM;return f?.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m),()=>{window.clearTimeout(t),window.clearTimeout(n),r?.disconnect(),i.disconnect(),f?.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),cancelAnimationFrame(o)}},[e,a,m]);let h=(0,V.useCallback)(()=>{r()},[r]),g=(0,V.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:h},{id:`playground`,label:`Playground`,icon:(0,H.jsx)(k,{className:`h-3 w-3`}),onClick:e=>{sY(e)},splitIcon:(0,H.jsx)(nt,{className:`h-3 w-3`}),splitSuccessIcon:(0,H.jsx)(Zn,{className:`h-3 w-3 text-emerald-500`}),onSplitClick:e=>{lY(e)}}],[h]);return(0,H.jsx)(`div`,{className:`relative flex h-full flex-col bg-background text-left`,children:(0,H.jsxs)(`div`,{ref:c,className:`relative flex-1 min-h-0`,children:[(0,H.jsx)(sK,{noteId:`canvas:home`,value:e,onChange:t,onBlocksChange:n,onStartWorkout:h,commands:g,onViewCreated:e=>{l.current=e,a&&m()},theme:i,readonly:!1,showLineNumbers:!1,showFrontmatter:!1,enableOverlay:!1,enableInlineRuntime:!1,className:`h-full`}),a&&u&&(0,H.jsx)(`div`,{ref:o,"data-testid":`tour-wod-block-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:u.top,left:u.left,width:u.width,height:u.height}}),a&&f&&(0,H.jsx)(`div`,{ref:s,"data-testid":`tour-run-button-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:f.top,left:f.left,width:f.width,height:f.height}})]})})},$Y=e=>{let t=Math.max(0,Math.round(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`};function eX({result:e,onDismiss:t,dismissLabel:n}){let[r,i]=(0,V.useState)(Hx),a=e.logs??[];return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden p-4`,"data-testid":`tour-session-result`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3 border-b border-border/60 pb-3`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{className:`font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground`,children:`Session recorded`}),(0,H.jsx)(`div`,{className:`text-2xl font-extrabold tabular-nums tracking-tight`,children:$Y(e.duration)})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-muted-foreground`,children:[(0,H.jsx)(`span`,{className:e.completed?`rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 font-semibold text-emerald-600 dark:text-emerald-400`:`rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 font-semibold text-amber-600 dark:text-amber-400`,children:e.completed?`Completed`:`Stopped early`}),e.roundsCompleted!=null&&(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[`Rounds `,e.roundsCompleted,e.totalRounds==null?``:`/${e.totalRounds}`]}),e.repsCompleted!=null&&(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[`Reps `,e.repsCompleted]})]}),t&&(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-md border border-border px-3 py-1.5 text-[12px] font-medium transition-colors hover:bg-accent`,"data-testid":`tour-session-result-dismiss-top`,children:n})]}),(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto py-3`,children:[(0,H.jsx)(Kx,{presets:Ux,filter:r,onChange:i}),(0,H.jsx)(Jx,{outputs:a,filter:r,timeOrigin:e.startTime,onClearFilter:()=>i(``)})]}),t&&(0,H.jsx)(`div`,{className:`flex justify-end border-t border-border/60 pt-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-md border border-border px-3 py-1.5 text-[12px] font-medium transition-colors hover:bg-accent`,"data-testid":`tour-session-result-dismiss`,children:n??`Back`})})]})}function tX(e){let t=Number.isFinite(e.startTime)?e.startTime:0,n=[];for(let r of e.logs??[]){if(r.outputType!==`segment`||r.stackLevel!==1||r.line==null)continue;let e=r.timeSpan;if(!e||typeof e.started!=`number`||typeof e.ended!=`number`||e.ended<=e.started)continue;let i=r.metrics??[],a=e=>i.some(t=>t.type===e),o=i.find(e=>e.type===`effort`&&typeof e.value==`string`),s=a(`duration`)&&!a(`rep`)?`clock`:r.completionReason===`user-advance`?`next`:null;s&&n.push({start:e.started-t,end:e.ended-t,kind:s,label:o?.value??`Line ${r.line+1}`})}return n.length===0?null:{segments:n,totalMs:Number.isFinite(e.duration)&&e.duration>0?e.duration:Math.max(...n.map(e=>e.end)),clockMs:n.filter(e=>e.kind===`clock`).reduce((e,t)=>e+(t.end-t.start),0),nextMs:n.filter(e=>e.kind===`next`).reduce((e,t)=>e+(t.end-t.start),0),reactions:n.filter(e=>e.kind===`next`).map(e=>e.end-e.start)}}var nX=e=>{let t=Math.max(0,Math.round(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},rX=e=>`${(Math.round(e/100)/10).toFixed(1)}s`;function iX({result:e,onRun:t}){let n=(0,V.useMemo)(()=>e?tX(e):null,[e]);if(!e||!n)return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-4 p-8 text-center`,"data-testid":`tour-insights-empty`,children:[(0,H.jsx)(`p`,{className:`max-w-sm text-sm leading-relaxed text-muted-foreground`,children:`Run the workout and this window turns your run into data — rest vs. work, how fast you answered the clock, round by round.`}),(0,H.jsxs)(`button`,{type:`button`,onClick:t,"data-testid":`tour-insights-run`,className:`inline-flex min-h-11 items-center gap-2 rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow transition-colors hover:bg-primary/90`,children:[(0,H.jsx)(Ht,{className:`size-4`}),`Run to view the results`]})]});let{segments:r,totalMs:i,clockMs:a,nextMs:o,reactions:s}=n,c=s.length>0?s.reduce((e,t)=>e+t,0)/s.length:0,l=s.length>0?Math.max(...s):0,u=o>0?a/o:0;return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col gap-4 overflow-y-auto p-4`,"data-testid":`tour-insights`,children:[(0,H.jsxs)(`div`,{"data-testid":`tour-insights-timeline`,children:[(0,H.jsx)(`div`,{className:`flex h-3 w-full overflow-hidden rounded-full border border-border/60 bg-muted/40`,children:r.map((e,t)=>(0,H.jsx)(`div`,{title:`${e.label} — ${e.kind===`clock`?`countdown`:`to Next`} ${nX(e.end-e.start)}`,className:`h-full`,style:{flexGrow:e.end-e.start,flexBasis:0,backgroundColor:e.kind===`clock`?`hsl(var(--metric-rest))`:`hsl(var(--metric-time))`,marginLeft:+(t>0)}},t))}),(0,H.jsxs)(`div`,{className:`mt-1.5 flex items-center gap-4 font-mono text-[10px] uppercase tracking-wider text-muted-foreground`,children:[(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-rest))`}}),`Countdown`]}),(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-time))`}}),`To Next click`]}),(0,H.jsxs)(`span`,{className:`ml-auto`,children:[nX(i),` total`]})]})]}),(0,H.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,H.jsxs)(`div`,{"data-testid":`tour-insights-ratio`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,H.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Rest / Test Ratio`}),(0,H.jsxs)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:[`1 : `,u>0?(o/Math.max(a,1)).toFixed(1):`∞`]}),(0,H.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[nX(a),` on countdown timers · `,nX(o),` to click Next`]})]}),(0,H.jsxs)(`div`,{"data-testid":`tour-insights-reaction`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,H.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Reaction Time`}),(0,H.jsx)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:s.length>0?rX(c):`—`}),(0,H.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[s.length,` click`,s.length===1?``:`s`,s.length>1?` · slowest ${rX(l)}`:``]})]})]})]})}var aX=864e5;function oX(e){let t=new Date(e);return Math.round(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())/aX)}function sX(e,t){let n=[...e.keys()].filter(e=>e<=t);if(n.length===0)return[];let r=Math.min(...n),i=t=>e.get(t)??0,a=[];for(let e=r;e<=t;e++){let t=0,n=0;for(let r=0;r<28;r++){let a=i(e-r);n+=a,r<7&&(t+=a)}let r=t/7,o=n/28,s=0;for(let t=0;t<7;t++){let n=i(e-t)-r;s+=n*n}let c=Math.sqrt(s/7),l={day:e};o>0&&(l.acwr=r/o),c>0&&(l.monotony=r/c,l.strain=l.monotony*t),(l.acwr!==void 0||l.monotony!==void 0)&&a.push(l)}return a}var cX=864e5;function lX(e){return Math.round(e*10)/10}function uX(e,t,n=9){let r=new Date(e-t*cX);return r.setHours(n,0,0,0),r.getTime()}function dX(e,t,n,r,i,a={}){let o={canonicalKey:i};a.effortSlug&&(o.effortSlug=a.effortSlug),a.discipline&&(o.effortDiscipline=a.discipline),a.intensityTier&&(o.effortIntensityTier=a.intensityTier),e.push({id:e.length,outputType:`analytics`,timeSpan:{started:0},metrics:[{type:G.Label,value:t,origin:`analyzed`},{type:G.Metric,value:n,unit:r,origin:`analyzed`,metadata:o}],sourceBlockKey:``,stackLevel:0})}var fX=new Set([`tis`,`calc.acwr`,`calc.adherence`,`calc.ef`,`calc.pct1rm`]);function pX(e,t){return cg(e,{noteId:t.noteId,resultId:t.resultId,blockId:`example-block`,blockVersion:1,blockContentId:t.blockContentId,origin:`journal`,workoutTimestamp:t.timestamp}).map(e=>{let t=e.metrics[0];if(!t||!(`metadata`in t))return e;let n=t.metadata?.canonicalKey;return typeof n!=`string`||!fX.has(n)||typeof t.value!=`number`?e:{...e,reducerStats:{observedCount:1,sum:t.value,min:t.value,max:t.value}}})}function mX(e=Date.now()){let t=[],n=new Map,r=[],i=[],a=(e,t)=>{let r=oX(e);n.set(r,(n.get(r)??0)+t)};for(let n=0;n<16;n++){let o=(15-n)*7+1,s=uX(e,o);{let e=[{slug:`back-squat`,top:100+4*n,reps:5,tis:12.5},{slug:`bench-press`,top:80+2.5*n,reps:5,tis:10},{slug:`deadlift`,top:140+4*n,reps:3,tis:8.4}],r=[],i=0,o=0;for(let t of e){let e=t.reps*t.top;i+=e,o+=t.tis;let n={effortSlug:t.slug,discipline:`strength`,intensityTier:`high`};dX(r,`Total reps`,t.reps,`reps`,`totalReps`,n),dX(r,`Training intensity score`,t.tis,`pts`,`tis`,n),dX(r,`Total volume`,e,`kg`,`totalVolume`,n),dX(r,`Estimated 1RM`,lX(t.top*(1+t.reps/30)),`kg`,`calc.e1rm`,n),dX(r,`%1RM intensity`,lX(100/(1+t.reps/30)),`%`,`calc.pct1rm`,n)}let c=lX(i/100+13+o/10);dX(r,`Session load`,c,`AU`,`sessionLoad`,{discipline:`strength`,intensityTier:`high`}),t.push(...pX(r,{noteId:`example-strength-w${n}`,resultId:`example-strength-w${n}-r`,blockContentId:`example-content-strength`,timestamp:s})),a(s,c)}let c=uX(e,o+2);{let e=[],r;if(n%3==0){r=`high`;for(let[t,n,i,a]of[[`thruster`,45,2.2,42.5],[`pull-up`,45,1.6,0]]){let o={effortSlug:t,discipline:a?`strength`:`gymnastics`,intensityTier:r};dX(e,`Total reps`,n,`reps`,`totalReps`,o),dX(e,`Training intensity score`,lX(n*i),`pts`,`tis`,o),a&&dX(e,`Total volume`,n*a,`kg`,`totalVolume`,o)}}else if(n%3==1){r=`moderate`;let t=16+n%5;for(let[n,i,a]of[[`pull-up`,5,1.5],[`push-up`,10,1.2],[`air-squat`,15,1.1]]){let o=t*i,s={effortSlug:n,discipline:`gymnastics`,intensityTier:r};dX(e,`Total reps`,o,`reps`,`totalReps`,s),dX(e,`Training intensity score`,lX(o*a),`pts`,`tis`,s)}}else{r=`moderate`;for(let[t,n,i]of[[`double-under`,150,.5],[`sit-up`,150,1.3]]){let a={effortSlug:t,discipline:`gymnastics`,intensityTier:r};dX(e,`Total reps`,n,`reps`,`totalReps`,a),dX(e,`Training intensity score`,lX(n*i),`pts`,`tis`,a)}}let i=lX(30.6);dX(e,`Session load`,i,`AU`,`sessionLoad`,{intensityTier:r}),t.push(...pX(e,{noteId:`example-conditioning-w${n}`,resultId:`example-conditioning-w${n}-r`,blockContentId:`example-content-conditioning`,timestamp:c})),a(c,i)}let l=uX(e,o+4,8);if(n%4==1)r.push(oX(l));else{let e=6e3+100*n,r=lX(e/2.8),o=[],s={effortSlug:`running`,discipline:`running`,intensityTier:`low`};dX(o,`Total distance`,e,`m`,`totalDistance`,s),dX(o,`Elapsed time`,r,`s`,`elapsed`,s),dX(o,`Training intensity score`,r,`pts`,`tis`,s);let c=lX(r/10);dX(o,`Session load`,c,`AU`,`sessionLoad`,{intensityTier:`low`}),t.push(...pX(o,{noteId:`example-run-w${n}`,resultId:`example-run-w${n}-r`,blockContentId:`example-content-run`,timestamp:l})),a(l,c),i.push({day:oX(l),pace:e/r})}let u=uX(e,o+6,10);{let e=4e3+50*n,r=lX(e/2),i=[],o={effortSlug:`rowing`,discipline:`rowing`,intensityTier:`moderate`};dX(i,`Total distance`,e,`m`,`totalDistance`,o),dX(i,`Elapsed time`,r,`s`,`elapsed`,o),dX(i,`Training intensity score`,r,`pts`,`tis`,o);let s=lX(r/10);dX(i,`Session load`,s,`AU`,`sessionLoad`,{intensityTier:`moderate`}),t.push(...pX(i,{noteId:`example-row-w${n}`,resultId:`example-row-w${n}-r`,blockContentId:`example-content-row`,timestamp:u})),a(u,s)}}let o=Math.max(...n.keys()),s=(e,t=10)=>{let n=new Date(e*cX);return n.setHours(t,0,0,0),n.getTime()},c=(e,n,r)=>{let i=[];for(let[e,t,n]of r)dX(i,e,t,n,e);t.push(...pX(i,{noteId:`example-calc`,resultId:e,blockContentId:`example-content-calc`,timestamp:n}))};for(let e of sX(n,o))e.acwr!==void 0&&c(`example-calc-d${e.day}`,s(e.day),[[`calc.acwr`,lX(e.acwr),`ratio`]]);let l=0,u=0,d=Math.min(...n.keys());for(let e=d;e<=o;e++){let t=n.get(e)??0;l+=(t-l)/42,u+=(t-u)/7,n.has(e)&&c(`example-calc-pmc-d${e}`,s(e),[[`calc.ctl`,lX(l),`AU`],[`calc.atl`,lX(u),`AU`],[`calc.tsb`,lX(l-u),`AU`]])}let f=new Set([...n.keys()]);for(let e of r)f.add(e);for(let e of f){let t=+!!n.has(e);c(`example-calc-adh-d${e}`,s(e,7),[[`calc.adherence`,t,`ratio`]])}for(let e of i)c(`example-calc-ef-d${e.day}`,s(e.day,8),[[`calc.ef`,lX(e.pace/141*1e5),`pts`]]);return t}function hX(e=Date.now()){return new Vg(O_(mX(e)))}var gX=null;function _X(){return gX??=hX()}var vX=[4,8,16],yX={parse(e){let t=Number.parseInt(e,10);return vX.includes(t)?t:null},serialize(e){return String(e)},withDefault(e){return{...this,defaultValue:e}}};function bX(){return Gt(`weeks`,yX.withDefault(16))}function xX(e){let t=e.trim().split(/\s+/).filter(e=>e!==``);if(t.length===0)return;let n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)continue;let r=e.slice(0,t),i=e.slice(t+1);i.startsWith(`"`)&&i.endsWith(`"`)&&i.length>=2&&(i=i.slice(1,-1)),n[r]=i}return Object.keys(n).length===0?void 0:n}var SX=[{label:`Auto`,spanCols:void 0,spanFull:!1},{label:`1 col`,spanCols:1,spanFull:!1},{label:`2 cols`,spanCols:2,spanFull:!1},{label:`4 cols`,spanCols:4,spanFull:!1},{label:`Full row`,spanCols:void 0,spanFull:!0}],CX=300;function wX({open:e,...t}){return e?(0,H.jsx)(TX,{...t}):null}function TX({onClose:e,mode:t,initialWql:n,initial:r,subsetQuery:i,destination:a,executor:o,rangeStart:s,rangeEnd:c,preferredUnit:l,tokenValues:u,onApply:d,footerExtra:f,applyLabel:p=t===`edit`?`Apply changes`:`Add widget`}){let m=t===`inspect`,[h,g]=(0,V.useState)(n),[_,v]=(0,V.useState)(r?.title??``),[y,b]=(0,V.useState)(r?.question??``),[x,S]=(0,V.useState)(r?.type||`table`),[C,w]=(0,V.useState)({spanCols:r?.spanCols,spanFull:r?.spanFull}),[T,E]=(0,V.useState)(Object.entries(r?.attributes??{}).map(([e,t])=>`${e}=${t}`).join(` `)),[D,O]=(0,V.useState)(!1),[k,A]=(0,V.useState)(()=>!Y(n).error),[j,M]=(0,V.useState)(null),N=(0,V.useMemo)(()=>Y(h.trim()),[h]),P=x===``?`table`:x,F=!N.error&&h.trim()!==``&&(tm(N)?P===`table`||P===`list`:P!==`list`),[I,ee]=(0,V.useState)({status:`idle`}),te=(0,V.useRef)(0);(0,V.useEffect)(()=>{if(!F||!o){ee(e=>e.status===`ok`?e:{status:`idle`});return}let e=t_(h.trim(),u??{});if(e.missing.length>0){ee({status:`blocked`,message:Kg(e.missing)});return}let t=++te.current;ee({status:`loading`});let n=setTimeout(()=>{o.runQuery(e.query,{rangeStart:s,rangeEnd:c,preferredUnit:l}).then(e=>{te.current===t&&ee({status:`ok`,result:e})}).catch(e=>{te.current===t&&ee({status:`error`,message:e instanceof Error?e.message:String(e)})})},CX);return()=>clearTimeout(n)},[h,F,o,s,c,l,u]);let ne=!F&&I.status===`ok`,re=F&&k,ie=async()=>{if(!(!re||!d||D)&&!(Y(h.trim()).error||h.trim()===``)){O(!0),M(null);try{await d({title:_.trim()||void 0,question:y.trim()||void 0,type:x===`table`?``:x,spanCols:C.spanFull?void 0:C.spanCols,spanFull:C.spanFull||void 0,wql:h.trim(),attributes:xX(T)}),e()}catch(e){M(e instanceof Error?e.message:String(e))}finally{O(!1)}}};return(0,H.jsx)(lS,{open:!0,onClose:e,presentation:`sheet`,title:t===`inspect`?`Inspect widget`:t===`edit`?`Edit widget`:`Add widget`,description:m?`Read-only — clone the dashboard to edit this widget.`:`Dataset, calculation, visualization, preview — then apply.`,footer:m&&!f?void 0:(0,H.jsxs)(H.Fragment,{children:[f,(0,H.jsx)(`div`,{className:`flex-1`}),!m&&(0,H.jsxs)(H.Fragment,{children:[(0,H.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,H.jsx)(`button`,{type:`button`,"data-testid":`widget-composer-apply`,disabled:!re||D,title:N.error?N.error:void 0,onClick:()=>void ie(),className:`min-h-12 px-3 py-1.5 text-xs font-medium text-primary-foreground bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg shadow transition-colors`,children:D?`Applying…`:p})]})]}),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[i!==void 0&&(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Dataset — the subset`}),i?(0,H.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-subset`,children:i}):(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`widget-composer-subset`,children:`No subset — the calculation runs over the whole store.`})]}),a,(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Calculation`}),m?(0,H.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-query`,children:h}):(0,H.jsx)(EC,{query:h,onQueryChange:g,onValidationChange:e=>A(e.valid),showDiagnostics:!0,...o?{execute:e=>o.runQuery(e.raw,{rangeStart:s,rangeEnd:c,preferredUnit:l})}:{}}),!m&&h.trim()!==``&&(0,H.jsx)(`code`,{className:`mt-1.5 block rounded-md border border-primary/30 bg-primary/[0.04] px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-wql`,children:h.trim()}),!m&&(0,H.jsxs)(`label`,{className:`mt-3 flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Visualization`}),(0,H.jsx)(`select`,{value:x,onChange:e=>S(e.target.value),"data-testid":`widget-composer-type`,className:`min-h-12 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary sm:min-h-0`,children:Hg.map(e=>(0,H.jsx)(`option`,{value:e,children:e},e))})]})]}),!m&&(0,H.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Title`}),(0,H.jsx)(`input`,{type:`text`,value:_,onChange:e=>v(e.target.value),placeholder:`Weekly volume`,"data-testid":`widget-composer-title`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,H.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Coaching question `,(0,H.jsx)(`span`,{className:`normal-case font-normal`,children:`(optional)`})]}),(0,H.jsx)(`input`,{type:`text`,value:y,onChange:e=>b(e.target.value),placeholder:`How much work per week?`,"data-testid":`widget-composer-question`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Size`}),(0,H.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1 self-start`,children:SX.map(e=>{let t=e.spanFull?C.spanFull===!0:e.spanCols==null?!C.spanFull&&C.spanCols==null:!C.spanFull&&C.spanCols===e.spanCols;return(0,H.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:()=>w(e.spanFull?{spanFull:!0}:{spanCols:e.spanCols}),className:`text-xs px-2.5 py-1 rounded-md transition-colors ${t?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.label},e.label)})})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1 sm:col-span-2`,children:[(0,H.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Parameters `,(0,H.jsx)(`span`,{className:`normal-case font-normal`,children:`(goal targets, space-separated)`})]}),(0,H.jsx)(`input`,{type:`text`,value:T,onChange:e=>E(e.target.value),placeholder:`300 200`,"data-testid":`widget-composer-params`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-mono text-foreground focus:outline-none focus:border-primary`})]})]}),m&&(0,H.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs text-muted-foreground`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Title`}),(0,H.jsx)(`div`,{className:`text-foreground`,children:r?.title||`—`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Question`}),(0,H.jsx)(`div`,{className:`text-foreground`,children:r?.question||`—`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Type`}),(0,H.jsx)(`div`,{className:`font-mono text-foreground`,children:x||`table`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Size`}),(0,H.jsx)(`div`,{className:`font-mono text-foreground`,children:r?.spanFull?`full row`:r?.spanCols?`${r.spanCols} cols`:`default`})]})]}),(0,H.jsxs)(`section`,{children:[(0,H.jsxs)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5 flex items-center gap-2`,children:[`Preview`,ne&&(0,H.jsx)(`span`,{"data-testid":`widget-preview-stale`,className:`font-medium normal-case tracking-normal text-amber-600`,children:`stale — showing the last valid query`})]}),(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-background/50 p-3 h-56 overflow-hidden`,children:[I.status===`idle`&&(F?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Preview runs as you compose…`}):(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:N.error?N.error:tm(N)?`find: queries return things — use a table or list widget instead`:`Compose a calculation to preview.`})),I.status===`loading`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Running preview…`}),I.status===`blocked`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`error`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`ok`&&(0,H.jsx)(ox,{type:x,result:I.result,label:_.trim()||void 0,unit:l,attributes:xX(T)})]})]}),j&&(0,H.jsx)(`p`,{role:`alert`,"data-testid":`widget-composer-error`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive font-mono`,children:j})]})})}function EX({boardSlug:e}){let t=_X(),n=sD(),r=(0,V.useMemo)(()=>n?Pj(n):[],[n]),i=(0,V.useMemo)(()=>r.find(t=>t.slug===e)??r[0],[r,e]),a=(0,V.useMemo)(()=>{if(!i?.rawContent)return null;try{let{meta:e,sections:t}=u_(i.rawContent);return i_(t,e)}catch{return null}},[i]),[o,s]=bX(),[c,l]=(0,V.useMemo)(()=>{let e=Date.now();return[e-o*7*864e5,e]},[o]),[u,d]=(0,V.useState)(null);return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col`,"data-testid":`tour-session-dashboard`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 px-5 pt-4`,children:[(0,H.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`truncate text-[11px] font-semibold uppercase tracking-wide text-primary`,children:i?.title??e}),(0,H.jsx)(`span`,{"data-testid":`tour-session-dashboard-source`,className:`flex-none rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground`,children:`Example data`})]}),(0,H.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,H.jsx)(Sx,{weeks:o,onWeeksChange:s})})]}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto px-5 pb-5 pt-3 [&_[data-testid=dashboard-view]>div.grid]:grid-cols-1 [&_[data-testid=dashboard-view]>div.grid]:sm:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid]:lg:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid>*]:col-span-1`,children:a?(0,H.jsx)(xx,{document:a,executor:t,onInspectWidget:d,rangeStart:c,rangeEnd:l}):(0,H.jsx)(`p`,{className:`pt-8 text-center text-sm text-muted-foreground`,children:`Loading board…`})}),(0,H.jsx)(wX,{open:u!==null,onClose:()=>d(null),mode:`inspect`,initialWql:u?.body??`sum:totalVolume{}`,initial:u?{title:u.title,question:u.question,type:u.type,spanCols:u.spanCols,spanFull:u.spanFull,attributes:u.attributes}:void 0,executor:t,rangeStart:c,rangeEnd:l,tokenValues:a?Qg(a.tokens):void 0,onApply:void 0})]})}function DX({session:e,onRun:t}){return(0,H.jsxs)(`section`,{id:`tour-section-insights`,"data-testid":`tour-section-insights`,className:`flex flex-col gap-4 border-b border-border/60 pb-12`,children:[(0,H.jsx)(UY,{index:`01`,before:`Your Session, `,accentText:`Analyzed`,after:``,accent:IY.analytics,blurb:`The run you just did is already data — time on countdown timers against time to the next click, and how fast you answered the clock. Nothing to fill in; it comes straight from the run.`}),(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[820px] px-5 2xl:max-w-[920px]`,children:(0,H.jsx)(CH,{title:`Session Insights`,className:`h-[460px]`,children:(0,H.jsx)(iX,{result:e,onRun:t})})})]})}var OX=[`road-to-560-total`,`polarized-base-marathon`];function kX(){return(0,H.jsxs)(`section`,{id:`tour-section-boards`,"data-testid":`tour-section-boards`,className:`flex flex-col gap-4 border-b border-border/60 pb-12`,children:[(0,H.jsx)(UY,{index:`02`,before:`One Run Becomes `,accentText:`Many`,after:``,accent:IY.analytics,blurb:`The same recorded facts roll up across workouts — tonnage toward a total, easy vs. hard work over weeks. These boards answer over example data; yours updates as you log.`}),(0,H.jsx)(`div`,{className:`grid gap-4 px-5 lg:grid-cols-2 2xl:gap-6`,children:OX.map(e=>(0,H.jsx)(CH,{title:`Example Board`,className:`h-[520px]`,children:(0,H.jsx)(EX,{boardSlug:e})},e))})]})}function AX(e){let[t,n]=(0,V.useState)(!1),[r,i]=(0,V.useState)({});(0,V.useEffect)(()=>{i(dH()),n(!0);let e=e=>{e.key===`wodwiki.quests.v1`&&i(dH())};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 jX({chapters:e,className:t}){let{chapters:n}=AX(e),r=n.find(e=>e.chapter.id===`home-tour`),i=r?.isComplete??!1,a=r?.completedCount??0,o=r?.totalCount??5;return(0,H.jsx)(`section`,{"data-testid":`celebration-bridge`,className:U(`py-12 px-4 sm:px-6 xl:py-20 2xl:py-24 border-b border-border/60 text-center`,t),children:(0,H.jsxs)(`div`,{className:`mx-auto max-w-2xl xl:max-w-3xl 2xl:max-w-4xl flex flex-col items-center gap-4 xl:gap-6`,children:[(0,H.jsx)(`div`,{"data-testid":`celebration-badge`,className:U(`inline-flex items-center gap-2 rounded-full px-3.5 py-1.5 font-mono text-[11px] font-bold transition-colors`,i?`border border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400`:`border border-border bg-muted/30 text-muted-foreground`),children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Zn,{className:`size-3.5 stroke-[2.5]`}),(0,H.jsx)(`span`,{children:`Take the Tour — complete ✓`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`size-2 rounded-full bg-primary`}),(0,H.jsxs)(`span`,{children:[`Take the Tour — `,a,`/`,o]})]})}),(0,H.jsx)(`h2`,{className:`text-2xl sm:text-3xl xl:text-4xl 2xl:text-5xl font-black tracking-tight text-foreground`,children:`You've seen how it works. Now master the syntax.`}),(0,H.jsxs)(`p`,{className:`text-[14px] sm:text-[15px] xl:text-base 2xl:text-lg leading-relaxed text-muted-foreground max-w-xl xl:max-w-2xl 2xl:max-w-3xl`,children:[`From your first `,(0,H.jsx)(`code`,{className:`font-mono text-[12px] bg-muted px-1.5 py-0.5 rounded text-foreground`,children:`wod`}),` block to a full training session: time-capped protocols like AMRAP and EMOM, repeating rounds and dash-format rep schemes (`,(0,H.jsx)(`code`,{className:`font-mono text-[12px] bg-muted px-1 py-0.5 rounded text-foreground`,children:`21-15-9`}),`), inline metrics for effort and heart rate, dialect fences for workout, log, plan, and climb notes — and complex workouts that chain it all into one session. Six chapters on the syntax, each with a runnable example and quests to earn. Keep scrolling to start.`]})]})})}var MX=`w-[290px] sm:w-[320px] md:w-[340px] shrink-0 snap-start flex flex-col justify-between rounded-xl border border-border bg-card p-5 text-left transition-colors hover:border-primary/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`;function NX(e){let t=e.icon;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,H.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),(0,H.jsx)(`h3`,{className:`mt-4 text-base font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.description})]}),e.note?(0,H.jsx)(`span`,{className:`mt-4 text-xs font-medium text-muted-foreground`,children:e.note}):(0,H.jsxs)(`span`,{className:`mt-4 inline-flex items-center gap-1.5 text-sm font-medium text-foreground`,children:[(0,H.jsx)(`span`,{children:e.action}),(0,H.jsx)(h,{className:`size-4 transition-transform group-hover:translate-x-0.5`,"aria-hidden":!0})]})]})}function PX(e){switch(e.phase){case`checking`:return`Checking source…`;case`fetching`:return`Downloading ${e.chunkId??`package`}…`;case`applying`:return`Importing ${e.chunkId??`package`}…`;case`committed`:return`Committed ${e.chunkId??`package`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??`Done`}}function FX(e){let{pkg:t,anyBusy:n,onBusyChange:r}=e,[i,a]=(0,V.useState)(()=>MO(t.id)),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null);(0,V.useEffect)(()=>(a(MO(t.id)),PO(()=>a(MO(t.id)))),[t.id]);let f=async()=>{s(!0),r(!0),d(null),l(`Checking source…`);try{let e=await Nk(t.id,{onProgress:e=>l(PX(e))});if(e===`imported`||e===`current`){let n=NO(t.id,!0);a(!0),l(n?e===`imported`?`Imported — package added to your library.`:`Already up to date.`:`Subscribed for this session only — browser storage is unavailable.`)}else l(null),d(e===`server-stale`?`Published version is older than stored copy.`:e===`busy`?`Another tab is syncing. Try again shortly.`:`Sync failed. Check connection and try again.`)}catch(e){l(null),d(e instanceof Error?e.message:String(e))}finally{s(!1),r(!1)}},p=async()=>{s(!0),r(!0),d(null),l(`Removing package…`);try{await Ik(t.id),a(!1),l(`Removed from library.`)}catch(e){d(e instanceof Error?e.message:`Failed to delete package`)}finally{s(!1),r(!1)}},m=()=>{i?p():f()},h=o||n;return(0,H.jsxs)(`article`,{className:MX,"data-testid":`demo-feed-${t.id}`,"aria-label":`${t.label} package`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`rounded-full border border-border bg-muted/60 px-2 py-0.5 font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground`,children:t.sourceLabel}),(0,H.jsx)(`span`,{className:`rounded-full border border-border/80 bg-accent/40 px-2 py-0.5 font-mono text-[10px] text-muted-foreground`,children:t.category}),t.category===`feeds`&&(0,H.jsx)(`span`,{className:`rounded-full border border-border px-2 py-0.5 font-mono text-[10px] text-muted-foreground`,children:`Demo`})]}),(0,H.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":i,"aria-label":`Toggle ${t.label} in library`,onClick:m,disabled:h,"data-testid":`demo-feed-toggle-${t.id}`,title:i?`Remove from library`:`Add to library`,className:`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:opacity-50 ${i?`bg-emerald-600`:`bg-muted-foreground/30`}`,children:(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-3.5 transform rounded-full bg-background shadow transition-transform ${i?`translate-x-4.5`:`translate-x-0.5`}`})})]}),(0,H.jsx)(`h3`,{className:`mt-3.5 text-base font-semibold text-foreground`,children:t.label}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground line-clamp-3`,children:t.description})]}),(0,H.jsxs)(`div`,{className:`mt-4 pt-2 border-t border-border/60`,children:[(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:i?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-medium text-emerald-600`,children:[(0,H.jsx)(yn,{className:`size-3.5`,"aria-hidden":!0}),`In library`]}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Not in library`})}),c&&(0,H.jsxs)(`p`,{role:`status`,"aria-live":`polite`,className:`mt-1.5 flex items-center gap-1.5 text-xs text-muted-foreground`,"data-testid":`demo-feed-progress-${t.id}`,children:[o&&(0,H.jsx)(pn,{className:`size-3 animate-spin motion-reduce:animate-none`,"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`truncate`,children:c})]}),u&&(0,H.jsxs)(`p`,{role:`alert`,className:`mt-1.5 flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`demo-feed-error-${t.id}`,children:[(0,H.jsx)(Kn,{className:`mt-0.5 size-3 shrink-0`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:u})]}),(0,H.jsx)(`div`,{className:`mt-3 flex items-center gap-2`,children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{f()},disabled:h,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted disabled:opacity-50`,"data-testid":`demo-feed-sync-${t.id}`,children:[(0,H.jsx)(pn,{className:`size-3 ${o?`animate-spin motion-reduce:animate-none`:``}`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:o?`Syncing…`:`Sync now`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{p()},disabled:h,className:`inline-flex items-center gap-1 rounded-md border border-destructive/20 px-2 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40`,"data-testid":`demo-feed-unsubscribe-${t.id}`,title:`Remove package from library`,children:[(0,H.jsx)(j,{className:`size-3`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:`Delete`})]})]}):(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{f()},disabled:h,className:`inline-flex items-center gap-1.5 rounded-md bg-foreground px-2.5 py-1 text-xs font-medium text-background transition-colors hover:opacity-90 disabled:opacity-50`,"data-testid":`demo-feed-subscribe-${t.id}`,children:[(0,H.jsx)(pn,{className:`size-3 ${o?`animate-spin motion-reduce:animate-none`:``}`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:o?`Syncing…`:`Subscribe & sync`})]})})]})]})}function IX(){let e=Sn(),[t,n]=(0,V.useState)(``),[r,i]=(0,V.useState)(!1),a=(0,V.useRef)(null),o=(0,V.useMemo)(()=>yO(),[]),s=(0,V.useMemo)(()=>{let e=t.trim().toLowerCase();return e?o.filter(t=>t.label.toLowerCase().includes(e)||t.category.toLowerCase().includes(e)||t.sourceLabel.toLowerCase().includes(e)||t.description.toLowerCase().includes(e)):o},[o,t]),c=e=>{if(!a.current)return;let t=a.current.clientWidth*.75;a.current.scrollBy({left:e===`left`?-t:t,behavior:`smooth`})},l=(0,V.useCallback)(()=>{YV.record(XV.libraryOpened)},[]),[u,d]=(0,V.useState)(!0);(0,V.useEffect)(()=>{let e=!1,t=()=>{Lk().then(t=>{e||d(t.libraryImported)}).catch(()=>{})};t();let n=PO(t);return()=>{e=!0,n()}},[r]);let f=(0,V.useCallback)(async()=>{let t=Vj(),n=await Kj.create({journalDate:t,title:t,rawContent:``});YV.record(XV.noteCreated),e(qA(n.id))},[e]);return(0,H.jsxs)(`section`,{id:`tour-section-community-feeds`,"data-testid":`tour-jump-section`,className:`flex flex-col border-b border-border bg-muted/20 pb-8 xl:pb-12`,"aria-label":`Library and community feeds`,children:[(0,H.jsx)(UY,{index:`00`,before:`Library & `,accentText:`Community Feeds`,after:``,accent:``,blurb:`Subscribe to Markdown repositories and sync while you keep scrolling. Publishers run npx wod build to compile manifests and chunks, then deploy them through GitHub Pages. CrossFit Programming and Dan John 40-Day Program are demo feeds; other packages and workspace shortcuts are available here too.`}),(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-6xl px-4 sm:px-6`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[(0,H.jsxs)(`div`,{className:`relative w-full sm:w-64`,children:[(0,H.jsx)(Xn,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground`,"aria-hidden":!0}),(0,H.jsx)(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Filter packages…`,"data-testid":`package-search-input`,className:`w-full rounded-md border border-border bg-background py-1.5 pl-8 pr-7 text-xs text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`}),t&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(``),"aria-label":`Clear search`,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3.5`})})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(`left`),"aria-label":`Previous cards`,className:`flex size-7 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Tt,{className:`size-4`})}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(`right`),"aria-label":`Next cards`,className:`flex size-7 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Vn,{className:`size-4`})})]})]}),(0,H.jsxs)(`div`,{ref:a,"data-testid":`jump-carousel-track`,className:`mt-6 flex w-full gap-4 overflow-x-auto pb-4 pt-1 snap-x snap-mandatory scroll-smooth`,style:{scrollbarWidth:`thin`},children:[u?(0,H.jsx)(Wn,{to:`/catalogs`,onClick:l,"data-testid":`jump-library`,className:`group ${MX}`,children:(0,H.jsx)(NX,{icon:an,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`})}):(0,H.jsx)(`div`,{"data-testid":`jump-library`,"aria-disabled":`true`,className:`${MX} cursor-not-allowed opacity-60`,children:(0,H.jsx)(NX,{icon:an,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`,note:`0 feeds synchronized`})}),(0,H.jsx)(`button`,{type:`button`,onClick:f,"data-testid":`jump-new-note`,className:`group ${MX}`,children:(0,H.jsx)(NX,{icon:Ut,title:`Start your own journal`,description:`Create today's note and log your first workout.`,action:`Create today's note`})}),s.map(e=>(0,H.jsx)(FX,{pkg:e,anyBusy:r,onBusyChange:i},e.id)),s.length===0&&t&&(0,H.jsxs)(`div`,{className:`flex w-64 shrink-0 flex-col items-center justify-center rounded-xl border border-dashed border-border p-6 text-center text-xs text-muted-foreground`,children:[(0,H.jsxs)(`p`,{children:[`No packages match “`,t,`”.`]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(``),className:`mt-2 font-medium text-foreground underline underline-offset-4`,children:`Clear filter`})]})]}),(0,H.jsx)(`p`,{className:`mt-2 font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:`— or keep scrolling ↓`})]})]})}var LX=`wods/examples/home/welcome-1.md`;function RX({wodFiles:e,theme:t,quests:n,chapters:r}){let i=bH(`(prefers-reduced-motion: reduce)`),a=ZV()?.track;$V(`/`);let o=(0,V.useMemo)(()=>BL(LX,e),[e]),[s,c]=(0,V.useState)(()=>CY()),l=s?.content??o,u=s?s.by?.trim()||`anonymous`:void 0;(0,V.useEffect)(()=>{let e=e=>{let t=e.detail;t?.content&&(c(t),f(t.content))};return window.addEventListener(`wodwiki:home-shared`,e),()=>window.removeEventListener(`wodwiki:home-shared`,e)},[]);let[d,f]=(0,V.useState)(l),p=(0,V.useRef)(d);p.current=d;let m=(0,V.useRef)([]),h=(0,V.useRef)(!1),{run:g,start:_,finalize:v,end:y}=sH(),b=(0,V.useRef)(g);b.current=g;let x=(0,V.useRef)(!1),S=(0,V.useRef)(!1),C=(0,V.useRef)(null),[w,T]=(0,V.useState)(!1),E=(0,V.useRef)(!1),D=(0,V.useRef)(null),[O,k]=(0,V.useState)(null),[A,j]=(0,V.useState)(null),[M,N]=(0,V.useState)(null),P=M===`hero`,[F,I]=(0,V.useState)(!1),ee=(0,V.useRef)(!1),te=(0,V.useRef)(()=>{}),[ne,re]=(0,V.useState)(0),[ie,ae]=(0,V.useState)(!1),oe=(0,V.useCallback)(()=>{k(null),N(null),I(!1),le(null)},[]),[se,ce]=(0,V.useState)(!1),[L,le]=(0,V.useState)(null),ue=(0,V.useCallback)(async(e,t,n,r)=>{if(!t||ee.current)return!1;ee.current=!0,S.current=!1,x.current=!1,C.current=null,le(t),re(e=>e+1),ae(!0),k(null),j(null),N(r),I(!0);try{await _(e,t,{pageTitle:`Home`,sectionTitle:n})}catch(e){return console.error(`[HomeTour] failed to persist playground run note:`,e),I(!1),le(null),Z({title:`Could not start workout`,description:`The playground entry could not be saved.`,variant:`destructive`}),!1}finally{ee.current=!1}return!0},[_]),R=(0,V.useCallback)(async()=>{if(E.current=!1,T(!1),C.current)try{await v(C.current,!1),C.current=null}catch(e){console.error(`[HomeTour] retry save failed:`,e),Z({title:`Session still not saved`,description:`The run is kept — try again.`,variant:`destructive`});return}let e=D.current;if(D.current=null,e)switch(e.kind){case`apply-doc`:h.current=!1,f(e.doc),oe(),re(e=>e+1),ae(!1);break;case`restart`:await ue(e.doc,e.block,e.sectionTitle,e.location)}},[ue,oe,v]),de=(0,V.useCallback)(e=>{if(!D.current){if(!b.current||S.current||!x.current||C.current){D.current=e,R();return}D.current=e,E.current=!0,T(!0)}},[R]),fe=(0,V.useRef)(null),pe=(0,V.useRef)(null);DK(`hero`,pe);let me=(0,V.useRef)(!0),he=(0,V.useRef)(P);he.current=P;let ge=(0,V.useCallback)(()=>{he.current||de({kind:`apply-doc`,doc:l})},[l,de]);(0,V.useEffect)(()=>{let e=fe.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{let t=e.isIntersecting;t&&!me.current&&ge(),me.current=t});return t.observe(e),()=>t.disconnect()},[ge]);let _e=(0,V.useCallback)(()=>{wY(),c(null),de({kind:`apply-doc`,doc:o})},[o,de]);yH({pageRoute:`/`,quests:n,initialSource:l,currentSource:d}),vH({pageRoute:`/`,quests:n,completedResults:O}),te.current=OY(`/`,n),TY({pageRoute:`/`,quests:n,running:se}),(0,V.useEffect)(()=>{let e=document.getElementById(`tour-section-insights`);if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&te.current?.(`session-insights`)});return t.observe(e),()=>t.disconnect()},[]);let ve=(0,V.useCallback)(e=>{f(e),e!==l&&!h.current&&(h.current=!0,a?.(XV.demoEdited))},[l,a]),ye=(0,V.useCallback)(e=>{m.current=e},[]),be=(0,V.useCallback)((e,t,n,r,i)=>{if(n){if(a?.(XV.demoRun),r&&ce(!0),le(n),N(i),I(!0),ae(!0),re(e=>e+1),k(null),ee.current||D.current){D.current={kind:`restart`,doc:t,block:n,sectionTitle:e,location:i};return}if(b.current&&x.current&&!S.current){D.current={kind:`restart`,doc:t,block:n,sectionTitle:e,location:i},E.current=!0,T(!0);return}if(b.current&&!S.current){y().then(()=>ue(t,n,e,i));return}ue(t,n,e,i)}},[ue,y,a]),xe=(0,V.useCallback)(()=>{be(`Run`,p.current,m.current[0],!0,`hero`)},[be]),Se=(0,V.useCallback)(()=>{be(`Run`,p.current,m.current[0],!0,`cta`)},[be]),{setL3Items:Ce}=hA();(0,V.useEffect)(()=>(Ce([{id:`tour-hero`,label:`Welcome`,level:3,action:{type:`scroll`,sectionId:`tour-hero`}},{id:`insights`,label:`Your Session, Analyzed`,level:3,action:{type:`scroll`,sectionId:`tour-section-insights`},secondaryAction:{id:`run-start`,label:`Run the workout`,action:{type:`call`,handler:Se}}},{id:`boards`,label:`One Run Becomes Many`,level:3,action:{type:`scroll`,sectionId:`tour-section-boards`}},{id:`community-feeds`,label:`Library & Community Feeds`,level:3,action:{type:`scroll`,sectionId:`tour-section-community-feeds`}},{id:`offerings`,label:`You Own the Data`,level:3,action:{type:`scroll`,sectionId:`tour-section-offerings`}},{id:`hosted`,label:`Wod-Wiki Hosted`,level:3,action:{type:`scroll`,sectionId:`tour-section-hosted`}}]),()=>Ce([])),[Ce,Se]);let we=(0,V.useCallback)((e,t)=>{if(!(S.current&&!C.current))return k(t),(t.logs??[]).length===0?(S.current=!0,j(t),I(!1),R()):(S.current=!0,v(t,t.completed).then(()=>(C.current=null,j(t),I(!1),R())).catch(e=>{throw S.current=!1,x.current=!1,C.current=t,E.current=!1,T(!1),D.current=null,Z({title:`Session not saved`,description:`The run could not be recorded. Nothing was lost — your next action retries the save.`,variant:`destructive`}),e}))},[v,R]),Te=(0,V.useCallback)(()=>{I(!1)},[]),Ee=(0,V.useRef)(null),De=(0,V.useCallback)(e=>{Ee.current=e},[]),Oe=(0,V.useCallback)(()=>{x.current=!0;let e=Ee.current;ie&&e&&e.handle(new mf(void 0,e.nowProvider)),ae(!1)},[ie]),ke=(0,V.useRef)(!1),Ae=(0,V.useCallback)(()=>{if(ke.current){oe();return}let e=fe.current,t=document.querySelector(`[data-gate-id="hero-pane"]`);if(!e||!t){oe();return}let n=e.getBoundingClientRect().top+window.scrollY,r=t.getBoundingClientRect().top+window.scrollY,a=Math.max(0,r-n);if(typeof requestAnimationFrame!=`function`){oe();return}ke.current=!0,window.scrollTo({top:a,behavior:i?`auto`:`smooth`});let o=performance.now(),s=()=>{if(Math.abs(window.scrollY-a)<=2||performance.now()-o>1200){ke.current=!1,oe();return}requestAnimationFrame(s)};requestAnimationFrame(s)},[oe,i]),je=P&&O?`result`:`editor`,Me=(0,V.useRef)(`editor`);(0,V.useEffect)(()=>{let e=Me.current;if(Me.current=je,je===e)return;let t=()=>{let e=fe.current,t=document.querySelector(`[data-gate-id="hero-pane"]`);if(!e||!t)return null;let n=e.getBoundingClientRect().top+window.scrollY,r=t.getBoundingClientRect().top+window.scrollY;return Math.max(0,r-n)};if(je===`result`){let e=t();if(e==null)return;window.scrollTo({top:e,behavior:i?`auto`:`smooth`})}let n=[150,450].map(e=>setTimeout(()=>{let e=t();e!=null&&Math.abs(window.scrollY-e)>2&&window.scrollTo({top:e,behavior:`auto`})},e));return()=>n.forEach(clearTimeout)},[je,i]);let Ne=g?.block??L,Pe=F&&Ne&&(0,H.jsx)(BG,{block:Ne,autoStart:ie,externalStop:w,onRunStarted:Oe,onRuntimeReady:De,onClose:Te,onCompleteWorkout:we},ne),Fe=(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(ZY,{}),(0,H.jsxs)(`p`,{className:`-mt-8 text-center font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:[`— or learn the language with examples`,` `,(0,H.jsx)(Wn,{to:`/syntax`,className:`text-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:`on the syntax page →`})]})]});return i?(0,H.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,H.jsxs)(`section`,{id:`tour-hero`,"data-testid":`tour-hero`,className:`grid h-[calc(100dvh-65px)] grid-rows-[2fr_3fr] gap-4 px-6 py-4 lg:h-[calc(100dvh-104px)]`,children:[(0,H.jsx)(`div`,{className:`flex min-h-0 items-center justify-center overflow-y-auto`,children:(0,H.jsx)(zY,{})}),(0,H.jsxs)(`div`,{className:`relative min-h-0 overflow-hidden rounded-xl border border-border`,children:[u&&(0,H.jsx)(`button`,{type:`button`,onClick:_e,"data-testid":`tour-hero-reset-shared`,className:`absolute right-3 top-3 z-10 rounded-md border border-border bg-background px-3 py-2 text-xs hover:bg-accent`,children:`Reset`}),je===`result`&&O?(0,H.jsx)(eX,{result:O,onDismiss:Ae,dismissLabel:`Edit again`}):(0,H.jsx)(QY,{doc:d,theme:t,onDocChange:ve,onBlocksChange:ye,onRun:xe})]})]}),(0,H.jsx)(DX,{session:A,onRun:Se}),(0,H.jsx)(kX,{}),(0,H.jsx)(jX,{chapters:r}),(0,H.jsx)(IX,{}),Fe,(0,H.jsx)(Pq,{}),(0,H.jsx)(VY,{}),Pe]}):(0,H.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,H.jsx)(`div`,{ref:fe,"aria-hidden":!0,className:`h-px`}),(0,H.jsxs)(`section`,{ref:pe,id:`tour-hero`,"data-testid":`tour-hero`,className:`relative flex min-h-[calc(100dvh-65px)] flex-col items-center gap-4 px-5 py-4 text-center lg:min-h-[calc(100dvh-104px)] lg:px-10 xl:gap-8 xl:py-8 2xl:gap-10 2xl:py-10 2xl:px-16`,children:[(0,H.jsx)(`div`,{className:`flex w-full shrink grow-[2] basis-0 items-center justify-center`,children:(0,H.jsx)(zY,{})}),(0,H.jsx)(OK,{gateId:`hero-pane`,segmentId:`hero`,className:U(`w-full max-w-[720px] grow-[3] basis-0 xl:max-w-[820px] 2xl:max-w-[920px]`,je===`result`&&`[&>div:first-child]:min-h-fit`),children:(0,H.jsxs)(CH,{title:je===`result`?LY.metrics:u?u.toLowerCase().startsWith(`shared by`)?u:`shared by: ${u}`:`welcome-1.md`,headerActions:u&&(0,H.jsx)(`button`,{type:`button`,onClick:_e,title:`Reset`,className:`rounded-md border border-border px-2 py-1 text-[10px] transition-colors hover:bg-accent`,"data-testid":`tour-hero-reset-shared`,children:`Reset`}),className:je===`result`?`h-full min-h-fit [&>div:last-child]:min-h-fit`:`h-full`,children:[je===`editor`&&(0,H.jsx)(QY,{doc:d,theme:t,onDocChange:ve,onBlocksChange:ye,onRun:xe}),je===`result`&&O&&(0,H.jsx)(eX,{result:O,onDismiss:Ae,dismissLabel:`Edit again`})]})})]}),(0,H.jsx)(DX,{session:A,onRun:Se}),(0,H.jsx)(kX,{}),(0,H.jsx)(jX,{chapters:r}),(0,H.jsx)(IX,{}),Fe,(0,H.jsx)(Pq,{}),(0,H.jsx)(VY,{}),Pe]})}function zX(e){return(0,H.jsx)(AY,{children:(0,H.jsx)(EK,{children:(0,H.jsx)(RX,{...e})})})}function BX({wodFiles:e,theme:t}){let n=MP(`/`);return n?(0,H.jsx)(zX,{wodFiles:e,theme:t,quests:n.quests??[],chapters:n.chapters??[]}):(0,H.jsx)(`div`,{className:`flex items-center justify-center p-20 text-muted-foreground`,children:`Home canvas content not found (markdown/canvas/routes/home.md)`})}var VX=`idle`,HX=new Set,UX=null,WX=null;function GX(){for(let e of HX)e()}function KX(e){typeof document>`u`||(document.documentElement.dataset.seedState=e)}function qX(e){typeof document>`u`||(e===null?delete document.documentElement.dataset.seedOutcome:document.documentElement.dataset.seedOutcome=e)}KX(VX);function JX(e){VX!==e&&(VX=e,KX(e),GX())}function YX(){UX&&=(clearTimeout(UX),null),WX&&=(WX.close(),null)}function XX(){YX(),qX(null),JX(`preparing`)}function ZX(e){switch(qX(e),e){case`busy`:if(VX!==`preparing`)return;typeof BroadcastChannel<`u`&&!WX&&(WX=new BroadcastChannel(z_),WX.onmessage=e=>{e.data?.kind===`seed-imported`&&(YX(),JX(`ready`))}),UX=setTimeout(()=>{jk().then(ZX)},pk);break;case`error`:YX(),JX(`error`);break;default:YX(),JX(`ready`)}}function QX(){return VX===`idle`?`ready`:VX}function $X(e){return HX.add(e),()=>HX.delete(e)}function eZ(){return(0,V.useSyncExternalStore)($X,QX)}var tZ=null;function nZ(e={}){return tZ??=rZ(e),tZ}async function rZ(e){let t=e.sources??hk();await RO(t,e.storage).catch(e=>console.error(`[seedSync] subscription migration failed`,e));let n=e.storage??new SO,r;try{r=await n.getSeedMeta(V_(`core`))}catch{r=void 0}if(!r||r.seedVersion<=0){XX(),ZX(await jk({...e,sources:t,onFirstPaint:()=>ZX(`imported`)})),t.some(e=>e.id!==`core`&&MO(e.id))&&await jk({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e));return}ZX(`current`),await jk({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e))}function iZ(){let[e,t]=(0,V.useState)(null);return(0,V.useEffect)(()=>{let e=!1,n=()=>{Lk().then(n=>{e||t(!n.libraryImported)}).catch(()=>{e||t(!0)})};n();let r=hb(()=>n()),i=Ck(()=>n()),a=null;if(typeof BroadcastChannel<`u`)try{a=new BroadcastChannel(z_),a.onmessage=()=>n()}catch{}return()=>{e=!0,r(),i(),a?.close()}},[]),e}var aZ=UO.ICONS,oZ=({open:e,onOpenChange:t,onCreate:n})=>{let[r,i]=(0,V.useState)(``),[a,o]=(0,V.useState)(``),[s,c]=(0,V.useState)(`📓`),[l,u]=(0,V.useState)(!1),d=async()=>{if(!(!r.trim()||l)){u(!0);try{if(!await n(r.trim(),a.trim(),s))return;i(``),o(``),c(`📓`),t(!1)}finally{u(!1)}}};return(0,H.jsx)(MB,{open:e,onOpenChange:t,children:(0,H.jsxs)(NB,{className:`bg-popover text-popover-foreground border border-border`,children:[(0,H.jsxs)(PB,{children:[(0,H.jsx)(FB,{className:`text-foreground`,children:`Create Notebook`}),(0,H.jsx)(IB,{children:`Organize your sessions into collections.`})]}),(0,H.jsxs)(`div`,{className:`space-y-4 mt-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{className:`text-sm font-medium text-foreground/80 mb-2 block`,children:`Icon`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:aZ.map(e=>(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(e),className:U(`w-9 h-9 rounded-md flex items-center justify-center text-lg transition-all`,`hover:bg-accent hover:scale-110`,s===e?`bg-primary/20 ring-2 ring-primary scale-110`:`bg-muted/50`),children:e},e))})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Name `,(0,H.jsx)(`span`,{className:`text-destructive`,children:`*`})]}),(0,H.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&r.trim()&&(e.preventDefault(),d())},placeholder:`e.g., Morning Routines`,autoFocus:!0,className:U(`w-full px-3 py-2 rounded-md text-sm`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Description `,(0,H.jsx)(`span`,{className:`text-muted-foreground text-xs`,children:`(optional)`})]}),(0,H.jsx)(`textarea`,{value:a,onChange:e=>o(e.target.value),placeholder:`A brief description of this notebook...`,rows:2,className:U(`w-full px-3 py-2 rounded-md text-sm resize-none`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,H.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>t(!1),children:`Cancel`}),(0,H.jsx)(W,{variant:`default`,size:`sm`,onClick:()=>void d(),disabled:!r.trim()||l,children:l?`Creating…`:`Create`})]})]})]})})};function sZ({value:e,max:t,label:n,className:r}){let i=Math.max(1,t),a=Math.min(Math.max(e,0),i),o=Math.round(a/i*100),s=(0,V.useRef)(a),[c,l]=(0,V.useState)(!1);return(0,V.useEffect)(()=>{if(a>s.current){l(!0);let e=setTimeout(()=>l(!1),200);return s.current=a,()=>clearTimeout(e)}s.current=a},[a]),(0,H.jsxs)(`div`,{className:U(`w-full`,r),children:[n?(0,H.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.14em] text-brand-deep dark:text-brand-light`,children:[(0,H.jsx)(`span`,{children:n}),(0,H.jsxs)(`span`,{className:`tabular-nums text-muted-foreground`,children:[a,`/`,i]})]}):null,(0,H.jsx)(`div`,{role:`progressbar`,"aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":i,"aria-label":n??`Progress`,className:`h-2 w-full overflow-hidden rounded-pill bg-brand/10`,children:(0,H.jsx)(`div`,{className:U(`h-full rounded-pill transition-[width] duration-500 ease-out`,c?`bg-brand-deep`:`bg-brand`),style:{width:`${o}%`}})})]})}function cZ(e,t,n){UR.getState().open({placeholder:`Craft the query…`,wql:{initialQuery:e,execute:t,onApply:n},sources:[Mz()]})}function lZ({query:e,onQueryChange:t,scopeOptions:n,execute:r,defaultQuery:i,compact:a=!1,className:o}){let s=(0,V.useCallback)(()=>cZ(e,r,t),[e,r,t]);return a?(0,H.jsx)(`div`,{"data-testid":`stream-query-bar-dock`,className:U(`flex min-h-12 w-full items-stretch overflow-hidden rounded-xl border border-border bg-muted/40 shadow-xs`,o),children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`stream-query-bar`,onClick:s,className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 px-3 text-left transition-colors hover:bg-muted/70`,children:[(0,H.jsx)(Xn,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{"data-testid":`stream-query-summary`,className:`min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground`,children:e||i||`Filter or search…`}),(0,H.jsx)(wn,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`})]})}):(0,H.jsx)(`div`,{"data-testid":`stream-query-bar`,className:U(`flex min-w-0 flex-1 items-center gap-1 text-xs`,o),children:(0,H.jsx)(EC,{query:e,onQueryChange:t,compact:!0,showDiagnostics:!1,preferredChoices:n,placeholder:`Filter or search…`,className:`min-w-0 flex-1`})})}function uZ(e,t){let n=t??Y(e);return n.error?null:n.groupBy?.length?n.groupBy.map(e=>String(e).toLowerCase()):null}function dZ(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)||`default`}function fZ(e,t=`date`,n){let r=(Array.isArray(t)?t:[t]).map(e=>String(e).toLowerCase()).filter(Boolean);r.length===0&&r.push(`date`);let i=(e,t)=>{let r=pZ(e,t[0],n);return t.length===1?r:r.flatMap(e=>e.key===`shelf`?[e]:i(e.entries,t.slice(1)).map(t=>({...t,key:`${e.key}/${t.key}`,id:`${e.id}--${t.id}`,label:`${e.label} / ${t.label}`,isToday:e.isToday||t.isToday})))};return i(e,r)}function pZ(e,t,n){let r=t.toLowerCase(),i=_z();if(r===`date`||r===`day`){let t=new Map,r=[],a=[];for(let i of e){let e=i.date??(i.sourceCatalog===`playground`&&i.createdAt&&i.createdAt>9466848e5?new Date(i.createdAt).toISOString().slice(0,10):null);if(n?.shelfVisible&&(i.kind===`session`||e==null))r.push(i);else if(e){let n=t.get(e);n?n.push(i):t.set(e,[i])}else a.push(i)}let o=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)),s=[];n?.shelfVisible&&r.length>0&&s.push({id:`group-shelf`,key:`shelf`,label:`Catalog Sessions`,entries:r});for(let e of o)s.push({id:`date-group-${e}`,key:e,label:e===i?`Today`:vz(e),isToday:e===i,entries:t.get(e)??[]});return a.length>0&&s.push({id:`group-date-undated`,key:`undated`,label:`Undated`,entries:a}),s}if(r===`week`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let[e,i,a]=r.date.split(`-`).map(Number),o=new Date(Date.UTC(e,i-1,a)),s=o.getUTCDay(),c=o.getUTCDate()-s+(s===0?-6:1),l=new Date(Date.UTC(e,i-1,c)),u=l.toISOString().slice(0,10),d=`Week of ${l.toLocaleDateString(`en`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`})}`,f=t.get(u);f?f.entries.push(r):t.set(u,{label:d,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-week-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-week-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`month`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,7),[i,a]=e.split(`-`).map(Number),o=new Date(Date.UTC(i,a-1,1)).toLocaleDateString(`en`,{month:`long`,year:`numeric`,timeZone:`UTC`}),s=t.get(e);s?s.entries.push(r):t.set(e,{label:o,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-month-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-month-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`year`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,4),i=t.get(e);i?i.push(r):t.set(e,[r])}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-year-${e}`,key:e,label:e,entries:t.get(e)??[]}));return n.length>0&&r.push({id:`group-year-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`discipline`){let t=new Map;for(let n of e){let e=n.effort?.discipline||n.tags?.find(e=>[`strength`,`gymnastics`,`cardio`,`running`,`rowing`,`weightlifting`,`olympic-weightlifting`].includes(e.toLowerCase()))||`General`,r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=t.get(r);i?i.push(n):t.set(r,[n])}let n=[`Strength`,`Gymnastics`,`Cardio`,`Running`,`Rowing`,`Weightlifting`];return Array.from(t.keys()).sort((e,t)=>{let r=n.indexOf(e),i=n.indexOf(t);return r!==-1&&i!==-1?r-i:r===-1?i===-1?e.localeCompare(t):1:-1}).map(e=>({id:`group-discipline-${dZ(e)}`,key:e,label:e,entries:t.get(e)??[]}))}if(r===`origin`){let t=new Map;for(let n of e){let e=n.effort?.registrySource===`bundled`?`Bundled Standards`:`Custom Movements`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-origin-${dZ(e)}`,key:e,label:e,entries:t}))}if(r===`source`||r===`notebook`){let t=new Map;for(let n of e){let e=n.sourceCatalog||`Other`,r=e.charAt(0).toUpperCase()+e.slice(1),i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t.entries()).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({id:`group-source-${dZ(e)}`,key:e,label:e,entries:t}))}if(r===`kind`||r===`type`){let t=new Map;for(let n of e){let e=n.kind.charAt(0).toUpperCase()+n.kind.slice(1)+`s`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-kind-${dZ(e)}`,key:e,label:e,entries:t}))}if(!Dp.includes(r)){let t=new Map;for(let n of e){let e=n.typedTags?.find(e=>e.type?.toLowerCase()===r)?.label??`Unassigned`,i=t.get(e);i?i.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-property-${dZ(r)}-${dZ(e)}`,key:e,label:e,entries:t}))}let a=new Map;for(let t of e){let e=t.tags?.[0]?`#${t.tags[0]}`:`Untagged`,n=a.get(e);n?n.push(t):a.set(e,[t])}return Array.from(a.entries()).map(([e,t])=>({id:`group-tag-${dZ(e)}`,key:e,label:e,entries:t}))}var mZ=pt,hZ=Jn,gZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(sn,{ref:n,className:U(`fixed inset-0 z-50 bg-black/80 dark:bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t}));gZ.displayName=sn.displayName;var _Z=V.forwardRef(({className:e,children:t,...n},r)=>(0,H.jsxs)(hZ,{children:[(0,H.jsx)(gZ,{}),(0,H.jsxs)(Rn,{ref:r,className:U(`fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg`,e),...n,children:[t,(0,H.jsxs)(xn,{className:`absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground`,children:[(0,H.jsx)(Te,{className:`h-4 w-4`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]}));_Z.displayName=Rn.displayName;var vZ=({className:e,...t})=>(0,H.jsx)(`div`,{className:U(`flex flex-col space-y-1.5 text-center sm:text-left`,e),...t});vZ.displayName=`DialogHeader`;var yZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(Dt,{ref:n,className:U(`text-lg font-semibold leading-none tracking-tight`,e),...t}));yZ.displayName=Dt.displayName;var bZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(St,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t}));bZ.displayName=St.displayName;var xZ=[`date`,`datetime-local`,`month`,`time`,`week`],SZ=(0,V.forwardRef)(function({className:e,...t},n){return(0,H.jsx)(`span`,{"data-slot":`control`,className:U(`relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`sm:focus-within:after:ring-2 sm:focus-within:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:(0,H.jsx)(de,{ref:n,...t,className:U(t.type&&xZ.includes(t.type)&&[`[&::-webkit-datetime-edit-fields-wrapper]:p-0`,`[&::-webkit-date-and-time-value]:min-h-[1.5em]`,`[&::-webkit-datetime-edit]:inline-flex`,`[&::-webkit-datetime-edit]:p-0`,`[&::-webkit-datetime-edit-year-field]:p-0`,`[&::-webkit-datetime-edit-month-field]:p-0`,`[&::-webkit-datetime-edit-day-field]:p-0`,`[&::-webkit-datetime-edit-hour-field]:p-0`,`[&::-webkit-datetime-edit-minute-field]:p-0`,`[&::-webkit-datetime-edit-second-field]:p-0`,`[&::-webkit-datetime-edit-millisecond-field]:p-0`,`[&::-webkit-datetime-edit-meridiem-field]:p-0`],`relative block w-full appearance-none rounded-lg px-[calc(theme(spacing.3.5)-1px)] py-[calc(theme(spacing.2.5)-1px)]`,`sm:px-[calc(theme(spacing.3)-1px)] sm:py-[calc(theme(spacing.1.5)-1px)]`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6`,`border border-border/60 hover:border-border data-[hover]:border-border`,`bg-transparent dark:bg-white/5`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 dark:data-[disabled]:border-border/30 dark:data-[disabled]:bg-white/2.5`,`dark:scheme-dark`,e)})})}),CZ=e=>WP(new Date(e)),wZ=e=>{if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`};function TZ(e,t){Z(e===`imported`?{title:`${t} synced`,description:`Content was imported from the published seed. Your own edits were kept.`}:e===`error`?{title:`${t} sync failed`,description:`Check your connection and the browser console for details.`,variant:`destructive`}:e===`busy`?{title:`Another tab is already syncing`,description:`Wait for it to finish, then try again.`}:{title:`${t}: nothing to import (${e})`})}var EZ={imported:`Synced`,current:`Up to date`,"server-stale":`Published version is older than the stored version`,"update-pending":`Update available`,busy:`Another tab is syncing`,disabled:`Seed import is disabled`,error:`Sync failed`};function DZ(e){switch(e.phase){case`checking`:return`Checking source…`;case`fetching`:return`Downloading ${e.chunkId}…`;case`applying`:return`Importing ${e.chunkId}…`;case`committed`:return`Committed ${e.chunkId}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??EZ[e.outcome]}}function OZ({source:e,running:t,disabled:n,onSync:r,onSubscribe:i,onUnsubscribe:a,onDelete:o,onAutoSync:s}){let c=(0,V.useSyncExternalStore)(PO,()=>IO(e.id)),l=e.autoImport,u=e.subscribed&&!e.upToDate&&e.remote!==null;return(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-source-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0 flex-wrap`,children:[(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground truncate`,children:e.label}),(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0 ${e.subscribed?`bg-emerald-500/10 text-emerald-600`:`bg-muted text-muted-foreground`}`,children:e.subscribed?`Subscribed`:`Not subscribed`}),l&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0`,children:`Core`})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0 flex-wrap justify-end`,children:[e.subscribed?u?(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>r(e.id),disabled:n,"data-testid":`seed-sync-${e.id}`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${t?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:t?`Syncing…`:`Sync`})]}):(0,H.jsxs)(`span`,{className:`text-xs text-muted-foreground flex items-center gap-1.5`,"data-testid":`seed-current-${e.id}`,children:[(0,H.jsx)(yn,{className:`size-3.5 text-emerald-500`}),e.remote===null?`Remote unreachable`:`Up to date`]}):(0,H.jsxs)(W,{size:`sm`,onClick:()=>i(e.id),disabled:n,"data-testid":`seed-subscribe-${e.id}`,className:`gap-2`,children:[(0,H.jsx)(ot,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Subscribe`})]}),(0,H.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:e.subscribed?`Apply new published versions automatically during the load-time check. Turning it off never removes content.`:`Unsubscribed sources never auto-import.`,children:[(0,H.jsx)(`input`,{type:`checkbox`,className:`size-3.5 accent-primary`,checked:c,disabled:n||!e.subscribed,onChange:t=>s(e.id,t.target.checked),"aria-label":`Auto-sync ${e.label}`,"data-testid":`seed-autosync-${e.id}`}),(0,H.jsx)(`span`,{children:`Auto-sync`})]}),(0,H.jsxs)(`details`,{className:`relative shrink-0`,"data-testid":`seed-more-${e.id}`,children:[(0,H.jsx)(`summary`,{"aria-label":`More actions for ${e.label}`,className:`flex cursor-pointer list-none items-center justify-center rounded-md border border-border px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden`,children:`…`}),(0,H.jsxs)(`div`,{className:`absolute right-0 z-20 mt-1 flex w-64 max-w-[80vw] flex-col items-stretch gap-1.5 rounded-lg border border-border bg-card p-2 text-xs shadow-lg`,children:[e.url?(0,H.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all font-mono text-primary hover:underline`,children:[`Published HTML: `,e.url]}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Published HTML: bundled with this app (no standalone URL)`}),e.repositoryUrl?(0,H.jsx)(`a`,{href:e.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-primary hover:underline`,children:`Git source directory`}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Git repository: not published`}),!l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(e.id),disabled:n||!e.subscribed,"data-testid":`seed-unsubscribe-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Unsubscribe`}),!l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(e.id),disabled:n,"data-testid":`seed-delete-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Delete source`})]})]})]})]}),e.url&&(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground font-mono break-all`,"data-testid":`seed-origin-${e.id}`,children:e.url}),(0,H.jsxs)(`div`,{className:`grid gap-1 text-sm`,"data-testid":`seed-status-card`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Library`}),(0,H.jsxs)(`span`,{className:`font-medium text-foreground text-xs tabular-nums`,"data-testid":`seed-source-size`,children:[e.count.toLocaleString(),` catalog `,e.count===1?`item`:`items`,` · `,wZ(e.bytes)]})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Local database`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-local-version`,children:e.stored?`v${e.stored.version} · schema ${e.stored.schema} · imported ${CZ(e.stored.importedAt)}`:`Not imported yet`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Published version`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs flex items-center gap-1.5`,"data-testid":`seed-remote-version`,children:e.remote?`v${e.remote.version} · schema ${e.remote.schema}`:e.remoteError?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(gt,{className:`size-3.5 text-muted-foreground`}),`Unavailable`]}):`Checking…`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last check`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-check`,children:e.checkedAt?CZ(e.checkedAt):`—`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last sync`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-sync`,children:e.stored?CZ(e.stored.importedAt):`Never`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Status`}),(0,H.jsx)(`span`,{className:`font-medium text-xs flex items-center gap-1.5`,"data-testid":`seed-sync-status`,children:e.subscribed?e.upToDate?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(yn,{className:`size-3.5 text-emerald-500`}),`Up to date`]}):e.remote==null?`Unknown (remote unreachable)`:c?`Update available — applied automatically on next load`:`Update available — sync to apply`:`Not subscribed`})]})]})]})}function kZ(){let[e,t]=(0,V.useState)(null),[n,r]=(0,V.useState)(!0),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)([]),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(null),g=(0,V.useCallback)(async()=>{a(null);try{t(await Rk())}catch(e){a(e instanceof Error?e.message:String(e))}finally{r(!1)}},[]);(0,V.useEffect)(()=>{g()},[g]),(0,V.useEffect)(()=>PO(()=>{g()}),[g]),(0,V.useEffect)(()=>Ck(()=>{g()}),[g]);let _=(0,V.useCallback)(async t=>{s(t??`all`),l([]);let n=e=>l(t=>{let n=t.find(t=>t.event.sourceId===e.sourceId),r={event:e,imported:e.phase===`checking`||e.phase===`finished`?n?.imported??null:e,chunks:e.phase===`committed`&&e.chunkId!==null?[...n?.chunks??[],e.chunkId]:n?.chunks??[]};return n?t.map(t=>t.event.sourceId===e.sourceId?r:t):[...t,r]});try{TZ(t?await Nk(t,{force:!0,onProgress:n}):await Ak({force:!0,onProgress:n}),t?e?.sources.find(e=>e.id===t)?.label??t:`All sources`),await g()}finally{s(null)}},[g,e]),v=(0,V.useCallback)(async()=>{h(null);let e;try{e=lO(u,f)}catch(e){h(e instanceof Error?e.message:String(e));return}d(``),p(``),await _(e.id)},[u,f,_]),y=(0,V.useCallback)((e,t)=>{LO(e,t)||Z({title:`Couldn't save Auto-sync`,description:`Browser storage is unavailable — the choice lasts this session only.`,variant:`destructive`}),g()},[g]),b=(0,V.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Unsubscribe from "${n}"? Imported content for this catalog is removed from your library; the source stays listed so you can subscribe again. Your own notes are never touched.`)){try{let{deleted:e}=await Pk(t);Z({title:`${n} unsubscribed`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed. The source stays listed for a later Subscribe.`})}catch(e){Z({title:`${n} unsubscribe failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await g()}},[e,g]),x=(0,V.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Delete "${n}"? Imported content is removed and the source is unregistered. Your own notes are never touched.`)){try{let{deleted:e}=await Fk(t);Z({title:`${n} deleted`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed and the source unregistered.`})}catch(e){Z({title:`${n} delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await g()}},[e,g]),S=c.at(-1)?.event;return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(ot,{className:`size-4 text-primary`}),`Content Sources`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Notebooks, notes, guides, dashboards, and efforts import into your active data location from seed sources. Subscribed sources are checked against their published manifest on every load: Auto-sync applies updates by itself, otherwise you press Sync when an update is pending. The core seed imports automatically at launch and is always subscribed.`})]}),i&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-destructive`,"data-testid":`seed-status-error`,children:[(0,H.jsx)(gt,{className:`size-3.5 shrink-0`}),`Couldn't read the seed status from the active storage: `,i]}),S&&(0,H.jsxs)(`div`,{className:`space-y-3 rounded-xl border border-border bg-card p-4`,"data-testid":`seed-sync-progress`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-sm font-medium`,children:[(0,H.jsx)(`span`,{children:o===null?c.some(e=>e.event.phase===`finished`&&e.event.outcome===`error`)?`Sync finished with errors`:`Sync finished`:`Syncing…`}),(0,H.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[`Source `,S.sourceIndex,` of `,S.totalSources]})]}),(0,H.jsxs)(`p`,{role:`status`,"aria-live":`polite`,className:`sr-only`,"data-testid":`seed-sync-live-status`,children:[S.sourceLabel,`: `,DZ(S)]}),c.map(({event:e,imported:t,chunks:n})=>(0,H.jsxs)(`div`,{className:`space-y-2 border-t border-border/50 pt-3`,children:[(0,H.jsxs)(`p`,{className:`text-xs ${e.phase===`finished`&&e.outcome===`error`?`text-destructive`:`text-muted-foreground`}`,children:[(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:e.sourceLabel}),` · `,DZ(e)]}),t&&t.totalChunks>0?(0,H.jsx)(sZ,{value:t.completedChunks,max:t.totalChunks,label:`Chunks committed · ${e.sourceLabel}`}):e.phase===`finished`?null:(0,H.jsx)(`progress`,{"aria-label":`Checking ${e.sourceLabel}`,className:`h-2 w-full`}),t&&(0,H.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-xs tabular-nums`,"data-testid":`seed-sync-totals`,children:[(0,H.jsxs)(`span`,{children:[t.totalNotes.toLocaleString(),` notes`]}),(0,H.jsxs)(`span`,{children:[t.totalEfforts.toLocaleString(),` efforts`]}),(0,H.jsxs)(`span`,{children:[t.totalBlocks.toLocaleString(),` blocks`]}),t.skippedUserOwned>0&&(0,H.jsxs)(`span`,{children:[t.skippedUserOwned.toLocaleString(),` user-owned rows preserved`]}),t.deleted>0&&(0,H.jsxs)(`span`,{children:[t.deleted.toLocaleString(),` seed rows removed`]})]}),n.length>0&&(0,H.jsxs)(`details`,{className:`text-xs`,"data-testid":`seed-sync-chunks`,children:[(0,H.jsxs)(`summary`,{className:`cursor-pointer text-muted-foreground`,children:[`Committed chunks (`,n.length,`)`]}),(0,H.jsx)(`ul`,{className:`mt-2 max-h-32 space-y-1 overflow-y-auto font-mono text-muted-foreground`,children:n.map(e=>(0,H.jsx)(`li`,{children:e},e))})]})]},e.sourceId))]}),(0,H.jsxs)(`div`,{className:`grid gap-3`,"data-testid":`seed-source-list`,children:[e?.sources.map(e=>(0,H.jsx)(OZ,{source:e,running:o===e.id||o===`all`,disabled:o!==null,onSync:e=>{_(e)},onSubscribe:e=>{_(e)},onUnsubscribe:e=>{b(e)},onDelete:e=>{x(e)},onAutoSync:y},e.id)),n&&e===null&&(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,children:`Checking sources…`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between pt-3 border-t border-border/50`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sync re-applies every published chunk. Your own notes, results, and edits are never overwritten.`}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>{_(null)},disabled:o!==null||n,"data-testid":`seed-resync-button`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${o===`all`?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:o===`all`?`Syncing all…`:`Sync All Sources`})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(be,{className:`size-4 text-primary`}),`Add a Source`]}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Register any URL serving a Wod Wiki seed (a directory with `,(0,H.jsx)(`code`,{children:`manifest.json`}),` and`,` `,(0,H.jsx)(`code`,{children:`chunks/`}),`) — a community library mirror or one you compiled yourself. The host must allow cross-origin reads (CORS). Added sources sync immediately and start subscribed; manage Auto-sync, Unsubscribe, and Delete on each source card above.`]})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-add-source-form`,children:[(0,H.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`seed-source-label`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Label`}),(0,H.jsx)(SZ,{id:`seed-source-label`,value:u,onChange:e=>d(e.target.value),placeholder:`My library (optional — defaults to the host name)`,disabled:o!==null})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`seed-source-url`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Seed directory URL`}),(0,H.jsx)(SZ,{id:`seed-source-url`,type:`text`,autoComplete:`off`,spellCheck:!1,value:f,onChange:e=>p(e.target.value),placeholder:`https://example.com/seed/library/`,className:`font-mono`,disabled:o!==null})]})]}),m&&(0,H.jsxs)(`p`,{role:`alert`,className:`flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`seed-add-error`,children:[(0,H.jsx)(gt,{className:`size-3.5 mt-0.5 shrink-0`}),(0,H.jsx)(`span`,{children:m})]}),(0,H.jsx)(`div`,{className:`flex justify-end`,children:(0,H.jsxs)(W,{size:`sm`,onClick:()=>{v()},disabled:o!==null||!f.trim(),"data-testid":`seed-add-button`,className:`gap-2`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Add & Sync`})]})})]})]})]})}function AZ({open:e,onOpenChange:t}){return(0,H.jsx)(mZ,{open:e,onOpenChange:t,children:(0,H.jsxs)(_Z,{className:`max-h-[85vh] w-full max-w-2xl overflow-y-auto`,"data-testid":`catalogs-manager-drawer`,children:[(0,H.jsxs)(vZ,{children:[(0,H.jsx)(yZ,{children:`Notebook Subscriptions & Local Libraries`}),(0,H.jsx)(bZ,{children:`Manage the workout notebooks stored in your active data location — compare versions, sync updates, and subscribe, unsubscribe, or delete sources. Your own notes are never touched.`})]}),(0,H.jsx)(kZ,{})]})})}var jZ={stream:`cards`,table:`rows`},MZ=`wodwiki.viewSettings.v1`,NZ={"/sessions":`/results`,"/feeds":`/collections`},PZ=new qy(MZ);function FZ(e,t){return{level:e,layout:t??`cards`,visibleFields:PL(e),groupBy:void 0}}function IZ(e,t,n=PZ,r){let i=FZ(t,r),a=e.startsWith(`/`)?e:`/${e}`,o=NZ[a],s=n.get(a,{alias:o});if(!s)return i;let c=typeof s.layout==`string`?s.layout:``,l=c===`cards`||c===`rows`||c===`feed`?c:jZ[c]??`cards`,u=new Set(NL(t).map(e=>e.id)),d=Array.isArray(s.visibleFields)?s.visibleFields.filter(e=>typeof e==`string`&&u.has(e)):i.visibleFields,f=typeof s.groupBy==`string`?s.groupBy:void 0;return{level:t,layout:l,visibleFields:d.length>0?d:i.visibleFields,groupBy:f}}function LZ(e,t,n=PZ){let r=e.startsWith(`/`)?e:`/${e}`;n.set(r,{level:t.level,layout:t.layout,visibleFields:t.visibleFields,groupBy:t.groupBy})}function RZ(e,t,n=PZ){let r=e.startsWith(`/`)?e:`/${e}`,i=NZ[r];return n.remove(r,i),FZ(t)}function zZ(e,t,n){let[r,i]=(0,V.useState)(()=>IZ(e,t,PZ,n));(0,V.useEffect)(()=>{i(IZ(e,t,PZ,n))},[e,t,n]);let a=(0,V.useCallback)(t=>{i(n=>{let r=t(n);return LZ(e,r),r})},[e]);return{settings:r,setLayout:(0,V.useCallback)(e=>{a(t=>({...t,layout:e}))},[a]),toggleField:(0,V.useCallback)(e=>{a(t=>{let n=new Set(t.visibleFields);return n.has(e)?n.delete(e):n.add(e),{...t,visibleFields:Array.from(n)}})},[a]),setVisibleFields:(0,V.useCallback)(e=>{a(t=>({...t,visibleFields:e}))},[a]),setGroupBy:(0,V.useCallback)(e=>{a(t=>({...t,groupBy:e}))},[a]),resetSettings:(0,V.useCallback)(()=>{let n=RZ(e,t);i(n)},[e,t])}}function BZ(e,t=200){let[n,r]=(0,V.useState)(t),i=(0,V.useRef)(null);(0,V.useEffect)(()=>{r(t)},[e,t]);let a=n<e.length,o=(0,V.useCallback)(t=>r(n=>Math.max(n,Math.min(Math.max(t,0),e.length))),[e.length]);return(0,V.useEffect)(()=>{let n=i.current;if(!n||!a)return;let o=new IntersectionObserver(n=>{n.some(e=>e.isIntersecting)&&r(n=>Math.min(n+t,e.length))},{rootMargin:`400px`});return o.observe(n),()=>o.disconnect()},[a,e.length,t]),{visible:e.slice(0,n),hasMore:a,sentinelRef:i,total:e.length,growTo:o}}function VZ(e,t){let n=Y(e);return n.error||!nm(n)?e:Km({...n,metric:t})}function HZ(e){let t=Y(e);return t.error?e:Km({...t,window:void 0})}function UZ(e){let t=Y(e);return t.error?e:Km({...t,filters:t.filters.filter(e=>e.key===`source`)})}function WZ(e,t){let n=Y(e);return n.error?e:Km({...n,groupBy:[t]})}function GZ(e){return e.kind===`session`&&!e.sourceItem?!1:e.kind===`note`||e.kind===`session`||e.kind===`post`}async function KZ(e){if(e.wodBlock?.content.trim())return e.wodBlock.content;let t=await Kj.resolve(e.id),n=fz(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``),r=n.find(e=>e.dialect===`time`)??n[0];if(!r)throw Error(`No runnable workout block in this entry.`);return r.script}function qZ(e,t){return{id:e.wodBlock?.blockId??e.block?.blockId??C(),contentId:e.wodBlock?.blockContentId??e.blockContentId,dialect:`time`,startLine:0,endLine:t.split(`
155
- `).length,content:t,state:`idle`,widgetIds:{},version:1,createdAt:Date.now()}}async function JZ(e,t){let n=await KZ(e),r=qZ(e,n),i=C();if(wz(e)){let n=await Kj.getById(e.id),a=e.wodBlock||e.block?n.blocks?.[r.id]:Object.values(n.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The selected saved workout is unavailable.`);VJ.set(i,{block:{...r,id:a.id},noteId:e.id,origin:`playground`,returnTo:Cz(e)}),t(QA(i));return}let a=await OJ({workoutName:e.title,category:e.sourceCatalog,sourceNoteLabel:e.subtitle??e.title,sourceNotePath:Cz(e),wodContent:n}),o=Object.values(a.blocks??{}).find(e=>e.kind===`wod`);if(!o)throw Error(`The saved journal workout is unavailable.`);VJ.set(i,{block:{...r,id:o.id},noteId:a.id}),t(JA(a.journalDate??``,i))}var YZ={note:N,session:Rt,post:qt,effort:ce,result:Ue,segment:me,event:S,dashboard:tn,equipment:D},XZ={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},ZZ={note:`bg-primary/10 text-primary group-hover:bg-primary/20`,session:`bg-amber-500/10 text-amber-600 group-hover:bg-amber-500/20`,post:`bg-violet-500/10 text-violet-600 group-hover:bg-violet-500/20`,effort:`bg-emerald-500/10 text-emerald-600 group-hover:bg-emerald-500/20`,result:`bg-sky-500/10 text-sky-600 group-hover:bg-sky-500/20`,segment:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,event:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,dashboard:`bg-cyan-500/10 text-cyan-600 group-hover:bg-cyan-500/20`,equipment:`bg-orange-500/10 text-orange-600 group-hover:bg-orange-500/20`};function QZ({entry:e,leading:t,actions:n,dateLabel:r,visibleFieldIds:i,tone:a=`secondary`,onAddToToday:o,onRunStart:s}){let c=Sn(),l=e.kind===`note`?e.sourceCatalog:void 0,d=l===`playground`?u:l===`guides`?lr:YZ[e.kind],f=l===`playground`?`Playground`:l===`guides`?`Guide`:XZ[e.kind],p=a===`primary`,m=Tz(e),h=Cz(e),g=i?new Set(i):null,_=!g||g.has(`date`),v=!g||g.has(`catalog`)||g.has(`protocol`)||g.has(`elapsedTime`)||g.has(`splitDuration`)||g.has(`discipline`)||g.has(`met`)||g.has(`canonicalSlug`),y=!g||g.has(`excerpt`)||g.has(`movements`)||g.has(`tags`)||g.has(`aliases`);return(0,H.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:()=>c(Cz(e)),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),c(Cz(e)))},className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group w-full cursor-pointer ${p?`bg-primary/[0.025]`:``}`,"data-testid":`library-row-${e.kind}`,children:[t,(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl flex items-center justify-center transition-colors ${ZZ[e.kind]}`,children:(0,H.jsx)(d,{className:`size-4`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:e.title}),e.block&&(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-sky-600 border border-sky-500/40 bg-sky-500/10 rounded-full px-1.5 py-0.5`,"data-testid":`library-row-block-type`,children:e.block.dataType}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:f}),e.execution?.effortSlug&&(0,H.jsx)(Wn,{to:cj(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`library-row-effort-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors shrink-0`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:e.detail??e.execution.effortSlug}),m&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(Wn,{to:h,"data-testid":`library-row-details-link`,className:`text-[9px] font-bold tracking-wide text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border rounded-full px-2 py-0.5 transition-colors`,title:`View catalog details`,children:`Details`}),(0,H.jsx)(Wn,{to:m,"data-testid":`library-row-feed-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors`,title:`View feed`,children:`Feed`})]}),e.subtitle&&v&&(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/60 truncate`,children:e.subtitle})]}),y&&(e.block?(0,H.jsx)(`div`,{className:`mt-0.5`,"data-testid":`library-row-block-preview`,children:e.block.preview.map((e,t)=>(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate font-mono`,children:e},t))}):e.detail?(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate mt-0.5`,children:e.detail}):null)]}),r&&_&&(0,H.jsx)(`span`,{className:`flex-shrink-0 text-[10px] text-muted-foreground/70 tabular-nums`,"data-testid":`library-row-date`,children:r}),n??(0,H.jsx)($Z,{entry:e,onAddToToday:o,onRunStart:s})]})}function $Z({entry:e,onAddToToday:t,onRunStart:n}){let r=Sn(),i=Ez(e),a=Tz(e),o=Dz(e)&&!!t,s=GZ(e)&&!!n;return(0,H.jsxs)(`div`,{className:`flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(eQ,{title:a?`Details`:`Open`,testId:`action-open`,onClick:()=>r(Cz(e)),children:(0,H.jsx)(Ht,{className:`size-3.5`})}),a&&(0,H.jsx)(eQ,{title:`Feed`,testId:`action-feed`,onClick:()=>r(a),children:(0,H.jsx)(Rt,{className:`size-3.5`})}),o&&(0,H.jsx)(eQ,{title:`Add to today`,testId:`action-add`,onClick:()=>t?.(e),children:(0,H.jsx)(Kt,{className:`size-3.5`})}),s&&(0,H.jsx)(eQ,{title:`Run`,testId:`action-run`,onClick:()=>n?.(e),children:(0,H.jsx)(Ht,{className:`size-3.5`})}),i&&(0,H.jsx)(eQ,{title:`Compare`,testId:`action-compare`,onClick:()=>r(i),children:(0,H.jsx)(At,{className:`size-3.5`})})]})}function eQ({title:e,testId:t,onClick:n,children:r}){return(0,H.jsx)(`button`,{type:`button`,title:e,onClick:n,"data-testid":t,className:`size-8 rounded-lg flex items-center justify-center text-muted-foreground hover:text-primary hover:bg-primary/10 transition-colors`,children:r})}function tQ({entries:e,level:t,visibleFieldIds:n,onRowClick:r,emptyMessage:i=`No entries to display`,className:a=``,stickyHeaderTop:o}){let s=Sn(),c=(0,V.useMemo)(()=>t||(e.length>0?AL(e[0]):`note`),[t,e]),l=(0,V.useMemo)(()=>NL(c),[c]),u=(0,V.useMemo)(()=>{let e=new Set(n??PL(c));return l.filter(t=>e.has(t.id))},[l,n,c]),d=e=>{r?r(e):s(Cz(e))},[f,p]=(0,V.useState)(null),[m,h]=(0,V.useState)(`asc`),g=e=>{f===e?h(e=>e===`asc`?`desc`:`asc`):(p(e),h(`asc`))},_=(0,V.useMemo)(()=>{if(!f)return e;let t=l.find(e=>e.id===f);return t?[...e].sort((e,n)=>{let r=t.getValue(e),i=t.getValue(n);if(r==null&&i==null)return 0;if(r==null)return m===`asc`?1:-1;if(i==null)return m===`asc`?-1:1;if(typeof r==`number`&&typeof i==`number`)return m===`asc`?r-i:i-r;if(Array.isArray(r)&&Array.isArray(i)){let e=r.join(`, `),t=i.join(`, `);return m===`asc`?e.localeCompare(t):t.localeCompare(e)}let a=String(r),o=String(i);return m===`asc`?a.localeCompare(o):o.localeCompare(a)}):e},[e,f,m,l]);return e.length===0?(0,H.jsx)(`div`,{className:`w-full py-16 text-center text-sm text-muted-foreground ${a}`,"data-testid":`property-table-empty`,children:i}):(0,H.jsx)(`div`,{className:`w-full border-y border-border bg-card/50 ${o===void 0?`overflow-x-auto`:`overflow-x-clip`} ${a}`,"data-testid":`property-table`,children:(0,H.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,H.jsx)(`thead`,{className:o===void 0?void 0:`sticky z-10`,style:o===void 0?void 0:{top:`${o}px`},children:(0,H.jsx)(`tr`,{className:`border-b border-border`,children:u.map(e=>{let t=e.align===`right`?`text-right`:e.align===`center`?`text-center`:`text-left`;return(0,H.jsx)(`th`,{scope:`col`,onClick:()=>g(e.id),className:`px-4 py-3 font-semibold uppercase tracking-wider text-[11px] text-muted-foreground whitespace-nowrap border-b border-border cursor-pointer select-none hover:text-foreground transition-colors group/th ${o===void 0?`bg-muted/30`:`bg-muted/95 backdrop-blur-sm`} ${t}`,"data-testid":`property-table-header-${e.id}`,children:(0,H.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 ${t===`text-right`?`justify-end`:t===`text-center`?`justify-center`:`justify-start`}`,children:[(0,H.jsx)(`span`,{children:e.label}),f===e.id?(0,H.jsx)(`span`,{className:`text-primary font-bold text-xs`,"aria-label":m===`asc`?`sorted ascending`:`sorted descending`,children:m===`asc`?`↑`:`↓`}):(0,H.jsx)(`span`,{className:`opacity-0 group-hover/th:opacity-40 text-muted-foreground text-[10px]`,"aria-hidden":`true`,children:`↕`})]})},e.id)})})}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border/60`,children:_.map(e=>{let t=Tz(e),n=Cz(e);return(0,H.jsx)(`tr`,{role:`button`,tabIndex:0,onClick:()=>d(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),d(e))},className:`hover:bg-muted/40 transition-colors cursor-pointer group`,"data-testid":`property-table-row-${e.id}`,children:u.map(r=>{let i=r.getValue(e),a=r.formatValue(i,e),o=r.align===`right`?`text-right tabular-nums`:r.align===`center`?`text-center`:`text-left`;return(0,H.jsx)(`td`,{className:`px-4 py-3 whitespace-nowrap text-foreground/90 ${o}`,"data-testid":`property-table-cell-${r.id}`,children:r.id===`pacingTier`&&e.execution?.effortSlug?(0,H.jsx)(Wn,{to:cj(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`property-table-effort-link`,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:a}):r.id===`title`||r.id===`label`?(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`font-medium text-foreground group-hover:text-primary transition-colors`,children:a}),t&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-auto`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(Wn,{to:n,"data-testid":`property-table-details-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border transition-colors`,title:`View catalog details`,children:`Details`}),(0,H.jsx)(Wn,{to:t,"data-testid":`property-table-feed-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View feed`,children:`Feed`})]})]}):a},r.id)})},e.id)})})]})})}var nQ={note:N,session:Rt,post:N,effort:ce,result:Ue,segment:me,event:S,dashboard:tn,equipment:D},rQ={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},iQ=8;function aQ({entry:e}){let t=e.execution;if(!t)return null;let n=[];return t.elapsedMs!=null&&n.push(_I(t.elapsedMs)),t.reps!=null&&n.push(`${t.reps} reps`),t.loadLbs!=null&&n.push(`${t.loadLbs} lb`),t.distanceMeters!=null&&n.push(`${(t.distanceMeters/1e3).toFixed(2)} km`),t.tis!=null&&n.push(`TIS ${t.tis}`),n.length===0?null:(0,H.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1.5`,"data-testid":`stream-feed-metrics`,children:n.map(e=>(0,H.jsx)(`span`,{className:`rounded-full bg-muted/70 border border-border/60 px-2 py-0.5 text-[10px] font-bold tabular-nums text-muted-foreground`,children:e},e))})}function oQ({entry:e}){let[t,n]=(0,V.useState)(!1),r=e.wodBlock?.content.trim(),i=r?r.split(`
156
- `):e.excerpt??e.block?.preview??[],a=i.length>iQ,o=t||!a?i:i.slice(0,iQ);return i.length===0&&!e.detail?null:(0,H.jsxs)(`div`,{className:`mt-1.5`,"data-testid":`stream-feed-preview`,children:[i.length>0&&(0,H.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground ${a&&!t?`max-h-40 overflow-hidden`:``}`,children:o.join(`
157
- `)}),i.length===0&&e.detail&&(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.detail}),a&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(e=>!e),"data-testid":`stream-feed-preview-toggle`,className:`mt-1 min-h-[44px] px-2 -ml-2 text-[10px] font-black uppercase tracking-widest text-primary hover:text-primary/80 transition-colors`,children:t?`Show less`:`Show more (${i.length-iQ} lines)`})]})}function sQ({groups:e,batch:t,onRunEntry:n,onSendToPlayground:r,stickyOffset:i}){return(0,H.jsxs)(`div`,{className:`flex-1 divide-y divide-border/40`,"data-testid":`stream-feed`,children:[e.map(e=>(0,H.jsxs)(`section`,{id:e.id,"data-testid":`stream-feed-group-${e.key}`,children:[(0,H.jsx)(oL,{top:i,icon:(0,H.jsx)(qt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,H.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${e.entries.length} ${e.entries.length===1?`entry`:`entries`}`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(e=>{let t=e.kind===`note`?e.sourceCatalog:void 0,i=t===`playground`?u:t===`guides`?lr:nQ[e.kind],a=t===`playground`?`Playground`:t===`guides`?`Guide`:rQ[e.kind],o=Cz(e),s=Tz(e),c=!wz(e)&&(e.kind===`note`||e.kind===`session`||e.kind===`post`);return(0,H.jsx)(`article`,{"data-testid":`stream-feed-item`,className:`px-6 py-4`,children:(0,H.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center`,children:(0,H.jsx)(i,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:(0,H.jsx)(Wn,{to:o,className:`hover:text-primary transition-colors`,children:e.title})}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:a}),e.subtitle&&(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/70 truncate`,children:e.subtitle})]}),(0,H.jsx)(oQ,{entry:e}),(0,H.jsx)(aQ,{entry:e}),(0,H.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,H.jsx)(Wn,{to:o,"data-testid":`stream-feed-open`,className:`inline-flex min-h-[44px] items-center rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:s?`Details`:`Open`}),s&&(0,H.jsxs)(Wn,{to:s,"data-testid":`stream-feed-collection-feed`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,H.jsx)(Rt,{className:`size-3`}),`Feed`]}),GZ(e)&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e),"data-testid":`stream-feed-run`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,H.jsx)(Ht,{className:`size-3`}),`Run`]}),c&&r&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"data-testid":`stream-feed-playground`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:[(0,H.jsx)(er,{className:`size-3`}),`Playground`]})]})]})]})},e.id)})})]},e.id)),t.hasMore&&(0,H.jsxs)(`div`,{ref:t.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-feed-load-more`,children:[`Loading more — `,t.total-t.visible.length,` remaining…`]})]})}function cQ(e,t,n){return{journalDate:n,title:e.title,rawContent:t,sourceId:e.sourceId,type:`journal`}}var lQ=/\[([^\]]*)\]\((:[^)]*)\)!/g;function uQ(e){let t=e.trim();try{return decodeURIComponent(t)}catch{return t}}function dQ(e){let t=uQ(e);return t.startsWith(`:`)&&!Y(t).error}function fQ(e){let t=[],n=0;for(let r of e.matchAll(lQ)){let i=r.index??0,a=uQ(r[2]);dQ(a)&&(i>n&&t.push({kind:`markdown`,text:e.slice(n,i)}),t.push({kind:`query`,query:a.trim(),heading:r[1]}),n=i+r[0].length)}n<e.length&&t.push({kind:`markdown`,text:e.slice(n)});let r=[];for(let e of t){let t=r[r.length-1];e.kind===`markdown`&&t?.kind===`markdown`?t.text+=e.text:r.push(e)}return r}function pQ(e){return e.some(e=>e.kind===`query`)}var mQ=`9999-12-31`;function hQ(e,t){return(e.date??mQ).localeCompare(t.date??mQ)||e.title.localeCompare(t.title,void 0,{numeric:!0,sensitivity:`base`})}function gQ(e){let t=new Date(`${e}T12:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`,year:`numeric`})}function _Q({query:e,heading:t,onAddToToday:n,onRunStart:r}){let[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null);(0,V.useEffect)(()=>{let t=!1;return a(null),s(null),OI.query(e).then(e=>{t||a([...e].sort(hQ))}).catch(e=>{t||s(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let c=(0,V.useMemo)(()=>{if(!i)return null;let t=Y(e);if(t.error||!(`groupBy`in t)||!t.groupBy?.includes(`date`))return null;let n=new Map;for(let e of i){let t=e.date??``,r=n.get(t);r?r.push(e):n.set(t,[e])}return[...n.entries()]},[i,e]);if(o)return(0,H.jsxs)(`p`,{className:`my-3 text-xs text-destructive`,"data-testid":`readme-query-error`,children:[`Query failed: `,o]});if(i===null)return(0,H.jsx)(`div`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-loading`,children:`Loading…`});if(i.length===0)return(0,H.jsx)(`p`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-empty`,children:`No entries match this query.`});let l=e=>(0,H.jsx)(QZ,{entry:e,onAddToToday:n,onRunStart:r},e.id);return(0,H.jsxs)(`div`,{className:`my-3 not-prose`,"data-testid":`readme-query-block`,children:[t&&(0,H.jsx)(`p`,{className:`mt-4 mb-1 text-sm font-bold text-foreground`,"data-testid":`readme-query-heading`,children:t}),c?c.map(([e,t])=>(0,H.jsxs)(`div`,{className:`mt-3`,"data-testid":`readme-query-date-group`,children:[(0,H.jsx)(`p`,{className:`mb-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,children:e?gQ(e):`Undated`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:t.map(l)})]},e||`undated`)):(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:i.map(l)})]})}var vQ=new ID,yQ=[{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`}];function bQ({batch:e,testId:t=`stream-load-more`}){return e.hasMore?(0,H.jsxs)(`div`,{ref:e.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":t,children:[`Loading more — `,e.total-e.visible.length,` remaining…`]}):null}var xQ=150;function SQ(e){switch(e.phase){case`checking`:return`Checking the community library…`;case`fetching`:return`Downloading ${e.chunkId??`library`}…`;case`applying`:return`Importing ${e.chunkId??`library`}…`;case`committed`:return`Committed ${e.chunkId??`chunk`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??`Done`}}function CQ({error:e,target:t,matched:n,total:r,loading:i,applied:a,ignored:o,advisories:s,groupDims:c,groupingSource:l}){return(0,H.jsxs)(`div`,{role:`status`,"data-testid":`stream-query-status`,className:`flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground`,children:[e?(0,H.jsx)(`span`,{className:`font-semibold text-destructive`,children:`Invalid query — showing previous results`}):t?(0,H.jsxs)(`span`,{className:`font-mono`,children:[`:`,t]}):null,(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{"data-testid":`stream-query-counts`,className:i?`motion-safe:animate-pulse`:void 0,children:[n,` of `,r]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{"data-testid":`stream-query-filters`,children:[a,` applied`,o>0?`, ${o} ignored`:``]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{children:[`by `,c.join(`, `),` `,(0,H.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`(`,l,`)`]})]}),s.map(e=>(0,H.jsx)(`p`,{className:`w-full break-words text-amber-700 dark:text-amber-400`,children:e},e))]})}function wQ({profile:e,actions:t,queryEngine:n,onAddToToday:r,registerStreamDraft:i}){let a=Sn(),o=mt(),s=eZ(),c=iZ(),[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),{query:_,setQuery:v,urlQueryError:y}=bA({defaultQuery:()=>e.defaultWql,legacy:e.legacy});(0,V.useEffect)(()=>i?.(()=>_),[i,_]);let{settings:b,setLayout:x,toggleField:S,setGroupBy:C}=zZ(e.route,e.level,e.defaultLayout),[w,T]=(0,V.useState)([]),[E,D]=(0,V.useState)(void 0),[O,k]=(0,V.useState)(null),[A,j]=(0,V.useState)(!0),[M,N]=(0,V.useState)(!1),[P,F]=(0,V.useState)(null),I=UL(),ee=dL(),te=e.route===`/catalogs`,ne=(0,V.useMemo)(()=>te&&new URLSearchParams(o.search).get(`manage`)===`1`,[te,o.search]),re=(0,V.useCallback)(e=>{let t=new URLSearchParams(o.search);e?t.set(`manage`,`1`):t.delete(`manage`);let n=t.toString();a({pathname:o.pathname,search:n?`?${n}`:``},{replace:!e})},[a,o.pathname,o.search]),ie=te?(0,H.jsx)(AZ,{open:ne,onOpenChange:re}):null,[ae,oe]=(0,V.useState)(!1),se=(0,V.useCallback)(async(e,t,n)=>{let r=await WO.create(e,t,n);return await X.saveNote(WO.createNotebookLandingNote(r)),Se(e=>e+1),r},[]),ce=te?(0,H.jsx)(oZ,{open:ae,onOpenChange:oe,onCreate:se}):null,L=(0,V.useMemo)(()=>Y(_),[_]),le=(0,V.useMemo)(()=>L.error||rm(L)?!1:L.filters.some(e=>e.key===`source`&&!e.negate&&e.values.some(e=>e.value===`playground`)),[L]),ue=(0,V.useMemo)(()=>{if(e.catalog)return e.catalog;if(e.route.startsWith(`/c/`)){let t=e.route.slice(3);if(t&&!t.includes(`/`))return t}if(!L.error&&tm(L)){let e=L.filters.find(e=>(e.key===`notebook`||e.key===`catalog`)&&!e.negate)?.values[0]?.value;if(e)return xa(e)}},[e,L]),R=sD(),[de,fe]=(0,V.useState)(null),pe=(0,V.useMemo)(()=>de?fQ(de):[],[de]),me=pQ(pe);(0,V.useEffect)(()=>{if(!ue){fe(null);return}let e=`markdown/collections/${ue}/README.md`,t=R?.[e];t&&fe(t.replace(/\{\{workouts\}\}/g,``).trim());let n=!1;return Kv(e).then(async e=>{try{let t=await vQ.getEntry(e);!n&&t?.rawContent&&fe(t.rawContent.replace(/\{\{workouts\}\}/g,``).trim())}catch{}}),()=>{n=!0}},[ue,R]);let he=(0,V.useMemo)(()=>{let e=n??OI;return b.layout===`feed`?e.withNoteBlockInfo():e},[n,b.layout]),ge=(0,V.useCallback)(async e=>{let t=_z(),n=``,r=e.kind===`result`||e.kind===`segment`?e.execution?.noteId:e.kind===`note`?e.sourceItem:e.id;if(r){if(e.kind===`segment`&&e.blockContentId){let t=(await XF.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]})).blocks.find(t=>t.id===e.blockContentId);t?.rawContent&&(n=t.rawContent)}if(!n&&(e.kind===`note`||e.kind===`result`||e.kind===`segment`)){let e=await Kj.getById(r);e&&typeof e==`object`&&`rawContent`in e&&typeof e.rawContent==`string`&&(n=e.rawContent)}if(!n&&e.kind!==`note`){let e=await XF.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]});e.blocks.length>0&&(n=[...e.blocks].sort((e,t)=>(e.position??0)-(t.position??0)).filter(e=>e.rawContent.trim()!==``).map(e=>e.dataType===`frontmatter`?`---\n${e.rawContent}\n---`:e.rawContent).join(`
159
+ `),a=t.match(/^(\d{1,2}:\d{2}(?::\d{2})?)/m)?.[1],o=r[0]?.substring(0,60)||`Workout`,s=e.type===`time`||e.type===`log`?e.type:`time`;return{id:e.id,title:o,statementCount:r.length,contentPreview:i,timerHint:a,dialect:s}}),o={type:`rpc-workbench-update`,mode:r.length>0?`preview`:`idle`,previewData:r.length>0?{title:r[0].title,blocks:r}:void 0},s=JSON.stringify(o);if(s!==a.current){a.current=s;try{i.send(o)}catch{}}},[i,e,t,n]),(0,V.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,V.useEffect)(()=>{t||(a.current=``)},[t]),(0,V.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},oK={[G.Duration]:{label:`Timer`,icon:`⏱`,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[G.Rep]:{label:`Reps`,icon:`✕`,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[G.Effort]:{label:`Exercise`,icon:`🏋`,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[G.Rounds]:{label:`Rounds`,icon:`↻`,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[G.Distance]:{label:`Distance`,icon:`📏`,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[G.Resistance]:{label:`Weight`,icon:`⚖`,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[G.Equipment]:{label:`Equipment`,icon:`🧰`,textClass:`text-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border/50`},[G.Action]:{label:`Action`,icon:`⚡`,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[G.Label]:{label:`Label`,icon:`🏷`,textClass:`text-muted-foreground`,bgClass:`bg-muted/30`,borderClass:`border-border/40`}},sK={[G.Rep]:`reps`,[G.Effort]:`movement`,[G.Resistance]:`weight`},cK=({metric:e,tooltip:t,isFocused:n,onClick:r})=>{let i=oK[e.type],a=e.type===G.Hint,o=e.image??(e.value===void 0?``:String(e.value)),s=i?.label??String(e.type);return(0,H.jsxs)(`span`,{title:t,onClick:r,className:U(`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium`,`pointer-events-auto transition-opacity hover:opacity-80`,i?.bgClass??`bg-muted/30`,i?.textClass??`text-muted-foreground`,i?.borderClass??`border-border/40`,r&&`cursor-pointer`,n&&`font-bold shadow-sm`),children:[(0,H.jsx)(`span`,{children:a?e.icon:i?.icon??`•`}),!a&&(0,H.jsx)(`span`,{children:s}),!a&&o&&(0,H.jsx)(`span`,{className:`font-semibold`,children:o})]})};function lK(e){let t=fa(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function uK(e,t){try{let n=e.coordsAtPos(t);if(!n)return null;let r=e.dom?.getBoundingClientRect?.()??{top:0,left:0},i=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:0};return{top:n.bottom-r.top,left:i.left-r.left,width:i.width}}catch{return null}}var dK=({view:e,cursorVersion:t,getCursorFocusState:n})=>{let[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(null),s=(0,V.useRef)(null),c=(0,V.useCallback)(()=>{if(!e){o(null),i(null);return}let t=(n??rU)(e.state);o(t),i(t?uK(e,t.lineFrom):null)},[e,n]);if((0,V.useEffect)(()=>{c()},[c,t]),(0,V.useEffect)(()=>{if(!e)return;let t=()=>c();return window.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t,!0),()=>{window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t,!0)}},[e,c]),!r||!a?.section)return null;let l=a.allStatements?.filter(e=>e.meta?.line===a.cursorLine-a.section.startLine)??(a.statement?[a.statement]:[]),u=l.flatMap(e=>e.metrics.toArray()).filter(e=>e.type!==G.Sound&&e.type!==G.System&&!(e.type===G.Hint&&!e.icon)),d=FB(u,`runtime-badge`),f=l.flatMap(e=>e.metrics.toArray()),p=[],m=[],h=[];for(let e of f){let t=lK(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;p.includes(t)||(p.push(t),m.push(e))}h.push(...t.diagnostics)}let g=typeof e?.state?.facet==`function`?e.state.facet(kw)?.()??null:null,_=typeof e?.state?.doc?.sliceString==`function`?qH(e.state.doc.sliceString(a.lineFrom,a.lineTo)):null,v=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&_?.equipment.includes(e.token)?`equipment`:`effort`,y=e=>typeof e==`string`&&e.trim()?e:null,b=async t=>{if(!e)return;let n=e.state.doc.sliceString(a.lineFrom,a.lineTo),r=UR.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort…`,sources:[GH(`effort`)]});if(t.dismissed)return;let i=y(t.item.payload);if(!i)return;e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:JH(n,{effort:i})}});return}let i=[..._?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)…`:`Set equipment…`,sources:[GH(`equipment`)]});if(e.dismissed)break;let t=y(e.item.payload);t&&!i.includes(t)&&i.push(t)}((_?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:JH(n,{equipment:i})}})},x=async()=>{if(!e)return;let t=e.state.doc.sliceString(a.lineFrom,a.lineTo),n=UR.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)…`,sources:[GH(`effort`)]});i.dismissed||(r=y(i.item.payload)??void 0);let o=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)…`,sources:[GH(`equipment`)]});if(e.dismissed)break;let t=y(e.item.payload);t&&!o.includes(t)&&o.push(t)}!r&&o.length===0||e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:JH(t,{effort:r,equipment:o})}})},S=async t=>{if(!e||!t.token)return;let n=v(t),r=await UR.getState().open({placeholder:`Replace “${t.token}”…`,sources:[GH(n,t.candidates)]});if(r.dismissed)return;let i=y(r.item.payload);if(!i)return;let o=e.state.doc.sliceString(a.lineFrom,a.lineTo).indexOf(t.token);o<0||e.dispatch({changes:{from:a.lineFrom+o,to:a.lineFrom+o+t.token.length,insert:i}})},C=t=>{let n=sK[t.type];if(!n||!e)return;let r=t.type===G.Effort?`effort`:t.type===G.Equipment?`equipment`:null;if(r&&_?.jsonFrom!==void 0&&_.jsonFrom>=0){b(r);return}cn(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-D6p7_NoH.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:t})=>{t(a,e,n)})};return(0,H.jsxs)(`div`,{ref:s,className:U(`cm-metric-inline-panel`,`absolute z-50 pointer-events-none`,`flex items-center gap-2 px-3 h-[28px]`,`bg-background/90 backdrop-blur-sm`,`border-l border-r border-border/50`,`transition-opacity duration-100`),style:{top:r.top,left:r.left,width:r.width,maxWidth:r.width},"aria-live":`polite`,"aria-label":`Metric inline panel`,children:[u.length>0?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-medium shrink-0 select-none`,children:`Metrics:`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[u.map((e,t)=>(0,H.jsx)(cK,{metric:e,tooltip:e.type===G.Hint?String(e.value??``):d[t]?.tooltip,isFocused:a.focusedMetric===e,onClick:sK[e.type]?()=>C(e):void 0},`${e.type}-${t}`)),m.map(e=>(0,H.jsxs)(`span`,{title:`${e.kind===`effort`?`Effort`:`Equipment`} · click to change source`,onClick:()=>void b(e.kind),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium cursor-pointer hover:opacity-80 bg-muted/40 text-foreground border-border/50`,children:[(0,H.jsx)(`span`,{children:e.kind===`effort`?`🏋`:`🧰`}),(0,H.jsx)(`span`,{className:`font-semibold`,children:e.label}),g&&(0,H.jsx)(`a`,{href:g.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`${e.kind}:${e.slug}`)),_?.malformed&&(0,H.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:`Reference JSON on this line does not parse — fix it in the raw text.`,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,H.jsx)(`span`,{children:`⚠`}),(0,H.jsx)(`span`,{children:`Malformed reference JSON`})]}),h.map((e,t)=>{let n=v(e);return(0,H.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,H.jsx)(`span`,{children:`⚠`}),(0,H.jsx)(`span`,{children:e.token??e.reason}),(0,H.jsx)(`button`,{type:`button`,className:`underline cursor-pointer`,onClick:()=>void S(e),children:`Select existing`}),g&&(0,H.jsx)(`a`,{href:g.createHref(n),className:`underline hover:text-foreground`,children:`Create page`})]},`${e.reason}-${t}`)}),(0,H.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void x(),className:`pointer-events-auto inline-flex items-center px-1.5 py-0.5 rounded border border-dashed border-border/60 text-[10px] text-muted-foreground hover:text-foreground hover:border-primary/50 cursor-pointer`,children:`+ Metric`})]})]}):(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/50 italic select-none`,children:`No metrics on this line`}),(0,H.jsx)(`span`,{className:`ml-auto text-[9px] text-muted-foreground/40 shrink-0 select-none`,children:`Ctrl+↑↓ · adjust value`})]})},fK=new ui,pK=new ui,mK=new ui;async function hK(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 gK(e){let t=await hK(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function _K(e){let t=await hK(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${Yy()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var vK=({noteId:e,noteBlocks:t,sourceRevision:n=0,onIdentityChange:r,onSaved:i,beforeRun:a,onSaveRequest:o,onCommitChange:s,value:c,onChange:l,onDocUpdate:u,onCursorPositionChange:d,onBlur:f,theme:p=`vs`,readonly:m=!1,className:h=``,onStartWorkout:g,onCompleteWorkout:_,onBlocksChange:v,onAddToPlan:y,notePersistence:b,onViewCreated:x,mode:S=`edit`,lineWrapping:w=!0,showLineNumbers:T=!0,enablePreview:E=!0,showFrontmatter:D=!0,enableLinting:O=!0,enableOverlay:A=!1,commands:j,hideDefaultCommands:M=!1,enableInlineRuntime:N=!0,extensions:P,widgetComponents:F,activeSectionId:I,scrollToSectionId:ee,results:te,placeholder:ne})=>{let re=(0,V.useRef)(null),ie=(0,V.useRef)(null),ae=(0,V.useRef)(null),oe=(0,V.useRef)(``);(0,V.useEffect)(()=>{let e=async e=>{if(e.view!==ie.current||!yK(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=bK(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)&&yK(r,n)};if(!r)return null;let{propertyKey:o,from:s}=r,c={"metrics.effort":`effort`,"metrics.equipment":`equipment`,equipment:`equipment`}[o.toLowerCase()];if(c){let e=await UH();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=bK(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}}let l=i.find(e=>e.name.toLowerCase()===o.toLowerCase());if(!l)return null;let u=a.filter(e=>e.type?.toLowerCase()===l.name.toLowerCase());return u.length===0?null:{from:s,options:u.map(e=>({label:e.label,detail:l.label,type:`constant`})),validFor:(e,t,n,r)=>{let i=bK(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}};return dw(e),()=>{fw(e)}},[]);let se=p===`dark`||p===`vs-dark`,ce=YH(ae,b),[L,le]=(0,V.useState)(null),[ue,R]=(0,V.useState)([]),[de,fe]=(0,V.useState)(1),[pe,me]=(0,V.useState)(0),he=I??L,ge=mU(ue,he),[_e,ve]=(0,V.useState)(null),[ye,be]=(0,V.useState)(null),[xe,Se]=(0,V.useState)(!1),Ce=(0,V.useRef)(null),we=(0,V.useRef)(!1),Te=(0,V.useRef)(n??0);(0,V.useEffect)(()=>{Te.current=n??0},[n]);let[Ee,De]=(0,V.useState)(null),Oe=(0,V.useRef)(null),ke=(0,V.useCallback)(async(t,n=!1)=>{let r=ie.current;if(!(!r||we.current)){we.current=!0,De(null);try{let o=await a?.();typeof o==`number`&&(Te.current=o);let s=r.state.field(ZC),c=await hF({noteId:e??C(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:Te.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,C(),e?void 0:`playground`,ce);Ce.current=c,Oe.current=null,Te.current=c.note.sourceRevision,r.dispatch({effects:UC.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),Se(n),be(c.block)}catch(e){De(e instanceof Error?e.message:String(e))}finally{we.current=!1}}},[e,ce,i,a]),Ae=(0,V.useCallback)(()=>{be(null),Se(!1)},[]),je=(0,V.useCallback)(e=>{N&&ke(e,!0)},[N,ke]),Me=(0,V.useRef)(null),Ne=(0,V.useCallback)((e,t)=>{let n=Me.current,r=n!==null&&n.results===t,i=Ce.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(Oe.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&ie.current){let t=ie.current,n=KT(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[Er.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(Me.current={results:t,resultId:a,runBlock:o});let s;try{s=PV(ce).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>_?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{Me.current?.results===t&&(Me.current=null),Oe.current=a},()=>{}),s},[l,_,ce]),Pe=(0,V.useMemo)(()=>{if(M)return[];if(j&&j.length>0)return j;let e=[];return N?e.push({id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:ke}):g&&e.push({id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:g}),e.push({id:`playground`,label:`Playground`,icon:(0,H.jsx)(k,{className:`h-3 w-3`}),splitIcon:(0,H.jsx)(nt,{className:`h-3 w-3`}),splitSuccessIcon:(0,H.jsx)(Zn,{className:`h-3 w-3`}),onClick:e=>{gK(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await _K(e.content);await navigator.clipboard.writeText(t)}}),y&&e.push({id:`plan`,label:`Plan`,icon:(0,H.jsx)(Kt,{className:`h-3 w-3`}),onClick:y}),e},[j,g,y,N,M,ke]),Fe=(0,V.useMemo)(()=>hi({codeLanguages:ZH}),[]),Ie=(0,V.useMemo)(()=>[...T?[Qr(),Hr()]:[],Wr(),pi(),kr(),mi(),...w?[Er.lineWrapping]:[],ri.allowMultipleSelections.of(!0),Dr(),Ti(),Ur(),yi(),fi.highest(yr.of([{key:`Tab`,run:e=>Rr(e.state)!==null&&(Ei(e),!0)},{key:`Enter`,run:e=>{let t=e.state.selection.main,n=bK(e.state,t.head),r=e.state.doc.lineAt(t.head);return!t.empty||n?.value.trim()!==``||r.text.slice(t.head-r.from).trim()?!1:(xr(e),ei(e))}}])),yr.of([...Lr,...$r,...li,...ci,...wi,...di,ti,{key:`Mod-s`,run:()=>(o?.(),!0)},{key:`Ctrl-.`,run:e=>{let t=rU(e.state);if(!t?.focusedMetric)return!1;let n=t.focusedMetric.type;return!new Set([`duration`,`rep`,`rounds`,`distance`,`resistance`]).has(n)&&(cn(()=>Promise.resolve().then(()=>HR).then(()=>{cn(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-D6p7_NoH.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:n})=>{n(t,e)}).catch(()=>{UR.getState().open({placeholder:`Modify metric…`,sources:[]})})}),void 0),!0)}}]),QT,ZC,BC.of({blocks:t??Aa(c,{sourceRevision:Math.max(1,n),registeredWidgets:F?[...F.keys()]:wa}),sourceRevision:Math.max(1,n),rawContent:c}),VC.of(F?[...F.keys()]:wa),QC,jw.of(D),...E||!D?[iT]:[],...E?[ww,Dw,FH(),HH(),xT,hT(),MT]:[],...O?[rw]:[],pw,lw,cw,...A?[$T]:[],hw,zC,oU,...RT,FC,...F&&F.size>0?[jE(F)]:[],sE({executor:XF,onResultSaved:MV,readOnly:m,noteHref:e=>Cz(`blockContentId`in e||`dataType`in e?hI(e):lI(e))}),XH(e,ce),Er.domEventHandlers({blur:()=>(f?.(),!1)}),Er.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(ZC);r?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision}),l(t.rawContent),u?.(e),SK(e.state,v,oe),e.transactions.some(e=>e.isUserEvent(`input`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||s?.()}if(e.selectionSet||e.docChanged){me(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Rr(e.startState)!==null&&Rr(e.state)===null&&bK(e.state,e.state.selection.main.head)?.value===``&&queueMicrotask(()=>{e.view.state===e.state&&ii(e.view)});let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);d?.(n.number,t-n.from+1);let r=ew(e.state);le(r?.id??null),fe(n.number);let{sections:i}=e.state.field(ZC);R(i)}}),ri.readOnly.of(m),Er.editable.of(!m),...ne?[bi(ne)]:[]],[l,d,f,u,v,r,m,o,s,T,w,E,D,O,A,e,ce,F,ne]);return(0,V.useEffect)(()=>{let e=re.current;if(!e)return;let t=ri.create({doc:c,extensions:[...Ie,fK.of(PC(se)),pK.of(Fe),mK.of([]),...P??[]]}),n=new Er({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{n.hasFocus&&i?.scale===1&&i.height<window.innerHeight&&n.dispatch({effects:Er.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})})})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),ie.current=n,ve(n),e.__codemirrorView=n,x?.(n);let{sections:s}=n.state.field(ZC);R(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;fe(l);let u=ew(n.state);le(u?.id??null);let d=n.state.field(ZC);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),SK(n.state,v,oe),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,ve(null),n.destroy()}},[]),(0,V.useEffect)(()=>{let e=ie.current;if(!e)return;let r=e.state.field(ZC);c===r.rawContent?t&&n!==r.sourceRevision&&e.dispatch({effects:UC.of({blocks:t,sourceRevision:n})}):e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},...t?{effects:WC.of({rawContent:c,blocks:t,sourceRevision:n})}:{}})},[c,t,n]),(0,V.useEffect)(()=>{ie.current&&ie.current.dispatch({effects:fK.reconfigure(PC(se))})},[se]),(0,V.useEffect)(()=>{if(ie.current){let e=[];ie.current.dispatch({effects:[Xr.reconfigure.of([...Ie,fK.of(PC(se)),pK.of(Fe),mK.of(e),...P??[]])]})}},[Ie,P,S,se,Fe]),(0,V.useEffect)(()=>{m||ie.current?.focus()},[m]),(0,V.useEffect)(()=>{if(ee&&ie.current){let e=ie.current,t=e.state.doc.toString().split(`
160
+ `),n=-1,r=ee.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,`-`)===ee}return!1}),n>=0&&n<t.length){let t=e.state.doc.line(n+1).from;e.dispatch({selection:{anchor:t,head:t},effects:[Er.scrollIntoView(t,{y:`start`,yMargin:20})]})}}},[ee]),(0,H.jsxs)(`div`,{ref:re,className:`cm-note-editor relative w-full min-w-0 ${h}`,children:[A&&(0,H.jsx)(lU,{view:_e??ie.current,widths:ge.widths,activeSectionId:he,renderSlot:t=>{if(!D&&t.sectionType===`frontmatter`)return null;if(t.sectionType===`time`||t.sectionType===`log`)return(0,H.jsx)(RU,{noteId:e,sectionId:t.sectionId,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,cursorLine:de,docVersion:t.docVersion,commands:Pe,extendedResults:te,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(ZC),n=e.find(e=>e.id===t.sectionId);return(0,H.jsx)(vU,{sectionId:t.sectionId,section:n,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,docVersion:t.docVersion})}return t.sectionType===`widget`&&t.widgetName?(0,H.jsx)(zU,{sectionId:t.sectionId,widgetName:t.widgetName,view:t.view,registry:F??new Map,docVersion:t.docVersion}):(0,H.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,H.jsx)(`div`,{className:`font-medium text-foreground`,children:t.sectionType})})},cursorLine:de}),Ee&&(0,H.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[`Workout not started. `,Ee,` Your draft is kept.`]}),!A&&Pe.length>0&&(0,H.jsx)(iK,{view:_e??ie.current,commands:Pe}),(0,H.jsx)(dK,{view:_e??ie.current,cursorVersion:pe}),ye&&ie.current&&(0,H.jsx)(ZG,{block:ye,view:_e??ie.current,onClose:Ae,onCompleteWorkout:Ne,autoStart:xe}),(0,H.jsx)(aK,{sections:ue,isRuntimeActive:ye!==null,editorState:(_e??ie.current)?.state??null,onSelectBlock:je})]})};function yK(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 bK(e,t){if(!yK(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 xK(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=Is().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(ZC).noteBlocks[e.id]?.version??1,createdAt:Date.now(),widgetIds:{}}}function SK(e,t,n){if(!t)return;let r=e.field(ZC).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>xK(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 CK({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,V.useRef)([]),E=(0,V.useCallback)(e=>{T.current=e,a?.(e)},[a]),D=(0,V.useCallback)(()=>{v?.onRun(n,T.current[0]??null)},[v,n]),O=(0,H.jsxs)(H.Fragment,{children:[y,v&&(0,H.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,H.jsx)(Ht,{size:11,fill:`currentColor`}),v.label??`Run`]})]});return(0,H.jsx)(PH,{title:e,subtitle:t,onReset:_,headerActions:O,className:S,children:(0,H.jsxs)(`div`,{className:`flex h-full flex-col min-h-0`,children:[b,(0,H.jsxs)(`div`,{ref:w,className:U(`relative flex-1 min-h-0`,C),children:[(0,H.jsx)(vK,{noteId:i,value:n,onChange:r,onBlocksChange:E,theme:o,readonly:s,showLineNumbers:c,enableOverlay:l,enableInlineRuntime:u,enablePreview:d,showFrontmatter:f,enableLinting:p,commands:m,hideDefaultCommands:h,onViewCreated:g,className:`h-full`}),x]})]})})}function wK({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,H.jsx)(`div`,{className:`h-full`,style:{opacity:t,transition:`opacity 180ms ease`},children:(0,H.jsx)(CK,{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,H.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,H.jsx)(`span`,{children:`Try editing this example ↓`}),e===n?null:(0,H.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 TK(e,t){return e>=t?`split`:`stack`}function EK(e,t){let n=(0,V.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:TK(t,n)}},[e]),[r,i]=(0,V.useState)(n);return(0,V.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:TK(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 DK=e=>Math.max(0,Math.min(1,e)),OK=(e,t,n)=>e+(t-e)*n,kK=e=>1-(1-e)**2;function AK(e,t){return e===``||t===e}var jK={id:``,range:[0,1]};function MK(e,t){if(!t||t.length===0)return{index:-1,stage:jK,t:0,ring:null};let n=DK(e),r=t.map(e=>({...e,start:DK(Math.min(e.range[0],e.range[1])),end:DK(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]??jK,o=(a.end??1)-(a.start??0),s=o>0?DK((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 NK(e,t,n){let r=t-n;return{progress:r>0?DK(-e/r):0,reached:e<=0,inView:e<n&&e+t>0}}function PK(e,t){let n=t/2;for(let t of e)if(t.top<=n&&t.bottom>n)return t.id;return null}var FK=(0,V.createContext)(null);function IK(){return(0,V.useContext)(FK)}function LK({children:e}){let t=(0,V.useRef)(new Map),n=(0,V.useRef)(new Map),r=(0,V.useRef)(null),i=(0,V.useRef)(0),[a,o]=(0,V.useState)(null),s=(0,V.useRef)(null),c=(0,V.useCallback)(e=>{r.current?.gateId===e&&(r.current=null,o(null))},[]),l=(0,V.useCallback)((e,t)=>{r.current={gateId:e,segmentId:t},o(e)},[]),u=(0,V.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=PK(l,e);if(u!==s.current){s.current=u;let e=r.current;e&&e.segmentId!==u&&(r.current=null,o(null))}n.current.forEach((t,n)=>{let r=a.get(n);if(!r||r.height-e<=0)return;let i=NK(r.top,r.height,e);t.onMeasure({slice:MK(i.progress,t.getStages()),progress:i.progress,reached:i.reached})})},[]),d=(0,V.useCallback)(()=>{i.current||=requestAnimationFrame(u)},[u]);(0,V.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,V.useCallback)((e,n)=>(t.current.set(e,n),d(),()=>{t.current.delete(e)}),[d]),p=(0,V.useCallback)((e,t)=>(n.current.set(e,t),d(),()=>{n.current.delete(e)}),[d]),m=(0,V.useCallback)(()=>u(),[u]),h=(0,V.useMemo)(()=>({registerAnchor:f,registerDriver:p,resync:m,capturedGateId:a,captureGate:l,releaseGate:c}),[f,p,m,a,l,c]);return(0,H.jsx)(FK.Provider,{value:h,children:e})}function RK(e,t){let n=IK()?.registerAnchor;(0,V.useEffect)(()=>{if(n)return n(e,()=>t.current)},[n,e,t])}function zK({gateId:e,segmentId:t,className:n,children:r}){let i=IK(),a=(0,V.useRef)(null),[o,s]=(0,V.useState)(!1);if((0,V.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,H.jsx)(`div`,{className:n,children:r});let c=i.capturedGateId===e?`captured`:`yield`;return(0,H.jsxs)(`div`,{"data-scroll-gate":c,"data-gate-id":e,className:`${n??``} flex flex-col`,onFocus:n=>{let r=n.target;r instanceof HTMLElement&&r.closest(`input:not([readonly]):not([disabled]), textarea:not([readonly]):not([disabled]), select:not([disabled]), [contenteditable="true"]`)&&i.captureGate(e,t??null)},onBlur:t=>{(!(t.relatedTarget instanceof Node)||!t.currentTarget.contains(t.relatedTarget))&&i.releaseGate(e)},children:[(0,H.jsx)(`div`,{ref:a,className:`relative min-h-0 flex-1`,children:r}),(o||c===`captured`)&&(0,H.jsx)(`button`,{type:`button`,className:`min-h-11 self-start rounded px-3 py-2 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`,"aria-label":`Scroll ${e.replace(/-/g,` `)} content`,"aria-pressed":c===`captured`,onClick:()=>c===`captured`?i.releaseGate(e):i.captureGate(e,t??null),onKeyDown:t=>{t.key===`Escape`&&i.releaseGate(e)},children:c===`captured`?`Scroll page`:`Scroll panel`})]})}function BK({trackRef:e,height:t,stages:n,activeIndex:r,pane:i,captions:a,status:o,segmentId:s,testId:c,className:l}){let[u,d]=(0,V.useState)(null),f=EK(104,u).mode===`split`,p={status:o,pips:(0,H.jsx)(`div`,{className:`flex items-center gap-1.5`,"aria-hidden":`true`,children:n.map((e,t)=>{let n=r===t;return(0,H.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,H.jsx)(`section`,{ref:e,"data-testid":c,className:l?`relative ${l}`:`relative`,style:{height:t},children:(0,H.jsx)(MH.Provider,{value:p,children:(0,H.jsx)(`div`,{className:`sticky top-[65px] flex h-[calc(100dvh-65px)] flex-col overflow-hidden lg:top-[104px] lg:h-[calc(100dvh-104px)]`,children:(0,H.jsxs)(`div`,{ref:d,className:`mx-auto flex min-h-0 w-full max-w-[1500px] 2xl:max-w-[1720px] flex-1 px-5 pt-2 pb-5 lg:px-10 lg:pt-3 xl:px-16 xl:pb-8 2xl:pb-10 ${f?`flex-row items-stretch gap-[clamp(20px,2.5vw,56px)] xl:gap-12 2xl:gap-16`:`flex-col gap-6 xl:gap-8`}`,children:[(0,H.jsx)(`div`,{className:`relative min-h-0 min-w-0 flex-[3_1_0%]`,children:i}),(0,H.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-[2_1_0%] flex-col`,children:s?(0,H.jsx)(zK,{gateId:`${s}-captions`,segmentId:s,className:`relative min-h-0 flex-1`,children:a}):(0,H.jsx)(`div`,{className:`relative min-h-0 flex-1`,children:a})})]})})})})}function VK(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 HK(e,t,n=`smooth`){let r=VK(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 UK(e,t,n,r){let[i,a]=(0,V.useState)(()=>MK(0,n)),[o,s]=(0,V.useState)(!1),c=(0,V.useRef)(0),l=(0,V.useRef)(i),u=(0,V.useRef)(new Set),d=(0,V.useRef)(0),f=(0,V.useRef)(t);f.current=t;let p=IK(),m=p?.registerDriver,h=(0,V.useRef)(p);h.current=p;let g=(0,V.useId)(),_=r??g,v=(0,V.useRef)(n);v.current=n;let y=(0,V.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,V.useCallback)(()=>{if(d.current=0,f.current)return;let t=e.current;if(!t)return;let n=t.getBoundingClientRect(),r=n.height-window.innerHeight;if(r<=0)return;let i=Math.max(0,Math.min(1,-n.top/r));s(n.top<=0),y(MK(i,v.current),i)},[e,y]),x=(0,V.useCallback)(()=>{if(h.current){h.current.resync();return}b()},[b]),S=(0,V.useCallback)(()=>{d.current||=requestAnimationFrame(x)},[x]);(0,V.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,V.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,V.useCallback)(e=>(u.current.add(e),e(l.current,c.current),()=>{u.current.delete(e)}),[]),w=(0,V.useCallback)(()=>{x()},[x]);return{slice:i,progress:c.current,runwayReached:o,subscribe:C,resync:w}}var WK={reference:!0},GK={start:[[`fences`,`first-workout`],[`measurements`,`actions-comments`],[`system`,`try-it`]],protocols:[[`countdown-countup`,`required-rest`],[`amrap`,`emom`],[`tabata-intervals`,`caps`,`distance-intervals`,`try-it`]],structure:[[`rounds`,`rep-schemes`,`sets`],[`nesting`,`rep-math`,`named-sections`,`try-it`]],metrics:[[`planned-vs-recorded`,`custom-metrics`],[`capture`,`session-rpe`],[`calculated`,`try-it`]],clock:[[`run-next`,`pause-skip`],[`capture-prompts`,`casting`,`provenance`,`try-it`]],wql:[[`planes`,`aggregate`,`filters`,`sources`],[`windows`,`grouping-rollup`,`joins`],[`content`,`pipes`,`try-it`]],dashboards:[[`note-frontmatter`,`avg-tis`,`weekly-tonnage`,`widgets`],[`composer`,`cookbook`,`seeded-boards`,`try-it`]],sessions:[[`intent`,`full-session`],[`nested`,`partner`,`swimming`],[`barbell-cycling`,`climbing`,`try-it`]]};function KK(e,t){let n=e.filter(e=>!WK[e.id]),r=e.filter(e=>WK[e.id]);if(n.length===0)return{groups:[],tail:r};let i=t?GK[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 qK(e){let t=Math.max(1,e.length);return e.map((e,n)=>({id:e.id,range:[n/t,(n+1)/t]}))}var JK=[{src:`/images/hero/editing.png`,alt:`WhiteboardScript editor with live syntax highlighting and inline previews`,eyebrow:`Write`,title:`Type your workout in plain Markdown.`,caption:"Movements, reps, time caps, and rounds — fenced in a familiar ```time block. No drag-and-drop. No proprietary DSL."},{src:`/images/hero/timer.png`,alt:`Live runtime timer HUD counting down an interval with active round and rest indicators`,eyebrow:`Run`,title:`Press Run. The compiler takes over.`,caption:`Your Markdown becomes a live wallclock. The JIT engine dispatches rounds, counts reps, and tracks rest — all offline.`},{src:`/images/hero/journal.png`,alt:`Unified Library listing journal notes, Catalog sessions, and dated posts`,eyebrow:`Library`,title:`Browse Notes, Sessions, and Posts in one Library.`,caption:`Your dated journal entries and preloaded Catalog benchmarks live in one unified surface. Search, filter by source, or clone to today’s entry.`},{src:`/images/hero/results.png`,alt:`WQL Metric Explorer displaying volume trends and embedded dashboard blocks`,eyebrow:`Query`,title:`Ask questions with Wod Query Language (WQL).`,caption:`Aggregate volume, track TIS intensity trends, or embed live query and dashboard blocks directly in your Markdown notes.`}];function YK({slides:e=JK,className:t}){let n=(0,V.useRef)(null),[r,i]=(0,V.useState)(0);(0,V.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,H.jsxs)(`div`,{className:U(`relative w-full`,t),children:[(0,H.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,H.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,H.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,H.jsx)(`img`,{src:t.src,alt:t.alt,loading:n===0?`eager`:`lazy`,className:`h-full w-full object-cover`})}),(0,H.jsxs)(`div`,{className:`flex w-full flex-col gap-2 sm:w-1/2 sm:gap-3`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-[0.24em] text-primary/80`,children:t.eyebrow}),(0,H.jsx)(`h3`,{className:`text-2xl font-black tracking-[-0.04em] text-foreground sm:text-3xl`,children:t.title}),(0,H.jsx)(`p`,{className:`text-sm leading-7 text-muted-foreground sm:text-base`,children:t.caption}),(0,H.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground`,children:[(0,H.jsxs)(`span`,{className:`text-primary`,children:[`Step `,n+1]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,H.jsx)(`span`,{children:e.length})]})]})]},t.src))}),(0,H.jsx)(`div`,{className:`mt-4 flex items-center justify-center gap-2`,children:e.map((e,t)=>(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Go to slide ${t+1}: ${e.title}`,"aria-current":t===r?`true`:`false`,className:U(`h-2 rounded-full transition-all`,t===r?`w-8 bg-primary`:`w-2 bg-border hover:bg-muted-foreground/40`)},e.src))})]})}var XK=`wodwiki:text-filter-navigation`,ZK=({paramName:e=`q`,placeholder:t=`Search…`,autoFocus:n=!1,className:r,navigationScope:i,inputTestId:a})=>{let[o,s]=Gt(e,{defaultValue:``}),c=i??e,l=(0,V.useRef)(null);return(0,V.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,H.jsxs)(`div`,{className:U(`flex items-center gap-3 px-6 lg:px-10 pb-3`,r),children:[(0,H.jsx)(en,{className:`size-5 text-muted-foreground shrink-0`}),(0,H.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(XK,{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,H.jsx)(`button`,{onClick:()=>s(``),"aria-label":`Clear`,className:`text-muted-foreground hover:text-foreground transition-colors text-lg leading-none`,children:`×`})]})};function QK(e){let t=[],n=!1;for(let r of e){if(r.trim()===`---`){n=!n;continue}n||t.push(r)}return t}function $K(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 eq(e){return new Date(e).toISOString().slice(0,10)}function tq(e,t){let n=t.trim().toLowerCase();return!n||e.name.toLowerCase().includes(n)||e.content.toLowerCase().includes(n)||e.date!==void 0&&eq(e.date).includes(n)}function nq(e){if(!e)return null;let t=QK(Db(e).split(`
161
+ `)).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```"))[0];return t?$K(t):null}var rq=({category:e,workoutItems:t,onSelect:n,showSearch:r=!0,variant:i=`card`,className:a,navigationScope:o=`q`,getItemActions:s})=>{let[c]=Gt(`q`,{defaultValue:``}),[l,u]=(0,V.useState)(0),[d,f]=(0,V.useState)(0),p=(0,V.useRef)([]),m=(0,V.useMemo)(()=>t.filter(t=>t.category===e&&t.name.toLowerCase()!==`readme`).filter(e=>tq(e,c)),[t,e,c]),h=(0,V.useMemo)(()=>m.map(e=>({item:e,preview:nq(e.content),actions:s?.(e)??[{id:`open`,label:`Open`,onSelect:n}]})),[m,s,n]);return(0,V.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,V.useEffect)(()=>{p.current=[]},[h]),(0,V.useEffect)(()=>{u(0),f(0)},[c]),(0,V.useEffect)(()=>{(p.current[l]?.[d])?.scrollIntoView({block:`nearest`,inline:`nearest`})},[d,l]),(0,V.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(XK,e),()=>{window.removeEventListener(XK,e)}},[h,o,d,l]),(0,H.jsxs)(`div`,{className:U(`flex flex-col`,i===`card`&&`rounded-3xl border border-border bg-card overflow-hidden shadow-2xl shadow-black/5`,a),children:[r?(0,H.jsx)(`div`,{className:`border-b border-border/60 bg-background/95 backdrop-blur-md`,children:(0,H.jsx)(ZK,{placeholder:`Filter collection workouts…`,className:`pt-3`,navigationScope:o})}):null,h.length===0?(0,H.jsx)(`div`,{className:`px-6 py-10 text-sm font-medium text-muted-foreground`,children:`No workouts found.`}):(0,H.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,H.jsx)(`div`,{role:`option`,"aria-selected":n,className:U(`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,H.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:U(`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,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-10 rounded-xl bg-muted flex items-center justify-center transition-colors`,children:(0,H.jsx)(ce,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate uppercase tracking-tight`,children:e.item.displayName??e.item.name}),e.preview?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground font-medium truncate mt-1`,children:e.preview}):null]}),e.item.date===void 0?null:(0,H.jsx)(`span`,{className:`shrink-0 self-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:HP(new Date(e.item.date))}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground shrink-0 transition-opacity`})]}):r.label},r.id)})},e.item.id)})})]})};function iq(){return(0,V.useEffect)(()=>{WF().catch(e=>console.warn(`[queryService] page source population failed`,e))},[]),(0,V.useSyncExternalStore)(qF,KF)}function aq(e,t){let n=e.find(e=>e.key===t&&!e.negate);return n&&n.values.length===1?n.values[0].value:null}function oq(e){let t=e.trim();if(!t.startsWith(`:`))return null;let n=Y(t);if(n.error||!tm(n))return null;let r=`?q=${encodeURIComponent(t)}`;switch(n.target){case`effort`:return`/efforts${r}`;case`session`:case`segment`:case`event`:return`/sessions${r}`;case`note`:case`block`:{let e=aq(n.filters,`notebook`)??aq(n.filters,`catalog`);if(e){let t=xa(e);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:`/c/${encodeURIComponent(t)}${r}`}let t=aq(n.filters,`source`);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:t===`feeds`||t===`notebooks`||t===`notebook`||t===`guides`?`/feeds${r}`:aq(n.filters,`type`)===`dashboard`?`/dashboards${r}`:`/journal${r}`}default:return null}}var sq=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 cq(e){let t=e.split(`.`).pop()?.split(`?`)[0]?.toLowerCase()??``;return sq.has(t)}function lq(e){return/^https?:\/\//.test(e)||e.startsWith(`//`)}function uq({queryText:e,widgetType:t,widgetError:n}){return iq()?(0,H.jsx)(`div`,{className:`my-5 not-prose`,children:(0,H.jsx)(OC,{query:e,widgetType:t,widgetError:n,executor:XF,readOnly:!0,noteHref:e=>Cz(`blockContentId`in e||`dataType`in e?hI(e):lI(e))})}):(0,H.jsx)(`div`,{className:`my-5 not-prose text-xs text-muted-foreground py-2`,children:`Loading…`})}function dq(e){let{meta:t,body:n}=Sb(e);return Object.keys(t).length===0&&n===e?{fields:null,body:e}:{fields:t,body:n.trim()}}var fq={table({children:e}){return(0,H.jsx)(`div`,{className:`my-6 overflow-x-auto rounded-xl border border-border`,children:(0,H.jsx)(`table`,{className:`w-full text-sm border-collapse`,children:e})})},thead({children:e}){return(0,H.jsx)(`thead`,{className:`bg-muted/50 text-left`,children:e})},tbody({children:e}){return(0,H.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e})},tr({children:e}){return(0,H.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e})},th({children:e}){return(0,H.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,H.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,H.jsxs)(`figure`,{className:`my-6`,children:[(0,H.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,H.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=oq(e);if(r)return(0,H.jsx)(Wn,{to:r,className:`underline underline-offset-2 transition-colors text-primary hover:text-primary/70`,children:t})}let r=lq(n),i=cq(n);return(0,H.jsxs)(`a`,{href:n,rel:r?`noopener noreferrer`:void 0,target:r||i?`_blank`:void 0,className:U(`underline underline-offset-2 transition-colors`,i?`text-primary font-medium`:`text-primary hover:text-primary/70`),children:[t,r&&(0,H.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`↗`}),i&&!r&&(0,H.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`⬇`})]})},code({children:e,className:t}){let n=t?.replace(`language-`,``)??``,r=typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``);if(!t&&!r.includes(`
162
+ `))return(0,H.jsx)(`code`,{className:`px-1.5 py-0.5 rounded-md bg-muted font-mono text-[0.85em] text-foreground`,children:e});if(n===`query`||n.startsWith(`query:`)||n.startsWith(`query `)){let t=(typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``)).trim(),r=n.replace(/^query[:\s]?/,``).trim(),i=r?Jg(r):void 0;return(0,H.jsx)(uq,{queryText:t,widgetType:i?.type,widgetError:i?.error})}return(0,H.jsxs)(`div`,{className:`my-5 rounded-xl overflow-hidden border border-border`,children:[n&&(0,H.jsx)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-muted border-b border-border`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black tracking-widest uppercase text-muted-foreground`,children:n})}),(0,H.jsx)(`pre`,{className:`overflow-x-auto p-4 bg-muted/30`,children:(0,H.jsx)(`code`,{className:`font-mono text-sm text-foreground`,children:e})})]})},h1({children:e,id:t}){return(0,H.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,H.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,H.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,H.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,H.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,H.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,H.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,H.jsx)(`li`,{className:`leading-relaxed`,children:e})},blockquote({children:e}){return(0,H.jsx)(`blockquote`,{className:`my-5 pl-4 border-l-2 border-primary/40 text-muted-foreground italic text-sm`,children:e})},hr(){return(0,H.jsx)(`hr`,{className:`my-8 border-border/50`})},strong({children:e}){return(0,H.jsx)(`strong`,{className:`font-black text-foreground`,children:e})},em({children:e}){return(0,H.jsx)(`em`,{className:`italic text-foreground/80`,children:e})}},pq={...fq,p({children:e}){return(0,H.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=V.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,H.jsxs)(`span`,{className:`flex flex-col select-none mt-4 w-full gap-5 sm:gap-7`,children:[(0,H.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,H.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Markdown`}),`.`]}),(0,H.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,H.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,H.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,H.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Analytics`}),`.`]})]}):(0,H.jsx)(`strong`,{className:`font-black text-foreground`,children:e})}},mq={...fq,p({children:e}){return(0,H.jsx)(`p`,{className:`text-base lg:text-lg font-medium text-foreground/75 leading-relaxed my-4 first:mt-0`,children:e})}},hq=[Un];function gq(e){return e.startsWith(`:`)?e:Pn(e)}function _q(e){return e.type===`text`&&typeof e.value==`string`?e.value:(e.children??[]).map(_q).join(``)}function vq(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu,``).replace(/ /g,`-`).replace(/-+/g,`-`)||`heading`}var yq=()=>e=>{let t=new Map,n=e=>{if(e.tagName&&/^h[1-6]$/.test(e.tagName)){let n=vq(_q(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 bq({fields:e}){let t=Object.entries(e);return t.length===0?null:(0,H.jsxs)(`div`,{className:`my-6 rounded-xl border border-border bg-muted/30 overflow-hidden`,children:[(0,H.jsx)(`div`,{className:`px-4 py-2 border-b border-border bg-muted/50`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black tracking-[0.2em] uppercase text-muted-foreground`,children:`Metadata`})}),(0,H.jsx)(`dl`,{className:`divide-y divide-border/50`,children:t.map(([e,t])=>(0,H.jsxs)(`div`,{className:`flex items-baseline gap-4 px-4 py-2`,children:[(0,H.jsx)(`dt`,{className:`text-[11px] font-semibold text-muted-foreground uppercase tracking-wide min-w-[100px] shrink-0`,children:e}),(0,H.jsx)(`dd`,{className:`text-sm text-foreground break-words`,children:Array.isArray(t)?t.join(`, `):String(t)})]},e))})]})}var xq={default:fq,heroLead:pq,heroBody:mq};function Sq({prose:e,className:t,variant:n=`default`}){if(!e)return null;let{fields:r,body:i}=dq(e);return(0,H.jsxs)(`div`,{className:U(`prose-canvas`,t),children:[r&&(0,H.jsx)(bq,{fields:r}),i&&(0,H.jsx)(gn,{remarkPlugins:hq,rehypePlugins:[yq],urlTransform:gq,components:xq[n],children:i})]})}var Cq=({activations:e,fullBleed:t,runState:n,deps:r})=>{if(e.length===0)return null;let i=e[0];if(YM(i)&&n){let a=e.slice(1),o=n.isReconnect?(0,H.jsxs)(`button`,{onClick:n.onReconnect,className:U(`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,H.jsx)(Ye,{className:`size-3.5`}),`View`]}):(0,H.jsxs)(`button`,{type:`button`,onClick:n.onRun,className:U(`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||Ht;return(0,H.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,H.jsx)(`span`,{children:i.label})]});return(0,H.jsxs)(`div`,{className:U(`flex flex-wrap items-center gap-4 mt-8`,t&&`justify-center`),children:[o,a.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(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,H.jsx)(`div`,{className:U(`flex flex-wrap gap-4 mt-8`,t&&`justify-center`),children:e.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,r),className:U(`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))})},wq=({examples:e,activeIndex:t,onSelect:n})=>e.length===0?null:(0,H.jsx)(`div`,{className:`mt-6 rounded-2xl border border-border/70 bg-card/80 backdrop-blur-sm`,children:(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-3`,children:e.map((e,r)=>{let i=r===t,a=e.anchor===!0&&!i,o=!!e.badge&&a;return(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(r),"aria-current":i?`true`:void 0,className:U(`relative rounded-full px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] transition-all active:scale-95`,i?`bg-primary text-primary-foreground shadow-lg shadow-primary/25`:a?`border border-brand bg-brand/5 text-brand-deep hover:bg-brand/10 dark:text-brand-light`:`border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground`),children:[e.label,o?(0,H.jsx)(`span`,{className:`ml-2 inline-block rounded-pill bg-brand px-1.5 py-0.5 align-middle text-[8px] font-black leading-none tracking-[0.12em] text-background`,children:e.badge}):null]},`${e.label}-${r}`)})})}),Tq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`path`,{d:`M35 35 L65 35 L65 45 L45 45 L45 65 L35 65 Z`,fill:`url(#struct-grad)`}),(0,H.jsx)(`path`,{d:`M55 45 L65 45 L65 65 L45 65 L45 55 L55 55 Z`,fill:`url(#struct-grad)`,opacity:`0.7`})]}),Eq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`5`,fill:`url(#proto-grad)`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`15`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`2`,strokeDasharray:`4 2`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`50`,r:`25`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`1`,opacity:`0.5`}),(0,H.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:`25`,stroke:`url(#proto-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),Dq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`complex-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#F50057`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#D500F9`,stopOpacity:1}})]})}),(0,H.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,H.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)`})]}),Oq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsxs)(`defs`,{children:[(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]}),(0,H.jsxs)(`filter`,{id:`glow`,x:`-20%`,y:`-20%`,width:`140%`,height:`140%`,children:[(0,H.jsx)(`feGaussianBlur`,{stdDeviation:`3`,result:`blur`}),(0,H.jsx)(`feComposite`,{in:`SourceGraphic`,in2:`blur`,operator:`over`})]})]}),(0,H.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,H.jsx)(`path`,{d:`M55 20 L30 55 L45 55 L40 85 L70 45 L55 45 Z`,fill:`url(#basics-grad)`,filter:`url(#glow)`})]}),kq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`text`,{x:`50`,y:`65`,fontFamily:`monospace`,fontSize:`40`,fontWeight:`bold`,fill:`url(#basics-grad)`,textAnchor:`middle`,children:`10`})]}),Aq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`rect`,{x:`30`,y:`30`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,H.jsx)(`rect`,{x:`30`,y:`45`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,H.jsx)(`rect`,{x:`30`,y:`60`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`})]}),jq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.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`})]}),Mq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,H.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,H.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,H.jsx)(`text`,{x:`50`,y:`30`,fontFamily:`monospace`,fontSize:`12`,fill:`url(#struct-grad)`,textAnchor:`middle`,children:`21-15-9`})]}),Nq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`path`,{d:`M35 35 H65 V55 L50 70 L35 55 Z`,fill:`url(#proto-grad)`}),(0,H.jsx)(`circle`,{cx:`50`,cy:`45`,r:`4`,fill:`#0b1326`})]}),Pq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,H.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,H.jsx)(`rect`,{x:`30`,y:`60`,width:`10`,height:`15`,fill:`url(#metric-grad)`}),(0,H.jsx)(`rect`,{x:`45`,y:`40`,width:`10`,height:`35`,fill:`url(#metric-grad)`}),(0,H.jsx)(`rect`,{x:`60`,y:`25`,width:`10`,height:`50`,fill:`url(#metric-grad)`})]}),Fq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,H.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,H.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`})]}),Iq=e=>(0,H.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,H.jsx)(`defs`,{children:(0,H.jsxs)(`linearGradient`,{id:`dialect-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,H.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#76FF03`,stopOpacity:1}}),(0,H.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00E676`,stopOpacity:1}})]})}),(0,H.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,H.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 Lq(e){switch(e){case`trophy`:return Oq;case`dumbbell`:return ce;case`timer`:return Eq;case`play`:return Ht;case`blocks`:return Tq;case`puzzle`:return Dq;case`activity`:return Pq;case`file-text`:return Iq;default:return Ue}}function Rq(e){switch(e){case`basics-movement`:return Oq;case`basics-reps`:return kq;case`basics-load`:return Aq;case`structure-rounds`:case`complex-rounds`:case`protocols-rounds`:return jq;case`structure-repscheme`:return Mq;case`protocols-timer`:case`complex-time`:return Eq;case`protocols-tag`:return Nq;case`metrics-custom`:return Pq;case`metrics-calc`:return Fq;case`dialects-log`:case`dialects-climb`:return Iq;default:return null}}function zq({quest:e,onClick:t,className:n,compact:r=!1,disabled:i=!1}){let a=Rq(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:U(`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,H.jsxs)(H.Fragment,{children:[a?(0,H.jsxs)(`span`,{className:U(`relative shrink-0 mt-0.5`,r?`size-5`:`size-6`),children:[(0,H.jsx)(a,{className:`w-full h-full`}),e.isCompleted&&(0,H.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,H.jsx)(Zn,{className:`size-2`,strokeWidth:3})})]}):(0,H.jsx)(`span`,{className:U(`mt-0.5 shrink-0`,e.isCompleted?`text-primary`:`text-muted-foreground/50`),"aria-hidden":`true`,children:e.isCompleted?(0,H.jsx)(yn,{className:r?`size-3.5`:`size-4`}):(0,H.jsx)(Pt,{className:r?`size-3.5`:`size-4`})}),(0,H.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`p`,{className:U(`font-semibold`,e.isCompleted?`text-foreground line-through decoration-primary/40`:`text-foreground`,r&&`text-xs`),children:e.label}),e.desc&&!r&&(0,H.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:e.desc}),(0,H.jsx)(`p`,{"data-testid":`challenge-hint-${e.id}`,className:U(`mt-1 text-xs`,e.isCompleted||e.result?.pass?`text-primary/80`:`text-muted-foreground`),children:s})]})]});return t?(0,H.jsx)(`button`,{type:`button`,onClick:t,disabled:i,...c,children:l}):(0,H.jsx)(`div`,{...c,children:l})}function Bq(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 Vq=({section:e,idx:t,prose:n,blockId:r,keySuffix:i,showHeading:a=!0,showEyebrow:o=!0,renderButtons:s=!0,isActive:c=!1,hasViewDef:l=!1,runState:u,deps:d,onExampleSelect:f,selectedExampleIndex:p,chapters:m=[],challengeQuests:h=[],isCollection:g=!1,collectionSlug:_=null,workoutItems:v=[],handleSelectWorkout:y,onScrollToSection:b,variant:x=`default`})=>{let S=!!e.isFullBleed,C=!!e.isDark&&x!==`caption`,w=e.density,T=tP[e.theme||`slate`]??tP.slate,E=e.examples??[],D=t===-1,O=V.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`?Bq(a.text.trim()):{lead:``,rest:``},c=e.proseChunks.slice(n+1);return(0,H.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,H.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,H.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,H.jsxs)(`div`,{className:`relative max-w-2xl w-full text-center`,children:[o&&(0,H.jsx)(Sq,{prose:o,variant:`heroLead`,className:`mb-5`}),s&&(0,H.jsx)(Sq,{prose:s,variant:`heroBody`,className:`mb-2`}),c.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,H.jsx)(Sq,{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,H.jsx)(`div`,{className:`my-4 flex justify-center`,children:(0,H.jsx)(zq,{quest:n,onClick:()=>b?.(r),compact:!0})},`hero-challenge-${t}`):null}return null}),t.length>0&&(0,H.jsx)(Cq,{activations:t.map((e,t)=>JM(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,H.jsxs)(`div`,{id:r,"data-section-id":i==="default"||i===`before-workouts`?e.id:void 0,className:U(`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,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`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,H.jsx)(`div`,{className:U(`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,H.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,H.jsxs)(`div`,{className:U(`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,H.jsx)(`div`,{className:`mb-4 flex items-center gap-2 select-none min-h-[14px]`,children:O.quest.isCompleted?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse`}),`Challenge Complete`]}):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-muted-foreground/80 bg-muted/60 px-2 py-0.5 rounded-full border border-border/50`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500`}),O.chapterTitle,`: Challenge Pending`]})}),a?(0,H.jsx)(`h2`,{className:U(`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,H.jsx)(Sq,{prose:n,className:t===0?`mb-6`:`mt-4 mb-6`},`prose-${t}`):null}if(e.kind===`button`)return(0,H.jsx)(Cq,{activations:[JM(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,H.jsx)(`div`,{className:`my-6`,children:(0,H.jsx)(YK,{})},`hero-carousel-${t}`);if(e.widget===`workouts-list`&&g&&_&&y)return(0,H.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card my-6`,children:(0,H.jsx)(`div`,{className:`w-full mx-auto`,children:(0,H.jsx)(rq,{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,H.jsx)(`div`,{className:`my-4`,children:(0,H.jsx)(zq,{quest:n,onClick:()=>b?.(r),compact:!0})},`challenge-${t}`):null}return null}),E.length>0?(0,H.jsx)(wq,{examples:E,activeIndex:Math.min(p,E.length-1),onSelect:t=>f(e,t)}):null,s&&A?(0,H.jsx)(Cq,{activations:e.buttons.map((e,t)=>JM(e,t)),fullBleed:S,runState:l?u:void 0,deps:d}):null]})]},`${e.id}-${i}`)};function Hq({sections:e,activeIndex:t,part:n,args:r}){return(0,H.jsx)(`div`,{className:`h-full min-h-0 pr-1`,"data-testid":`guide-captions-${n}`,children:e.map((e,n)=>{let i=n===t;return(0,H.jsx)(`div`,{className:`absolute inset-0 min-h-0 overflow-y-auto transition-opacity duration-300 ${i?`opacity-100`:`pointer-events-none invisible opacity-0`}`,"aria-hidden":!i,children:(0,H.jsx)(Vq,{section:e,idx:n,blockId:`guide-caption-${e.id}`,keySuffix:`caption`,variant:`caption`,isActive:i,hasViewDef:r.hasViewDef??!0,runState:r.runState,deps:r.deps,onExampleSelect:r.onExampleSelect,selectedExampleIndex:r.selectedExamples[e.id]??0,chapters:r.chapters,challengeQuests:r.challengeQuests,onScrollToSection:r.onScrollToSection})},e.id)})})}function Uq({sections:e,part:t,partCount:n,title:r,pane:i,cardArgs:a,onActivateSection:o}){let s=(0,V.useRef)(null),c=(0,V.useMemo)(()=>qK(e),[e]),{slice:l,subscribe:u}=UK(s,!1,c),d=(0,V.useRef)(e);d.current=e;let[f,p]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=s.current;if(!e||typeof IntersectionObserver>`u`){p(!0);return}let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(p(!0),t.disconnect())},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let m=()=>{let e=s.current;if(!e)return!1;let{top:t,bottom:n}=e.getBoundingClientRect();return t<=0&&n>window.innerHeight},[h,g]=(0,V.useState)(!1);(0,V.useEffect)(()=>u(()=>{let e=m();g(t=>t===e?t:e)}),[u]);let _=(0,V.useRef)(!1),v=(0,V.useRef)(-1),y=(0,V.useRef)(o);y.current=o,(0,V.useEffect)(()=>{let e=_.current,t=v.current;if(_.current=h,v.current=l.index,!h||e&&t===l.index)return;let n=d.current[l.index];n&&y.current(n)},[h,l.index]);let b=e[l.index]??null;return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`header`,{"data-testid":`guide-runway-header-${t}`,className:`mx-auto w-full max-w-[1500px] px-6 pt-12 pb-6 lg:px-12`,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[`Part `,t,` / `,n]}),(0,H.jsx)(`h2`,{className:`mt-1 text-xl font-black uppercase tracking-tight text-foreground`,children:r})]}),(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(BK,{trackRef:s,height:`${(e.length+1)*100}vh`,stages:c,activeIndex:l.index,pane:f?i:null,captions:(0,H.jsx)(Hq,{sections:e,activeIndex:l.index,part:t,args:a}),status:(0,H.jsxs)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[String(l.index+1).padStart(2,`0`),b?` — ${b.heading}`:``]}),testId:`guide-runway-${t}`}),e.map((t,n)=>(0,H.jsx)(`span`,{id:t.id,"data-section-id":t.id,"aria-hidden":`true`,className:`pointer-events-none absolute left-0 h-px w-px`,style:{top:`calc((100% - 100vh) * ${n/e.length} + 50vh + 120px)`}},t.id))]})]})}function Wq({sections:e,groupKey:t,title:n,pane:r,cardArgs:i,onActivateSection:a}){let{groups:o,tail:s}=KK(e,t);return(0,H.jsxs)(H.Fragment,{children:[o.map((e,t)=>(0,H.jsx)(Uq,{sections:e,part:t+1,partCount:o.length,title:n,pane:r,cardArgs:i,onActivateSection:a},e[0]?.id??t)),s.length>0&&(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] px-6 lg:px-12`,"data-testid":`guide-static-tail`,children:(0,H.jsx)(`div`,{className:`lg:max-w-[50%]`,children:s.map((e,t)=>(0,H.jsx)(Vq,{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 Gq(){let e=jP(),{pathname:t}=mt(),n=(0,V.useMemo)(()=>qN(e).flatMap(e=>e.action?.type===`route`?[{id:e.id,label:e.label,to:e.action.to}]:[]),[e]);if(n.length===0)return null;let r=n.findIndex(e=>e.to===t),i=r>=0,a=i&&n.length>1?(r+1)%n.length:-1;return(0,H.jsx)(`nav`,{"aria-label":i?`What’s Next`:`Syntax & Guides`,"data-testid":`guide-index-footer`,className:`border-t border-border px-6 py-12 xl:py-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col rounded-lg border border-border overflow-hidden`,children:[(0,H.jsxs)(`h2`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[i?`What’s Next`:`Syntax & Guides`,` · `,n.length]}),(0,H.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:n.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(Wn,{to:e.to,"aria-current":t===r?`page`:void 0,className:U(`flex flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,t===r&&`bg-muted/50`),children:[(0,H.jsxs)(`span`,{className:`flex w-full items-baseline justify-between gap-3`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.label}),t===a&&(0,H.jsx)(`span`,{className:`text-xs font-semibold text-primary`,"data-testid":`guide-next-marker`,children:`Next →`})]}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.to})]})},e.id))})]})})}var Kq=`22rem`,qq=`42rem`,Jq=`20rem`,Yq=`calc(100dvh - var(--canvas-sticky-top) - 2rem)`;function Xq(e){return{editorWidth:e||`50%`,editorMinWidth:Kq,editorMaxWidth:qq,editorMinHeight:Jq,editorMaxHeight:Yq}}function Zq(e){let t=Math.max(1,e.split(`
163
+ `).length);return`calc(${Math.min(560,Math.max(180,t*22))}px + 3.5rem)`}function Qq(e,t){return{"--canvas-editor-width":e.editorWidth,"--canvas-editor-min-width":e.editorMinWidth,"--canvas-editor-max-width":e.editorMaxWidth,"--canvas-editor-min-height":e.editorMinHeight,"--canvas-editor-max-height":e.editorMaxHeight,"--canvas-editor-preferred-height":Zq(t)}}var $q=(e,t,n)=>(0,H.jsx)(Vq,{section:e,idx:t,blockId:e.id,keySuffix:`default`,isActive:n.activeSectionId===e.id,hasViewDef:n.hasViewDef,runState:n.runState,deps:n.deps,onExampleSelect:n.handleExampleSelect,selectedExampleIndex:n.selectedExamples[e.id]??0,chapters:n.chapters,challengeQuests:n.challengeQuests,isCollection:n.isCollection,collectionSlug:n.collectionSlug,workoutItems:n.workoutItems,handleSelectWorkout:n.handleSelectWorkout,onScrollToSection:n.onScrollToSection},`${e.id}-default`),eJ=({heroSlot:e,mobilePanel:t,desktopPanel:n,stickyAlign:r=`right`,editorWidth:i=`50%`,contentSections:a,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,activeSectionId:u,selectedExamples:d,runState:f,deps:p,handleExampleSelect:m,hasWorkoutsTag:h,hasViewDef:g,chapters:_=[],challengeQuests:v=[],onScrollToSection:y,editorAppearsAtSectionId:b})=>{let x=b?a.findIndex(e=>e.id===b):-1,S=x>0&&!!n,C={activeSectionId:u,selectedExamples:d,handleExampleSelect:m,hasViewDef:g,runState:f,deps:p,chapters:_,challengeQuests:v,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,onScrollToSection:y},w=S?{width:`calc(100% - ${i})`,flexBasis:`calc(100% - ${i})`,maxWidth:`calc(100% - ${i})`}:{},T=o&&s&&c?(0,H.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card`,children:(0,H.jsx)(`div`,{className:`w-full mx-auto`,children:(0,H.jsx)(rq,{category:s??``,workoutItems:c??[],onSelect:l,showSearch:!1,variant:`flat`})})}):null;if(S){let i=a.slice(0,x),o=a.slice(x);return(0,H.jsxs)(H.Fragment,{children:[e,i.map((e,t)=>$q(e,t,C)),(0,H.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,H.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[t,o.map((e,t)=>$q(e,t,C)),T]}),r===`right`&&n]})]})}return(0,H.jsxs)(H.Fragment,{children:[t,(0,H.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,H.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[e,a.map((e,t)=>$q(e,t,C)),T]}),r===`right`&&n]})]})},tJ=({activations:e,runState:t,deps:n})=>{if(e.length===0)return null;let r=e[0];if(YM(r)&&t){let i=e.slice(1),a=t.isReconnect?(0,H.jsxs)(`button`,{onClick:t.onReconnect,className:`flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full border transition-all active:scale-95 border-amber-500/40 bg-amber-500/15 text-amber-600 hover:bg-amber-500/20 dark:text-amber-400`,children:[(0,H.jsx)(Ye,{className:`size-3.5`}),`View`]}):(0,H.jsxs)(`button`,{type:`button`,onClick:t.onRun,className:`flex items-center gap-2 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest rounded-full shadow-lg shadow-primary/25 min-h-[44px] px-6 py-2 text-xs`,children:[(()=>{let e=r.icon||Ht;return(0,H.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,H.jsx)(`span`,{children:r.label})]});return(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 justify-end pt-3 px-1`,children:[a,i.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full bg-muted border border-border text-foreground hover:bg-muted/80 transition-all active:scale-95`,children:e.label},e.id||t))]})}return(0,H.jsx)(`div`,{className:`flex flex-wrap gap-3 justify-end pt-3 px-1`,children:e.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>KM(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full transition-all active:scale-95 bg-primary text-primary-foreground shadow-lg shadow-primary/25 hover:scale-[1.04]`,children:e.label},e.id||t))})},nJ=({variant:e,panelTitle:t,panelSubtitle:n,panelContent:r,panelThemeClass:i,headerActions:a,showPanelButtons:o=!1,viewDefButtons:s,runState:c,deps:l,width:u,source:d=``})=>{let f=r,p=o&&s&&s.length>0?(0,H.jsx)(tJ,{activations:s.map((e,t)=>JM(e,t)),runState:c,deps:l}):null;return e===`desktop`?(0,H.jsxs)(`div`,{className:`self-start sticky hidden lg:flex flex-col p-6 pt-8 pb-8 gap-3`,style:{top:`104px`,height:`calc(100vh - 104px)`,width:`clamp(var(--canvas-editor-min-width), var(--canvas-editor-width), var(--canvas-editor-max-width))`,...Qq(Xq(u),d)},children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col justify-center py-4`,children:(0,H.jsx)(`div`,{className:`h-[min(var(--canvas-editor-preferred-height),var(--canvas-editor-max-height))] min-h-[var(--canvas-editor-min-height)] max-h-[var(--canvas-editor-max-height)] flex flex-col w-full`,children:f})}),p]}):(0,H.jsx)(`div`,{className:`lg:hidden sticky z-20 shrink-0 px-4 pt-2 pb-1`,"data-page-sticky-boundary":`true`,style:{top:`65px`,height:`min(var(--canvas-editor-preferred-height), calc(100dvh - 65px - 1rem))`,minHeight:`18rem`,"--canvas-editor-preferred-height":Zq(d)},children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 h-full`,children:[(0,H.jsx)(`div`,{className:`flex-1 min-h-0`,children:f}),p]})})},rJ=({heroSlot:e,children:t})=>(0,H.jsxs)(`section`,{className:`relative border-b border-border/50`,children:[e,t]}),iJ=new Set([G.Duration,G.Time]);function aJ(e){return e.metrics.some(e=>e.type===G.Hint&&e.value===`domain.wod`)}function oJ(e){return e?e.filter(e=>!aJ(e)&&e.metrics.some(e=>e.type===G.Effort)).length:0}function sJ(e){if(!e)return 0;let t=0;for(let n of e)if(!aJ(n))for(let e of n.metrics)e.type===G.Rounds&&typeof e.value==`number`&&(t+=e.value);return t}function cJ(e){return e?e.some(e=>!aJ(e)&&e.metrics.some(e=>iJ.has(e.type))):!1}function lJ(e){return e?e.some(e=>!aJ(e)&&e.metrics.some(e=>e.type===G.Rep)):!1}function uJ(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function dJ(e,t){return typeof e==`string`&&e.length>0?e:typeof e==`number`?String(e):null}var fJ={"has-movement":e=>{let t=oJ(e.statements);return t>0?{pass:!0,detail:`${t} movement${t===1?``:`s`}`}:{pass:!1,reason:"Add at least one movement line (e.g. `10 KB Swings`)."}},"exactly-movements":(e,t)=>{let n=uJ(t.count??t.value,`count`);if(n===null)return{pass:!1,reason:"exactly-movements: missing `count`."};let r=oJ(e.statements);return r===n?{pass:!0,detail:String(r)}:{pass:!1,reason:`Expected exactly ${n} movement${n===1?``:`s`}, found ${r}.`}},"has-reps":e=>lJ(e.statements)?{pass:!0}:{pass:!1,reason:"Add a rep count (e.g. `10` reps on a movement line)."},"has-timer":e=>cJ(e.statements)?{pass:!0}:{pass:!1,reason:"Add a timer (e.g. `*:30 Rest` or `5:00 cap`)."},"min-rounds":(e,t)=>{let n=uJ(t.count??t.min,`count`);if(n===null)return{pass:!1,reason:"min-rounds: missing `count`."};let r=sJ(e.statements);return r>=n?{pass:!0,detail:`${r} round${r===1?``:`s`}`}:{pass:!1,reason:`Need at least ${n} round${n===1?``:`s`} — found ${r}.`}},"contains-token":(e,t)=>{let n=dJ(t.value??t.token,`value`);return n===null?{pass:!1,reason:"contains-token: missing `value`."}:(e.content??``).includes(n)?{pass:!0,detail:`"${n}"`}:{pass:!1,reason:`Script must include the token "${n}".`}}};function pJ(e,t){if(!t||typeof t.type!=`string`||t.type.length===0)return{pass:!1,reason:`Quest has no validation schema.`};let n=fJ[t.type];return n?n(e,t):{pass:!1,reason:`Unknown validation type "${t.type}".`}}function mJ({pageRoute:e,quests:t,block:n,enabled:r=!0}){let{markComplete:i,quests:a,isComplete:o}=OH(e,t),[s,c]=(0,V.useState)(new Set),l=(0,V.useMemo)(()=>{let e={};if(!r||!n){for(let n of t)e[n.id]={pass:!1,reason:`No active block.`};return e}let i={content:n.content,statements:n.statements??[]};for(let n of t){if(!n.validation){e[n.id]={pass:!1};continue}if(n.validation?.type===`workout-complete`){e[n.id]={pass:!1,reason:`Finish the workout to check this off.`};continue}e[n.id]=pJ(i,n.validation)}return e},[n,t,r]);(0,V.useEffect)(()=>{if(r)for(let e of a)e.isCompleted||s.has(e.id)||l[e.id]?.pass&&(i(e.id),c(t=>{if(t.has(e.id))return t;let n=new Set(t);return n.add(e.id),n}))},[r,a,l,s,i]);let u=(0,V.useMemo)(()=>t.map(e=>e.id).join(`|`),[t]);return(0,V.useEffect)(()=>{c(new Set)},[e,u]),{quests:a.map(e=>{let t=l[e.id]??{pass:!1,reason:`No validator result.`},n=e.isCompleted?{...t,pass:!0,detail:`Completed`}:t;return{...e,result:n}}),isComplete:o,results:l}}function hJ({page:e,wodFiles:t,theme:n,workoutItems:r,onSelect:i,contentOverride:a,panelHeaderActions:o,onPanelActionsReady:s,heroSlot:c,onScrollToSection:l}){let u=Sn(),d=mt(),{sections:f,route:p,chapters:m}=e,h=d.pathname.startsWith(`/p/`)||p.startsWith(`/p/`),g=(0,V.useMemo)(()=>zL(p),[p]),_=e.type===`guide`||p.startsWith(`/guide`);uH(_?p:void 0);let v=p.startsWith(`/collections/`)||p.startsWith(`/c/`),y=jH(`(prefers-reduced-motion: reduce)`),b=_&&!v&&!y,x=v?p.split(`/`).pop()??null:null,S=(0,V.useCallback)(e=>{if(i){i(e);return}u(ZA(e.category,e.name))},[u,i]),C=f.some(e=>e.proseChunks.some(e=>e.kind===`widget`&&e.widget===`workouts-list`)),w=f.slice(1),T=f[0]??null,E=!!T&&(T.proseChunks.some(e=>e.kind===`prose`&&e.text.trim()!==``)||T.buttons.length>0),D=f.find(e=>e.view)?.view??null,O=D?.align??`right`,k=D?.width??`50%`,A=w[0]??f[0]??null,j=p===`/`?`learn`:void 0,M=D?.source?BL(D.source,t):``,N=D?.source||`__initial__`,[P,F]=(0,V.useState)(A?.id??null),[I,ee]=(0,V.useState)(A?.heading??`Whiteboard Script`),[te,ne]=(0,V.useState)(A?.heading??`Whiteboard Script`),re=(0,V.useMemo)(()=>HL(w),[w]),ie=b&&p.split(`/`).pop()||void 0,ae=(0,V.useMemo)(()=>b?KK(w,ie):null,[b,ie,w]),{guideOwnerBySection:oe,guideOwnerSource:se}=(0,V.useMemo)(()=>{if(!b)return{guideOwnerBySection:null,guideOwnerSource:null};let e=new Map,t=new Map,n=null;for(let r of w){let i=r.proseChunks.find(e=>e.kind===`button`&&e.button.pipeline.some(e=>e.action===`set-source`))?.button.pipeline.find(e=>e.action===`set-source`)?.value??r.buttons.find(e=>e.pipeline.some(e=>e.action===`set-source`))?.pipeline.find(e=>e.action===`set-source`)?.value??null;i&&(n=r,t.set(r.id,i)),e.set(r.id,n)}return{guideOwnerBySection:e,guideOwnerSource:t}},[b,w]),[ce,L]=(0,V.useState)(()=>(A??f[0])?.theme??`slate`),[le,ue]=(0,V.useState)({}),{editorSource:R,editorOpacity:de,isEditorLoading:fe,activeOriginalSource:pe,swapSource:me,handleEditorChange:he,resetActiveSource:ge,setEditorView:_e,getSource:ve}=bH({initialSource:M,initialSourceKey:N,contentOverride:a}),ye=(0,V.useRef)(t);ye.current=t;let be=(0,V.useCallback)(()=>Pe.current[0]??null,[]),{startRun:xe,closeRun:Se,handleWorkoutComplete:Ce,resetRun:we,resetRequested:Te,fullscreen:Ee,runState:De,completedResults:Oe}=yH({getBlock:be,getContent:ve,title:e.frontmatter.title}),ke=(0,V.useCallback)(async()=>await we(M)?(ge(),!0):!1,[we,M,ge]),[Ae,je]=(0,V.useState)(null),Me=e.quests??[],Ne=mJ({pageRoute:e.route,quests:Me,block:Ae});kH({pageRoute:e.route,quests:Me,completedResults:Oe}),AH({pageRoute:e.route,quests:Me,initialSource:M,currentSource:R});let Pe=(0,V.useRef)([]),Fe=(0,V.useRef)(re.get(A?.id??``)?.id??null),Ie=(0,V.useCallback)(e=>{F(e.id),ee(e.heading),L(e.theme??`slate`);let t=(oe??re).get(e.id)??null;ne(t?.heading??A?.heading??`Whiteboard Script`);let n=t?.id??null;if(n===Fe.current)return;if(Fe.current=n,!t){me(M,N);return}let r=t.examples??[];if(r.length>0){let e=r[le[t.id]??0]??r[0];e?.source&&me(BL(e.source,ye.current),e.source)}for(let e of t.commands){let t=e.pipeline.filter(e=>!(r.length>0&&e.action===`set-source`)).map(t=>qM(t,e.open??`view`));t.length!==0&&KM(t.length===1?t[0]:{type:`pipeline`,steps:t},He.current)}let i=oe?se?.get(t.id):void 0;i&&me(BL(i,ye.current),i)},[le,me,re,oe,se,A,M,N]),Le=(0,V.useCallback)((e,t)=>{ue(n=>({...n,[e.id]:t})),F(e.id),ee(e.heading),L(e.theme??`slate`),ne(e.heading),Fe.current=e.id;let n=e.examples?.[t];n?.source&&me(BL(n.source,ye.current),n.source)},[me]),[Re,ze]=Gt(`h`,{history:`replace`,shallow:!0}),[Be]=Gt(`q`,{defaultValue:``,shallow:!0}),Ve=(0,V.useMemo)(()=>({navigate:(e,t)=>u(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&ze(n,{history:t?`replace`:`push`})},swapSource:e=>me(BL(e,ye.current),e),setPanelState:e=>{if(e===`track`){let e=be();e&&xe(e)}}}),[u,me,ze,be,xe]),He=(0,V.useRef)(Ve);He.current=Ve;let Ue=(0,V.useCallback)(e=>{ze(e.id,{history:`replace`}),Ie(e)},[Ie,ze]),We=aL(104),Ge=(0,V.useMemo)(()=>`-${We}px 0px -30% 0px`,[We]),Ke=ae?ae.tail.map(e=>e.id):w.map(e=>e.id),qe=(0,V.useRef)(!1);eL({ids:Ke,enabled:Ke.length>0,rootMargin:Ge,threshold:[0,.1,.25,.5,.75],dataAttribute:`data-section-id`,scrollDirection:`topmost-when-up`,debounceMs:50,shouldAcceptChange:()=>qe.current?!0:(qe.current=window.scrollY>0,qe.current),onChange:e=>{let t=w.find(t=>t.id===e);t&&(ze(e,{history:`replace`}),Ie(t))}});let Je=(0,V.useRef)(!1);(0,V.useEffect)(()=>{Je.current||!Re||w.length===0||(Je.current=!0,requestAnimationFrame(()=>{let e=document.querySelector(`[data-section-id="${Re}"]`);if(!e)return;let t=We+8,n=e.getBoundingClientRect().top+window.scrollY-t;window.scrollTo({top:Math.max(0,n),behavior:`smooth`})}))},[w,Re,We]);let Ye=(0,V.useRef)(Be);(0,V.useEffect)(()=>{if(!v){Ye.current=Be;return}let e=Be.trim(),t=Ye.current.trim();if(e&&e!==t){let e=document.getElementById(`collection-workouts`);if(e){let t=e.getBoundingClientRect().top+window.scrollY-We-8;window.scrollTo({top:Math.max(0,t),behavior:`smooth`})}}Ye.current=Be},[Be,v,We]);let Xe=(0,V.useRef)(s);Xe.current=s,(0,V.useEffect)(()=>{Xe.current?.({run:()=>{let e=Pe.current[0]??null;e&&xe(e)},reset:()=>{we()},results:()=>{},fullscreen:()=>{let e=Pe.current[0]??null;e&&xe(e)},getSource:ve})},[xe,we,ve]);let Ze=(0,V.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:e=>{xe(e)}}],[xe]),Qe=tP[ce]??tP.slate,$e=fe?`${I} · loading`:I,et=!fe&&I!==te?te:void 0,tt=(0,V.useCallback)(e=>{let t=e[0]??null;Pe.current=e,je(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),nt=c??(E&&T?(0,H.jsx)(Vq,{section:T,idx:-1,prose:void 0,blockId:T.id,keySuffix:`hero`,showEyebrow:!1,isActive:!1,hasViewDef:!!D,deps:Ve,onExampleSelect:Le,selectedExampleIndex:0,onScrollToSection:l,challengeQuests:Ne.quests}):null),rt=o,it=(0,H.jsx)(wK,{editorSource:R,editorOpacity:de,activeOriginalSource:pe,handleEditorChange:he,onResetToSource:ke,canvasNoteId:g,readonly:h,showFrontmatter:typeof e.frontmatter.showFrontmatter==`boolean`?e.frontmatter.showFrontmatter:!_&&p!==`/`&&!p.startsWith(`/syntax`),theme:n,commands:Ze,onBlocksChange:tt,onViewCreated:_e,panelTitle:$e,panelSubtitle:et,panelThemeClass:Qe.panel,headerActions:rt,onRun:(e,t)=>{t&&xe(t,e)}}),at=D&&(0,H.jsx)(nJ,{variant:`desktop`,panelContent:it,panelTitle:$e,panelSubtitle:et,viewDefButtons:D.buttons,runState:De,deps:Ve,width:k,source:R}),ot=D&&(0,H.jsx)(nJ,{variant:`mobile`,panelContent:it,panelTitle:$e,panelSubtitle:et,viewDefButtons:D.buttons,runState:De,deps:Ve,width:k,source:R});return(0,H.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,children:[Ee?.kind===`timer`&&(0,H.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:We},children:(0,H.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,H.jsx)(eH,{block:Ee.block,onClose:Se,autoStart:!0,externalStop:Te,onComplete:(e,t)=>{Ce(t)}})})}),(0,H.jsx)(rJ,{heroSlot:nt,children:b?(0,H.jsx)(Wq,{sections:w,groupKey:ie,title:String(e.frontmatter.title??``),pane:(0,H.jsx)(`div`,{className:`absolute inset-0`,style:{"--canvas-editor-preferred-height":Zq(R)},children:it}),cardArgs:{activeSectionId:P,selectedExamples:le,onExampleSelect:Le,runState:De,deps:Ve,hasViewDef:!!D,chapters:m,challengeQuests:Ne.quests,onScrollToSection:l},onActivateSection:Ue}):(0,H.jsx)(eJ,{contentSections:w,isCollection:v,collectionSlug:x,workoutItems:r,handleSelectWorkout:S,activeSectionId:P,selectedExamples:le,runState:De,deps:Ve,handleExampleSelect:Le,hasWorkoutsTag:C,hasViewDef:!!D,chapters:m,challengeQuests:Ne.quests,onScrollToSection:l,mobilePanel:ot,desktopPanel:at,stickyAlign:O,editorWidth:k,editorAppearsAtSectionId:j})}),_&&(0,H.jsx)(Gq,{})]})}var gJ={"workout-complete":!0,"run-started":!0};function _J(e,t,n){let{markComplete:r}=OH(e,t),i=(0,V.useRef)(new Set);i.current=new Set(t.filter(e=>!e.validation||!gJ[e.validation.type]).map(e=>e.id));let a=(0,V.useRef)({}),o={};for(let e of n)e.quest&&(o[e.id]=e.quest);return a.current=o,(0,V.useCallback)(e=>{let t=a.current[e];t&&i.current.has(t)&&r(t)},[r])}function vJ(){let e=jH(`(prefers-reduced-motion: reduce)`),t=jH(`(max-width: ${RL}px)`);return e?`reduced`:t?`mobile`:`desktop`}var yJ=.25;function bJ({sourcesByStageId:e,doc:t,setDoc:n,subscribe:r,enabled:i}){let[a,o]=(0,V.useState)(!1),s=(0,V.useRef)(t),c=(0,V.useRef)(null),l=(0,V.useRef)(t),u=(0,V.useRef)(a),d=(0,V.useRef)(``),f=(0,V.useRef)(null),p=(0,V.useRef)(!1);return l.current=t,u.current=a,(0,V.useEffect)(()=>{let e=d.current;if(c.current!==null){if(t===c.current){s.current=t,c.current=null;return}if(t!==s.current){o(!0);return}}t!==s.current&&t!==e&&o(!0)},[t]),(0,V.useEffect)(()=>{if(!i){c.current=null;return}let t=r(t=>{if(t.stage.id!==f.current&&(f.current=t.stage.id,d.current=e[t.stage.id]??``,s.current=``,c.current=null,o(!1),p.current=!0),u.current||c.current!==null)return;let r=d.current;if(!r)return;let i=t.index===0?r.length:Math.floor(kK(DK(t.t/yJ))*r.length),a=r.slice(0,i),m=l.current;p.current=!1,a!==m&&(c.current=a,n(a))});return()=>{t()}},[i,e,n,r]),{userDiverged:a,complete:(0,V.useCallback)(()=>{if(u.current)return;let e=d.current;e&&(c.current=e,n(e))},[n])}}function xJ({stages:e,activeIndex:t}){return(0,H.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`scroll-captions`,children:e.map((n,r)=>(0,H.jsxs)(`div`,{className:`absolute inset-0 overflow-y-auto transition-opacity duration-300`,style:{opacity:+(r===t)},"aria-hidden":r!==t,inert:r!==t,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:n.accent??`hsl(var(--muted-foreground))`},children:[String(r+1).padStart(2,`0`),` / `,String(e.length).padStart(2,`0`)]}),(0,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:n.id.replace(/-/g,` `)}),n.caption&&(0,H.jsx)(Sq,{prose:n.caption,className:`mt-3 text-sm text-muted-foreground`})]},n.id))})}var SJ=(0,V.forwardRef)(function({text:e,accent:t},n){let r=t??`hsl(var(--metric-rounds))`;return(0,H.jsxs)(`div`,{ref:n,className:`pointer-events-none absolute top-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-2.5 whitespace-nowrap rounded-full border bg-card px-5 py-2.5 font-mono text-[10.5px] tracking-[0.04em] opacity-0 shadow-xl`,style:{borderColor:`color-mix(in srgb, ${r} 55%, transparent)`},children:[(0,H.jsx)(`span`,{className:`size-[9px] rounded-sm`,style:{background:r}}),e]})}),CJ=8,wJ=3,TJ=2;function EJ(e,t,n){let r=e.querySelectorAll(`.cm-content .cm-line`),i=Math.max(1,Math.min(n[0],n[1]))-1,a=Math.max(1,Math.max(n[0],n[1])),o=Array.from(r).slice(i,a);if(o.length===0)return null;let s=e.getBoundingClientRect(),c=1/0,l=1/0,u=-1/0,d=-1/0;for(let e of o){let t=e.getBoundingClientRect();c=Math.min(c,t.top),l=Math.min(l,t.left),u=Math.max(u,t.bottom),d=Math.max(d,t.right)}return c-=wJ,l-=CJ,u+=wJ,d+=CJ,t&&(l=Math.max(l,t.left-TJ),d=Math.min(d,t.right+TJ),c=Math.max(c,t.top-TJ),u=Math.min(u,t.bottom+TJ)),{top:c-s.top,left:l-s.left,width:d-l,height:u-c}}function DJ(e,t){if(!t)return null;let n=t.getBoundingClientRect();if(n.width===0||n.height===0)return null;let r=e.getBoundingClientRect();return{top:n.top-r.top-TJ,left:n.left-r.left-TJ,width:n.width+4,height:n.height+4}}function OJ({accent:e,lines:t}){let n=e??`hsl(var(--foreground))`,r=(0,V.useRef)(null),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(!1);return(0,V.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let n=requestAnimationFrame(()=>s(!0)),i=e.parentElement;if(!i)return()=>cancelAnimationFrame(n);let o=()=>{let e=i.firstElementChild,n=e?.getBoundingClientRect()??null;a((t?EJ(i,n,t):null)??DJ(i,e))};o();let c=new ResizeObserver(o);return c.observe(i),()=>{cancelAnimationFrame(n),c.disconnect()}},[t]),(0,H.jsx)(`div`,{ref:r,className:`pointer-events-none absolute z-30 transition-all duration-300 ${i?t?`rounded-lg`:`rounded-2xl`:`-inset-1.5 rounded-2xl`}`,style:{boxShadow:`0 0 0 2px ${n}`,opacity:+!!o,...i??{}},"data-testid":`scroll-ring`,"data-ring-lines":t?`${t[0]}-${t[1]}`:void 0})}function kJ({scroll:e,wodFiles:t,theme:n,noteTitle:r=`note.md`,showFrontmatter:i,doc:a,onDocChange:o,onBlocksChange:s,onStageEnter:c,onRun:l,className:u}){let d=e.stages,f=(0,V.useRef)(null),p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useRef)(new Set),g=(0,V.useMemo)(()=>Object.fromEntries(d.map(e=>[e.id,e.source?BL(e.source,t):``])),[d,t]),[_,v]=(0,V.useState)(()=>g[d[0]?.id]??``),y=a??_,b=o??v,[x,S]=(0,V.useState)(!1),{slice:C,subscribe:w,resync:T}=UK(f,x,d),[E,D]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=f.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&D(!0)},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let{userDiverged:O}=bJ({sourcesByStageId:g,doc:y,setDoc:b,subscribe:w,enabled:!x&&e.typewriter}),k=C.stage.id,A=AK(g[k]??``,y);(0,V.useEffect)(()=>{!x&&E&&c?.(k)},[x,k,E,c]),(0,V.useEffect)(()=>{if(!x){let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)}},[x,T]),(0,V.useEffect)(()=>{let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)},[k,T]),(0,V.useEffect)(()=>{O&&S(!0)},[O]),(0,V.useEffect)(()=>{let e=d.flatMap(e=>e.effects??[]);return w(t=>{let n=m.current;if(n){let e=DK((t.t-.04)/.12),r=DK((t.t-.5)/.2);n.style.opacity=String(Math.max(0,e-r)),n.style.transform=`translateX(-50%) translateY(${OK(-14,0,e)}px)`}let r=p.current;if(!r)return;let i=new Set;for(let n of e){if(!n.stages.includes(t.stage.id))continue;i.add(n.target);let[e,a]=n.in??[0,1],o=a>e?DK((t.t-e)/(a-e)):1,s=n.ease===`linear`?o:kK(o);r.querySelectorAll(`[data-effect-target="${n.target}"]`).forEach(e=>{n.opacity&&(e.style.opacity=String(OK(n.opacity[0],n.opacity[1],s))),n.translateY&&(e.style.transform=`translateY(${OK(n.translateY[0],n.translateY[1],s)}px)`)})}for(let e of h.current)i.has(e)||r.querySelectorAll(`[data-effect-target="${e}"]`).forEach(e=>{e.style.opacity=``,e.style.transform=``});h.current=i})},[w,d]);let j=C.stage.accent??`hsl(var(--foreground))`;return(0,H.jsxs)(`div`,{ref:p,className:u,"data-testid":`scroll-runway-section`,children:[(0,H.jsx)(BK,{trackRef:f,height:e.runway,stages:d,activeIndex:C.index,status:(0,H.jsx)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:x?`Playground mode`:C.stage.id.replace(/-/g,` `)}),pane:(0,H.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,H.jsx)(CK,{title:r??``,noteId:`canvas:scroll-runway`,doc:y,onDocChange:b,onBlocksChange:s,theme:n,showFrontmatter:i,run:l?{onRun:l}:void 0,className:`absolute inset-x-2 top-2 bottom-2`,children:C.stage.toast&&(0,H.jsx)(SJ,{ref:m,text:C.stage.toast,accent:j})}),C.ring&&!x&&A&&(0,H.jsx)(OJ,{accent:j,lines:C.ring.lines})]}),captions:(0,H.jsx)(xJ,{stages:d,activeIndex:C.index})}),x&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>S(!1),className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-full bg-foreground px-5 py-2.5 font-mono text-[10px] tracking-[0.06em] text-background opacity-95 transition-opacity hover:opacity-100`,children:[`▶ Playground mode — `,O?`your edits are kept`:`editing`,` · tap here to return to the tour`]})]})}function AJ({spec:e,wodFiles:t,onStageEnter:n,className:r}){let i=e.stages,a=(0,V.useMemo)(()=>Object.fromEntries(i.map(e=>[e.id,e.source?BL(e.source,t):``])),[i,t]),o=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=o.current;if(!e)return;let t=new IntersectionObserver(e=>{for(let r of e){if(!r.isIntersecting)continue;let e=r.target.dataset.cardId;e&&(n?.(e),t.unobserve(r.target))}},{threshold:.4});return e.querySelectorAll(`[data-card-id]`).forEach(e=>t.observe(e)),()=>t.disconnect()},[n]),(0,H.jsx)(`section`,{className:r,"data-testid":`runway-reduced`,children:(0,H.jsx)(`div`,{className:`px-6 pt-4 pb-24`,children:(0,H.jsx)(`div`,{ref:o,className:`mx-auto max-w-2xl`,children:i.map((e,t)=>(0,H.jsxs)(`article`,{"data-card-id":e.id,className:`mb-6 rounded-2xl border border-border bg-card p-7`,children:[(0,H.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:e.accent??`hsl(var(--muted-foreground))`},children:[String(t+1).padStart(2,`0`),` / `,String(i.length).padStart(2,`0`)]}),(0,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:e.id.replace(/-/g,` `)}),e.caption&&(0,H.jsx)(Sq,{prose:e.caption,className:`mt-3 text-sm text-muted-foreground`}),a[e.id]&&(0,H.jsx)(`pre`,{className:`mt-5 overflow-x-auto rounded-lg bg-background px-4 py-4 font-mono text-[12px] tracking-[0.04em] text-muted-foreground`,children:a[e.id]})]},e.id))})})})}function jJ(){return vJ()}function MJ({spec:e,formFactor:t,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d}){let f=jJ();return(t??f)===`reduced`?(0,H.jsx)(AJ,{spec:e,wodFiles:n,onStageEnter:l,className:d}):(0,H.jsx)(kJ,{scroll:e,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d})}function NJ({page:e,wodFiles:t,theme:n,onScrollToSection:r}){let i=e.scroll,a=i.stages,o=Sn();uH(e.type===`guide`||e.route.startsWith(`/guide`)?e.route:void 0);let s=(0,V.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,e.source?BL(e.source,t):``])),[a,t]),[c,l]=(0,V.useState)(()=>s[a[0]?.id]??``),u=(0,V.useRef)([]),[d,f]=(0,V.useState)(null),p=_J(e.route,e.quests,a),m=(0,V.useCallback)(()=>u.current[0]??null,[]),h=yH({getBlock:m,getContent:(0,V.useCallback)(()=>c,[c]),title:e.frontmatter.title}),{startRun:g}=h,_=aL(104),v=mJ({pageRoute:e.route,quests:e.quests,block:d});kH({pageRoute:e.route,quests:e.quests,completedResults:h.completedResults});let[,y]=Gt(`h`,{history:`replace`,shallow:!0}),b=(0,V.useMemo)(()=>({navigate:(e,t)=>o(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&y(n,{history:t?`replace`:`push`})},swapSource:e=>l(BL(e,t)),setPanelState:e=>{if(e===`track`){let e=m();e&&g(e)}}}),[o,y,t,m,g]),x=(0,V.useCallback)((e,n)=>{let r=e.examples?.[n];r?.source&&l(BL(r.source,t))},[t]),S=(0,V.useCallback)(e=>{let t=e[0]??null;u.current=e,f(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),C=(0,V.useCallback)((e,t)=>{t&&g(t,e)},[g]),w=`${e.route.split(`/`).pop()??`note`}.md`,T=e.sections.slice(1).map((e,t)=>(0,H.jsx)(Vq,{section:e,idx:t,blockId:e.id,keySuffix:`scroll`,isActive:!1,hasViewDef:!1,deps:b,onExampleSelect:x,selectedExampleIndex:0,challengeQuests:v.quests,onScrollToSection:r},e.id));return(0,H.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,"data-testid":`scroll-canvas-page`,children:[h.fullscreen?.kind===`timer`&&(0,H.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:_},children:(0,H.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,H.jsx)(eH,{block:h.fullscreen.block,onClose:h.closeRun,autoStart:!0,externalStop:h.resetRequested,onComplete:(e,t)=>{h.handleWorkoutComplete(t)}})})}),(0,H.jsx)(MJ,{spec:i,wodFiles:t,theme:n,noteTitle:w,showFrontmatter:e.frontmatter.showFrontmatter===!0,doc:c,onDocChange:l,onBlocksChange:S,onStageEnter:p,onRun:C}),T]})}var PJ=({timeLabel:e,title:t,subtitle:n,onClick:r})=>(0,H.jsxs)(`button`,{onClick:r,className:`flex items-center gap-4 px-6 py-3 hover:bg-muted/40 transition-colors text-left group w-full`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 w-14 text-right`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,H.jsx)(De,{className:`size-2.5 text-muted-foreground/40`}),(0,H.jsx)(`span`,{className:`text-[10px] font-black text-muted-foreground/60 tabular-nums`,children:e})]})}),(0,H.jsx)(`div`,{className:`flex-shrink-0 size-8 rounded-lg bg-muted flex items-center justify-center group-hover:bg-background transition-colors`,children:(0,H.jsx)(In,{className:`size-3.5 text-signal-positive`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground truncate`,children:t}),n&&(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate`,children:n})]})]});function FJ(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function IJ(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function LJ(e,t){return FJ(e)===FJ(t)}var RJ=(0,V.forwardRef)(({items:e,onSelect:t,onCreateEntry:n,journalEntries:r,onOpenEntry:i,onVisibleDateChange:a,stickyOffset:o=0,className:s,renderNoteCard:c,renderResultRow:l,renderEmptyDate:u,initialDate:d},f)=>{let p=(0,V.useRef)(null),m=(0,V.useRef)(null),h=(0,V.useRef)(null),g=(0,V.useRef)(null),_=(0,V.useRef)(new Map),v=(0,V.useRef)(!1),y=(0,V.useRef)(!1),b=(0,V.useRef)(!1),x=(0,V.useRef)(!1),S=(0,V.useRef)(new Date),C=(0,V.useRef)(new Date),w=(0,V.useRef)(null),T=(0,V.useRef)(null),[E,D]=(0,V.useState)(o);(0,V.useEffect)(()=>{let e=()=>{if(!T.current)return;let e=T.current.getBoundingClientRect(),t=Math.round(e.top+window.scrollY);D(Math.max(o,t))},t=requestAnimationFrame(e);return window.addEventListener(`resize`,e,{passive:!0}),()=>{cancelAnimationFrame(t),window.removeEventListener(`resize`,e)}},[o]);let O=(0,V.useRef)(null),k=(0,V.useRef)(!1),A=(0,V.useRef)(null),j=(0,V.useRef)(``),[M,P]=(0,V.useState)(()=>{let e=new Date;if(d){let t=IJ(e,90);return{start:IJ(d,-14),end:IJ(d,14)>t?t:IJ(d,14)}}return{start:IJ(e,-7),end:e}}),F=(0,V.useMemo)(()=>{let e=[],t=new Date(M.end),n=M.start;for(;t>=n;)e.push(new Date(t)),t=IJ(t,-1);return e},[M]),I=(0,V.useMemo)(()=>{let t=new Map;return e.forEach(e=>{if(!e.date)return;let n=FJ(new Date(e.date)),r=t.get(n)??[];r.push(e),t.set(n,r)}),t},[e]),ee=(0,V.useMemo)(()=>{let t=null;return r?.forEach((e,n)=>{let r=new Date(n+`T00:00:00`);(!t||r<t)&&(t=r)}),e.forEach(e=>{if(!e.date)return;let n=new Date(e.date);(!t||n<t)&&(t=n)}),t},[r,e]),te=(0,V.useRef)(null);(0,V.useEffect)(()=>{te.current=ee},[ee]),(0,V.useLayoutEffect)(()=>{S.current=M.start},[M.start]),(0,V.useLayoutEffect)(()=>{C.current=M.end},[M.end]),(0,V.useLayoutEffect)(()=>{let e=w.current;if(!e)return;w.current=null;let t=_.current.get(e.key);if(!t)return;let n=t.getBoundingClientRect().top-e.top;Math.abs(n)>1&&window.scrollBy(0,n)},[F]);let ne=(0,V.useCallback)(()=>{let e=(e,t)=>{e.current&&t.current&&(e.current.unobserve(t.current),e.current.observe(t.current))};e(h,p),e(g,m)},[]),re=(0,V.useCallback)(()=>{k.current=!0,A.current&&clearTimeout(A.current);let e=()=>{k.current=!1,A.current&&=(clearTimeout(A.current),null),ne()};window.addEventListener(`scrollend`,e,{once:!0});let t=window.scrollY,n=0,r=()=>{if(!k.current)return;let i=window.scrollY;if(i===t){if(n++,n>=2){window.removeEventListener(`scrollend`,e),e();return}}else t=i,n=0;A.current=setTimeout(r,100)};A.current=setTimeout(r,150)},[ne]),ie=(0,V.useCallback)(e=>{let t=e.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:t,behavior:`smooth`})},[E]);(0,V.useImperativeHandle)(f,()=>({scrollToDate(e){let t=FJ(e),n=_.current.get(t);if(n)re(),ie(n);else{let n=IJ(new Date,90);O.current=t,P({start:IJ(e,-14),end:IJ(e,14)>n?n:IJ(e,14)})}}}),[re,ie]),(0,V.useEffect)(()=>{requestAnimationFrame(()=>{if(d&&!LJ(d,new Date)){let e=FJ(d),t=_.current.get(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:Math.max(0,e),behavior:`auto`})}}else window.scrollTo({top:0,behavior:`instant`});b.current=!0,ne()})},[E,d,ne]),(0,V.useEffect)(()=>{let e=O.current;if(!e)return;let t=_.current.get(e);t&&(O.current=null,re(),requestAnimationFrame(()=>{let e=t.getBoundingClientRect().top+window.scrollY-E-8;window.scrollTo({top:Math.max(0,e),behavior:`auto`})}))},[F,re,E]),(0,V.useEffect)(()=>{let e=()=>{!b.current||k.current||x.current||(x.current=!0,ne())};return window.addEventListener(`scroll`,e,{passive:!0}),()=>{window.removeEventListener(`scroll`,e)}},[ne]),(0,V.useEffect)(()=>{let e=p.current;if(!e)return;let t=new IntersectionObserver(([e])=>{if(!e.isIntersecting||v.current||!b.current||k.current||!x.current)return;let t=IJ(new Date,90);if(C.current>=t)return;let n=FJ(C.current),r=_.current.get(n);r&&(w.current={key:n,top:r.getBoundingClientRect().top}),v.current=!0,P(e=>{let t=IJ(new Date,90);if(e.end>=t)return e;let n=IJ(e.end,7);return{...e,end:n>t?t:n}})},{rootMargin:`600px 0px 0px 0px`,threshold:0});return t.observe(e),h.current=t,()=>{t.disconnect(),h.current=null}},[]),(0,V.useEffect)(()=>{let e=setTimeout(()=>{v.current=!1,ne()},400);return()=>clearTimeout(e)},[M.end]),(0,V.useEffect)(()=>{let e=m.current;if(!e)return;let t=new IntersectionObserver(([e])=>{if(!e.isIntersecting||y.current||!b.current||k.current)return;let t=te.current,n=t?IJ(t,-14):IJ(new Date,-90);S.current<=n||(y.current=!0,P(e=>{let t=te.current?IJ(te.current,-14):IJ(new Date,-90),n=IJ(e.start,-7);return{...e,start:n<t?t:n}}))},{rootMargin:`0px 0px 400px 0px`,threshold:0});return t.observe(e),g.current=t,()=>{t.disconnect(),g.current=null}},[]),(0,V.useEffect)(()=>{let e=setTimeout(()=>{y.current=!1},400);return()=>clearTimeout(e)},[M.start]);let ae=(0,V.useRef)(E);(0,V.useEffect)(()=>{ae.current=E},[E]),(0,V.useEffect)(()=>{if(!a)return;let e=new Map,t=null,n=new IntersectionObserver(n=>{if(n.forEach(t=>{t.target.id&&(t.isIntersecting?e.set(t.target.id,t.boundingClientRect.top):e.delete(t.target.id))}),k.current||!b.current)return;let r=ae.current+8,i=``,o=1/0;if(e.forEach((e,t)=>{let n=Math.abs(e-r);n<o&&(o=n,i=t)}),i&&i!==j.current){t&&clearTimeout(t);let e=i;t=setTimeout(()=>{e!==j.current&&(j.current=e,a(e))},150)}},{rootMargin:`-${E+8}px 0px -50% 0px`,threshold:[0,.1,.25,.5,.75,1]});return _.current.forEach(e=>e&&n.observe(e)),()=>{n.disconnect(),t&&clearTimeout(t)}},[F,a,E]);let oe=(0,V.useCallback)(e=>t=>{t?_.current.set(e,t):_.current.delete(e)},[]),se=FJ(new Date);return(0,H.jsxs)(`div`,{className:U(`bg-card`,s),"data-testid":`journal-date-scroll`,children:[(0,H.jsx)(`div`,{ref:T,className:`h-0`,"aria-hidden":!0}),(0,H.jsx)(`div`,{ref:p,className:`h-px`,"data-testid":`top-sentinel`}),F.map(e=>{let a=FJ(e),o=(I.get(a)??[]).filter(e=>e.type===`result`),s=r?.get(a),d=a===se,f=e>new Date(se+`T23:59:59`),p=!s&&o.length===0;return(0,H.jsxs)(`div`,{id:a,ref:oe(a),className:`flex flex-col`,style:{scrollMarginTop:E+8},children:[(0,H.jsxs)(`div`,{className:`sticky z-[5] px-6 py-2 bg-muted/80 backdrop-blur-sm border-y border-border flex items-center gap-2`,style:{top:E},children:[(0,H.jsx)(qt,{className:`size-3 text-muted-foreground`}),(0,H.jsxs)(`span`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,children:[VP(e),d&&(0,H.jsx)(`span`,{className:`ml-2 text-primary font-black`,children:`— Today`})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-0 pb-1`,children:[s?(()=>{let e={...s,title:zj(s.title)};return c?c({dateKey:a,entry:e,isToday:d,onOpenEntry:i}):(0,H.jsxs)(`button`,{onClick:()=>i?.(a),className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors`,children:(0,H.jsx)(N,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:U(`text-sm truncate`,e.title?`font-bold text-foreground`:`italic text-muted-foreground`),children:e.title||`Untitled note`}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium`,children:`Note`})]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]})})():null,(()=>{let e=o.filter(e=>e.group!==`playground`),n=o.filter(e=>e.group===`playground`),r=e=>l?l(e,t):(0,H.jsx)(PJ,{timeLabel:e.date?new Date(e.date).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}):`—`,title:e.title,subtitle:e.subtitle,onClick:()=>t(e)},`result-${e.id}`),i=(e,t)=>t.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-6 pt-2 pb-1`,children:[(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/40`}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-[0.2em] text-muted-foreground/50`,children:e}),(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/40`})]}),t.map(r)]});return(0,H.jsxs)(H.Fragment,{children:[i(`Workouts`,e),i(`Playground`,n)]})})(),p&&(u?u({date:e,dateKey:a,isFuture:f,isToday:d,onCreateEntry:n}):f?(0,H.jsx)(`button`,{"data-date":a,"data-testid":`journal-plan-workout`,onClick:()=>n?.(e),className:`flex items-center gap-3 px-6 py-3 text-left hover:bg-muted/30 transition-colors group`,children:(0,H.jsx)(`span`,{className:`text-[11px] text-muted-foreground/50 font-medium group-hover:text-primary transition-colors`,children:`+ Plan a workout`})}):(0,H.jsx)(`div`,{className:`px-6 py-2.5`,children:(0,H.jsx)(`span`,{className:`text-[11px] text-muted-foreground/30 font-medium`,children:`No activity`})}))]})]},a)}),(0,H.jsx)(`div`,{ref:m,className:`h-px`,"data-testid":`bottom-sentinel`}),ee&&M.start<=IJ(ee,-14)&&(0,H.jsxs)(`div`,{className:`flex items-center gap-3 px-6 py-6 select-none`,"aria-hidden":!0,children:[(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/30`}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-[0.2em] text-muted-foreground/40`,children:`Beginning of records`}),(0,H.jsx)(`div`,{className:`h-px flex-1 bg-border/30`})]})]})});RJ.displayName=`JournalDateScroll`;async function zJ({workoutName:e,category:t,sourceNoteLabel:n,sourceNotePath:r,wodContent:i,date:a,wrapInWod:o=!0}){let s=Bj(a??new Date),c=r?.trim()||`/collections/${encodeURIComponent(t)}`,l=[`# ${e}`,``];return o?l.push("```time",i.trimEnd(),"```"):l.push(i.trimEnd()),l.push(``),Kj.create({journalDate:s,title:zj(e),rawContent:l.join(`
164
+ `),sourceId:c})}function BJ(){let[e,t]=Gt(`s`,{defaultValue:``,shallow:!0,history:`replace`}),n=(0,V.useMemo)(()=>{if(e){let t=new Date(e+`T00:00:00`);if(!isNaN(t.getTime()))return t}return null},[e]),r=(0,V.useCallback)(e=>{if(!e)t(``);else{let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,`0`),i=String(e.getDate()).padStart(2,`0`);t(`${n}-${r}-${i}`)}},[t]),[i,a]=Gt(`feed`,{defaultValue:``,shallow:!0,history:`replace`}),o=(0,V.useCallback)(e=>{a(t=>t===e?``:e)},[a]),s=(0,V.useCallback)(()=>a(``),[a]);return{dateParam:e,selectedDate:n,setSelectedDate:r,setDateParam:t,selectedFeed:i||null,selectFeed:o,clearFeed:s}}function VJ({dateKeys:e,items:t,journalEntries:n,onSelectItem:r,onOpenEntry:i,onAddToToday:a,className:o}){let s=(0,V.useMemo)(()=>{let e=new Map;for(let n of t){let t=e.get(n.feedDate)??[];t.push(n),e.set(n.feedDate,t)}return e},[t]);return e.length===0?(0,H.jsxs)(`div`,{className:U(`flex flex-col items-center justify-center py-20 text-muted-foreground/50`,o),children:[(0,H.jsx)(`p`,{className:`text-sm font-medium`,children:`No feed content found.`}),(0,H.jsx)(`p`,{className:`text-xs mt-1`,children:`Feed workouts will appear here once content is available.`})]}):(0,H.jsx)(`div`,{className:U(`bg-card flex flex-col`,o),"data-testid":`feed-feed`,children:e.map(e=>{let t=new Date(e+`T00:00:00`),o=s.get(e)??[],c=n.get(e);return(0,H.jsxs)(`div`,{id:e,className:`flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`sticky z-[5] px-6 py-2 bg-muted/80 backdrop-blur-sm border-y border-border flex items-center gap-2 top-0`,children:[(0,H.jsx)(qt,{className:`size-3 text-muted-foreground flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,children:VP(t)})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-0 pb-1`,children:[c&&(0,H.jsxs)(`button`,{onClick:()=>i?.(e),className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors`,children:(0,H.jsx)(N,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate`,children:c.title}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium`,children:`Journal note`})]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]}),o.map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/30 transition-colors cursor-pointer group`,onClick:()=>r(e),children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors`,children:(0,H.jsx)(`span`,{className:`text-[10px] font-black text-primary`,children:`WOD`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground truncate`,children:e.name}),(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium mt-0.5`,children:e.feedName})]}),a&&(0,H.jsxs)(`button`,{onClick:t=>{t.stopPropagation(),a(e)},title:`Add to today's journal`,className:U(`flex items-center gap-1 rounded-full border border-border px-2.5 py-1`,`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,`hover:text-primary hover:border-primary/50 transition-colors shrink-0`,`opacity-0 group-hover:opacity-100`),children:[(0,H.jsx)(Kt,{className:`size-3`}),`Today`]}),(0,H.jsx)(Vn,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]},e.id))]})]},e)})})}function HJ({feedSlug:e}){let t=Sn(),{dateParam:n}=BJ(),r=n&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:null,i=sD(),a=(0,V.useMemo)(()=>i?pz(i).find(t=>t.id===e):void 0,[i,e]),[o,s]=(0,V.useState)(new Map),[c,l]=(0,V.useState)(!0);(0,V.useEffect)(()=>{let e=!1;async function t(){l(!0);try{if(!a)return;let t=Array.from(new Set(a.items.map(e=>e.feedDate))),n=await Promise.all(t.map(async e=>{let t=await uz.getPage(`journal/${e}`).catch(()=>void 0);return t?[e,{title:t.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??e,updatedAt:t.updatedAt}]:null}));if(e)return;let r=new Map;n.forEach(e=>e&&r.set(e[0],e[1])),s(r)}catch{}finally{e||l(!1)}}return t(),()=>{e=!0}},[a]);let u=(0,V.useMemo)(()=>a?a.items.map(e=>({id:e.id,feedId:a.id,feedName:a.name,feedDate:e.feedDate,name:e.name,content:e.content,path:e.path})):[],[a]),d=(0,V.useMemo)(()=>{if(r)return[r];let e=new Set(u.map(e=>e.feedDate));return Array.from(e).sort().reverse()},[r,u]),f=(0,V.useCallback)(async e=>{try{let n=await zJ({workoutName:e.name,category:e.feedId,sourceNoteLabel:e.feedName,sourceNotePath:`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`,wodContent:e.content,wrapInWod:!1}),r=FJ(new Date);Z({title:`Added to journal`,description:n.journalDate===r?`Added to today's journal`:`Added to ${n.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>t(KA(n.journalDate??r)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[t]),p=(0,V.useCallback)(e=>{t(`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`)},[t]),m=(0,V.useCallback)(e=>{t(`/journal/${e}`)},[t]);return a?c?(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm font-medium text-muted-foreground`,children:`Loading…`}):(0,H.jsx)(VJ,{dateKeys:d,items:u,journalEntries:o,onSelectItem:p,onOpenEntry:m,onAddToToday:f}):(0,H.jsxs)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm text-muted-foreground`,children:[`Feed not found: `,e]})}var UJ=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function WJ(e,t){return new Date(e,t+1,0).getDate()}function GJ(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function KJ(e,t,n){return`${e}-${String(t+1).padStart(2,`0`)}-${String(n).padStart(2,`0`)}`}function qJ(e){return KJ(e.getFullYear(),e.getMonth(),e.getDate())}var JJ=({selectedDate:e,onDateSelect:t,entryDates:n=new Set,disabled:r=!1,className:i})=>{let[a,o]=(0,V.useState)(()=>e||new Date),s=a.getFullYear(),c=a.getMonth();(0,V.useEffect)(()=>{e&&o(t=>t.getFullYear()!==e.getFullYear()||t.getMonth()!==e.getMonth()?new Date(e.getFullYear(),e.getMonth(),1):t)},[e]);let l=e?qJ(e):null,u=(0,V.useMemo)(()=>{let e=WJ(s,c),t=GJ(s,c),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[s,c]),d=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c-1,1))},f=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c+1,1))},p=a.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),m=qJ(new Date);return(0,H.jsxs)(`div`,{className:U(`select-none px-2 py-2`,r&&`opacity-60 cursor-not-allowed`,i),onClick:e=>e.stopPropagation(),"aria-disabled":r||void 0,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,H.jsx)(`button`,{onClick:d,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Previous month`,children:(0,H.jsx)(Tt,{className:`h-4 w-4`})}),(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:p}),(0,H.jsx)(`button`,{onClick:f,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Next month`,children:(0,H.jsx)(Vn,{className:`h-4 w-4`})})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 mb-1`,children:UJ.map(e=>(0,H.jsx)(`div`,{className:`text-center text-[10px] text-muted-foreground font-medium py-0.5 w-8`,children:e},e))}),(0,H.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:u.map((e,i)=>{if(e===null)return(0,H.jsx)(`div`,{className:`w-8 h-8`},`empty-${i}`);let a=KJ(s,c,e),o=n.has(a),u=a===l;return(0,H.jsxs)(`button`,{disabled:r,onClick:n=>{n.stopPropagation(),n.preventDefault(),t(new Date(s,c,e),n.ctrlKey||n.metaKey)},className:U(`w-8 h-8 flex items-center justify-center rounded text-xs transition-colors relative`,`disabled:pointer-events-none`,u?`bg-primary text-primary-foreground font-bold`:a===m?`font-bold text-primary ring-1 ring-primary/40`:o?`font-semibold text-foreground hover:bg-muted`:`text-muted-foreground hover:bg-muted/50`),"aria-label":`${e} ${p}${o?` (has entries)`:``}`,children:[e,o&&!u&&(0,H.jsx)(`span`,{className:`absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary/60`})]},a)})})]})};function YJ({onSave:e,getSnapshotKey:t,onError:n}){let r=(0,V.useRef)(null),i=(0,V.useRef)(null),a=(0,V.useRef)(null),o=(0,V.useRef)(Promise.resolve()),s=(0,V.useRef)({onSave:e,getSnapshotKey:t,onError:n});s.current={onSave:e,getSnapshotKey:t,onError:n};let[c,l]=(0,V.useState)(null),u=(0,V.useCallback)(e=>{let t=o.current.then(async()=>{e.key!==i.current&&(await s.current.onSave(e.value),i.current=e.key,l(null))});return o.current=t.catch(e=>{l(e),s.current.onError?.(e)}),t},[]),d=(0,V.useCallback)(()=>r.current?u(r.current):o.current,[u]),f=(0,V.useCallback)(e=>{let t=s.current.getSnapshotKey?.(e)??(typeof e==`string`?e:JSON.stringify(e));r.current={value:e,key:t}},[]),p=(0,V.useCallback)((e,t)=>{a.current!==null&&a.current!==e&&d().catch(()=>{}),a.current=e},[d]),m=(0,V.useCallback)(()=>{d().catch(()=>{})},[d]);return(0,V.useEffect)(()=>{let e=()=>{d().catch(()=>{})},t=()=>{document.visibilityState===`hidden`&&e()};return window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`pagehide`,e),document.removeEventListener(`visibilitychange`,t),d().catch(()=>{})}},[d]),{onChange:f,onLineChange:p,onBlur:m,flush:d,error:c}}var XJ=8e3;function ZJ({category:e,name:t,mdContent:n,seedOnMount:r=!0}){let i=az(e,t),[a,o]=(0,V.useState)(n),[s,c]=(0,V.useState)(!0),[l,u]=(0,V.useState)(),[d,f]=(0,V.useState)({}),[p,m]=(0,V.useState)(0),[h,g]=(0,V.useState)(null),_=(0,V.useRef)({id:i,revision:0}),v=(0,V.useRef)(i);v.current=i;let y=(0,V.useRef)({rawContent:n,noteBlocks:{},sourceRevision:0}),b=(0,V.useCallback)(e=>{_.current.revision=e.sourceRevision,m(e.sourceRevision),y.current.rawContent===e.rawContent&&Object.keys(y.current.noteBlocks).length===Object.keys(e.blocks).length&&Object.values(y.current.noteBlocks).every(t=>{let n=e.blocks[t.id];return n&&n.from===t.from&&n.to===t.to&&n.kind===t.kind})&&(y.current={rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision},f(e.blocks))},[]),x=YJ({onSave:(0,V.useCallback)(async e=>{if(e.routeId===v.current&&h)throw h;let t=await Nj.saveNote({noteId:e.noteId,rawContent:e.rawContent,blocks:e.noteBlocks,expectedSourceRevision:_.current.id===e.noteId?_.current.revision:e.sourceRevision,metadata:{title:e.title},noteType:`playground`});v.current===e.routeId&&(_.current.id=t.id,u(t.id),b({rawContent:t.rawContent,blocks:t.blocks??{},sourceRevision:t.sourceRevision??1}))},[b,h]),getSnapshotKey:e=>JSON.stringify([e.noteId,e.rawContent,Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])});(0,V.useEffect)(()=>{let e=!1;_.current={id:i,revision:0},c(!0),g(null);let a=Aa(n,{sourceRevision:1,registeredWidgets:wa}),s=(e,t,n,r)=>{o(e),f(t),m(n),u(r),_.current={id:r??i,revision:n},y.current={rawContent:e,noteBlocks:t,sourceRevision:n}},l=setTimeout(()=>{e||(e=!0,s(n,a,0),g(Error(`Note load timed out. Reload before saving to avoid overwriting stored content.`)),c(!1))},XJ);return(async()=>{try{let o=await uz.getPage(i);if(e)return;if(o)s(o.content,o.noteBlocks??{},o.sourceRevision??1,o.id);else if(r){let r=await Nj.saveNote({noteId:i,rawContent:n,blocks:a,expectedSourceRevision:0,metadata:{title:t},noteType:`playground`});e||s(r.rawContent,r.blocks??{},r.sourceRevision??1,r.id)}else s(n,a,0)}catch(t){e||(s(n,a,0),g(t))}finally{clearTimeout(l),e||c(!1)}})(),()=>{e=!0,clearTimeout(l)}},[i,n,t,r]);let S=(0,V.useCallback)(e=>{(y.current.rawContent!==e.rawContent||JSON.stringify(Object.values(y.current.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))&&(y.current=e,o(e.rawContent),f(e.noteBlocks),x.onChange({...e,routeId:i,noteId:_.current.id,title:t}))},[x.onChange,i,t]),C=(0,V.useCallback)(e=>{if(o(e),y.current.rawContent===e)return;let t=Aa(e,{sourceRevision:_.current.revision||1,registeredWidgets:wa});S({rawContent:e,noteBlocks:t,sourceRevision:_.current.revision})},[S]),w=(0,V.useCallback)(async()=>{S({rawContent:n,sourceRevision:_.current.revision,noteBlocks:Aa(n,{sourceRevision:_.current.revision||1,registeredWidgets:wa})}),await x.flush()},[n,S,x.flush]),T=(0,V.useCallback)(()=>_.current.revision,[]);return{content:a,loading:s,entryId:l,noteBlocks:d,sourceRevision:p,onIdentityChange:S,onSaved:b,onChange:C,onLineChange:x.onLineChange,onBlur:x.onBlur,flush:x.flush,committedSourceRevision:T,resetToOriginal:w,isModified:a!==n,error:x.error??h}}var QJ=new Map;function $J(e,t,n){let r=t?e.filter(e=>e.blockId===t):e;if(r.length===0)return{current:[],currentVersion:0,history:new Map};let i=new Map;for(let e of r){let t=e.blockVersion;i.has(t)||i.set(t,[]),i.get(t).push(e)}let a=[],o=0;for(let[e,t]of i)t.some(e=>e.blockContentId===n)&&(e>o?(o=e,a.length=0,a.push(...t)):e===o&&a.push(...t));let s=new Map;for(let[e,t]of i)e!==o&&s.set(e,{version:e,contentId:t[0]?.blockContentId,results:t});return{current:a,currentVersion:o,history:s}}function eY(e,t,n,r,i){let a=e.map(e=>{if(e.type!==`time`&&e.type!==`log`)return e;let i=parseInt(e.id.replace(`${e.type}-line-`,``),10),a=t.find(e=>e.startLine+1===i),o={};if(r&&a){let{current:e}=$J(r,a.id,a.contentId);o={hasResult:e.length>0,resultCount:e.length}}return e.type===`log`||!n?{...e,...o}:{...e,...o,onRun:()=>{let e=a||t.find(e=>e.startLine+1===i)||t[0];e&&n(e)}}});if(i){let e=a.findIndex(e=>e.type===`heading`),t=e===-1?0:e;if(a[t])return a.map((e,n)=>n===t?{...e,onRun:i,runIcon:`edit`}:e)}return a}function tY({content:e,scriptBlocks:t,onStartWorkout:n,results:r,onEditNote:i}){let a=(0,V.useMemo)(()=>eY(Wz(e),t,n,r,i),[e,t,n,r,i]),{setL3Items:o}=hA();return(0,V.useEffect)(()=>(o(Gz(a)),()=>o([])),[a,o]),a}function nY(e){switch(e.kind){case`journal`:return KA(e.id);case`playground`:return WA(e.id);case`workout`:return e.category===`effort`?cj(e.id):e.category===`equipment`?ij(e.id):e.category?ZA(e.category,e.id):qA(e.raw)}}function rY(e){let t=ZF(e);return t.kind===`workout`&&!t.category?qA(e):nY(t)}var iY={efforts:[],related:[],backlinks:[]},aY=8;function oY(e){let t=e.id,n=e.type===`playground`||e.sourceId===`playground`||t.startsWith(`playground/`),r=ZF(t);if(e.type===`journal`||e.journalDate||!n&&r.kind===`journal`){let n=e.journalDate??(r.kind===`journal`?r.id:void 0);return{zone:`journal`,up:n?{id:n,title:`Journal`,to:GA(n)}:null,stamps:[t]}}if(n||r.kind===`playground`){let e=cI({id:t});return{zone:`playgrounds`,up:{id:`playgrounds`,title:`Playgrounds`,to:nj()},stamps:[`/playground/${e}`]}}if(r.kind===`workout`){if(r.category===`effort`)return{zone:`efforts`,up:{id:`efforts`,title:`Efforts`,to:rj()},stamps:[cj(r.id)]};if(r.category===`equipment`)return{zone:`equipment`,up:{id:`equipment`,title:`Equipment`,to:Q.equipment},stamps:[ij(r.id)]};if(r.category===`feeds`){let[,e,n,r]=t.split(`/`);return{zone:`feeds`,up:e?{id:e,title:e,to:YA(e)}:null,stamps:e&&n&&r?[`/feeds/${e}/${n}/${r}`]:[]}}if(r.category)return{zone:`feeds`,up:{id:r.category,title:r.category,to:XA(r.category)},stamps:[ZA(r.category,r.id)]}}if(e.type===`page`&&(e.pageId??e.slug)){let t=e.pageId??e.slug;return{zone:null,up:{id:t,title:`/p/${t}`,to:tj(t)},stamps:[]}}return{zone:null,up:null,stamps:[]}}function sY(e){if(!e.startsWith(`/`))return null;let t=e.split(`#`)[0],n=t.replace(/\/+$/,``).split(`/`).filter(Boolean),r=n[n.length-1];if(r)try{r=decodeURIComponent(r)}catch{}return{id:t,title:r||t,to:t}}function cY(e,t){let n=new Set,r=[];for(let i of e){if(!i.effortSlug||n.has(i.effortSlug))continue;n.add(i.effortSlug);let e=!t||t.has(i.effortSlug);r.push({id:i.effortSlug,title:i.effortSlug,to:e?cj(i.effortSlug):`${rj()}?q=${encodeURIComponent(i.effortSlug)}`})}return r}function lY(e,t,n=aY){let r=new Set(e.filter(e=>e.noteId===t&&e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId));if(r.size===0)return[];let i=new Map;for(let a of e)if(a.dataType===`wod`&&!(!a.blockContentId||!r.has(a.blockContentId)||a.noteId===t)&&!i.has(a.noteId)&&(i.set(a.noteId,{id:a.noteId,title:a.noteTitle||a.noteId,to:rY(a.noteId)}),i.size>=n))break;return[...i.values()]}function uY(e,t,n){if(t.length===0)return[];let r=e.filter(e=>e.id!==n&&!!e.sourceId&&t.some(t=>e.sourceId===t||e.sourceId.startsWith(`${t}#`)));return r.sort((e,t)=>t.createdAt-e.createdAt),r.map(e=>({id:e.id,title:e.title||e.id,to:rY(e.id)}))}function dY(e,t){let n=new Map;for(let r of e)r.noteId===t||n.has(r.noteId)||n.set(r.noteId,{id:r.noteId,title:r.noteId,to:rY(r.noteId)});return[...n.values()]}function fY({noteId:e,stamps:t,effortSlug:n}){let r=t.join(`
165
+ `),[i,a]=(0,V.useState)({key:``,data:iY}),o=`${e}\u0000${r}\u0000${n??``}`,s=i.key===o?i.data:iY;return(0,V.useEffect)(()=>{let t=!1,i=r?r.split(`
166
+ `):[];return Promise.all([X.getAllFromIndex(`block_efforts`,`by-note`,e),X.getAllFromIndex(`block_index`,`by-note`,e),X.getAllNotes(),X.getAllEfforts(),n?X.getAllFromIndex(`block_efforts`,`by-effort`,n):Promise.resolve([])]).then(async([r,a,o,s,c])=>{if(t)return iY;let l=new Set(s.map(e=>e.slug)),u=[...new Set(a.filter(e=>e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId))],d=await Promise.all(u.map(e=>X.getAllFromIndex(`block_index`,`by-content`,e)));if(t)return iY;let f=lY([...a,...d.flat()],e);if(n){let t=new Set(f.map(e=>e.id));for(let n of dY(c,e))t.has(n.id)||(t.add(n.id),f.push(n))}return{efforts:cY(r,l),related:f,backlinks:uY(o,i,e)}}).then(e=>{!t&&e&&a({key:o,data:e})}).catch(()=>{}),()=>{t=!0}},[e,r,n,o]),s}function pY({data:e,up:t,source:n,relatedLabel:r=`Related workouts`}){let{setContextNav:i}=hA(),a=mt();return(0,V.useEffect)(()=>{let o=[],s=(e,t,n)=>{n.length!==0&&o.push({kind:`section`,id:e,label:t,entries:n.map(t=>({kind:`link`,id:`${e}:${t.id}`,label:t.title,to:t.to}))})};return s(`note-context-up`,`Up`,t?[t]:[]),s(`note-context-source`,`Source`,n?[n]:[]),s(`note-context-efforts`,`Efforts`,e.efforts),s(`note-context-backlinks`,`Journal copies`,e.backlinks),s(`note-context-related`,r,e.related),i({pathname:a.pathname,spec:o}),()=>i(void 0)},[e,t,n,r,a.pathname,i]),null}function mY(e,t){return(0,V.useMemo)(()=>{let n=[];return t.onPlay&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`play`,label:`Play`,icon:(0,H.jsx)(rn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:t.onPlay}),t.onLog&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`log`,label:`Log`,icon:(0,H.jsx)(Be,{className:`h-3 w-3`}),primary:!0,onClick:t.onLog}),t.onOpenInPlayground&&(e===`journal-plan`||e===`collection-readonly`)&&n.push({id:`open-in-playground`,label:`Playground`,icon:(0,H.jsx)(o,{className:`h-3 w-3`}),onClick:t.onOpenInPlayground}),t.onShare&&n.push({id:`share`,label:`Share`,icon:(0,H.jsx)(g,{className:`h-3 w-3`}),onClick:t.onShare}),t.onAddToToday&&e===`playground`&&n.push({id:`add-to-today`,label:`Today`,icon:(0,H.jsx)(ye,{className:`h-3 w-3`}),onClick:t.onAddToToday}),t.onSchedule&&n.push({id:`schedule`,label:`Schedule`,icon:(0,H.jsx)(Ae,{className:`h-3 w-3`}),onClick:t.onSchedule}),n},[e,t.onPlay,t.onLog,t.onShare,t.onAddToToday,t.onSchedule,t.onOpenInPlayground])}async function hY(e){let t=new TextEncoder().encode(e),n=new CompressionStream(`gzip`),r=n.writable.getWriter(),i=n.readable.getReader();r.write(t),r.close();let a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;let l=``;for(let e=0;e<s.length;e++)l+=String.fromCharCode(s[e]);return btoa(l).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function gY(e,t){let n=e.dialect||`time`,r=await hY(`\`\`\`${e.sport?`${n}:${e.sport}`:n}\n${e.content.trimEnd()}\n\`\`\`\n`),i=`${window.location.origin}${$A({zip:r})}`;return t?`${i}&src=${encodeURIComponent(t)}`:i}async function _Y(e,t){let n=await gY(e,window.location.pathname),{pathname:r,search:i}=new URL(n);t(`${r}${i}`)}async function vY(e){let t=await gY(e,window.location.pathname);window.open(t,`_blank`)}async function yY(e){let t=e.dialect||`time`,n=await hY(`\`\`\`${e.sport?`${t}:${e.sport}`:t}\n${e.content.trimEnd()}\n\`\`\`\n`),r=`shared by ${Yy()}`;return`${window.location.origin}/?z=${n}&by=${encodeURIComponent(r)}`}function bY(e){yY(e).then(e=>{navigator.clipboard.writeText(e).then(()=>{Z({title:`Link copied`,description:`Share link copied to clipboard.`})}).catch(()=>{Z({title:`Could not copy`,description:e,variant:`destructive`})})})}function xY(e=`end`){let t=(0,V.useRef)(null),[n,r]=(0,V.useState)(e);return{triggerRef:t,align:n,recompute:(0,V.useCallback)(()=>{let e=t.current;if(!e)return;let{left:n,right:i}=e.getBoundingClientRect(),a=(n+i)/2;r(a>window.innerWidth/2?`end`:`start`)},[])}}function SY(e,t){if(t){t();return}let n=new Blob([e.content],{type:`text/markdown`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.name.replace(/[/\\:*?"<>|]/g,`-`)}.md`,i.click(),URL.revokeObjectURL(r)}function CY({currentWorkout:e,onDownload:t}){return e.content===``?null:(0,H.jsxs)(`button`,{type:`button`,onClick:()=>SY(e,t),className:`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,H.jsx)(Be,{className:`size-4 shrink-0`}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Download Markdown`})]})}function wY(e,t,n){let r=Sn(),{l3Items:i,scrollToSection:a,secondarySpec:o,streamControls:s}=hA(),c=t&&t.length>0?t:i,l=MI(o),u=[];s&&u.push({kind:`custom`,id:`l3-stream-controls`,nav:!0,render:()=>(0,H.jsx)(IL,{streamControls:s})});for(let e of l)if(e.kind===`section`){if(e.entries.length===0)continue;u.push({kind:`heading`,id:e.id,label:e.label,nav:!0});for(let t of e.entries)u.push({kind:`row`,id:t.id,label:t.label,nav:!0,onSelect:()=>{t.onRun?t.onRun():t.to?r(t.to):t.sectionId&&a(t.sectionId)}})}else u.push({kind:`row`,id:e.id,label:e.label,nav:!0,onSelect:()=>{e.onRun?e.onRun():e.to?r(e.to):e.sectionId&&a(e.sectionId)}});if(c.length>0){u.push({kind:`heading`,id:`on-this-page`,label:`On this page`,nav:!0});for(let e of c)u.push({kind:`row`,id:e.id,label:e.label,nav:!0,secondary:e.secondaryAction?{label:e.secondaryAction.label,icon:e.secondaryAction.icon&&(0,H.jsx)(e.secondaryAction.icon,{className:`size-3.5`}),onSelect:()=>{e.secondaryAction?.action.type===`call`&&e.secondaryAction.action.handler()}}:void 0,onSelect:()=>{e.action.type===`call`?e.action.handler():a(e.id)}})}return e.content!==``&&u.push({kind:`row`,id:`download-markdown`,label:`Download Markdown`,icon:(0,H.jsx)(Be,{className:`size-4`}),nav:!1,onSelect:()=>SY(e,n)}),u}function TY({currentWorkout:e,onDownload:t,items:n}){let r=wY(e,n,t),i=e=>e.kind===`heading`?(0,H.jsx)(SL,{children:e.label},e.id):e.kind===`custom`?(0,H.jsx)(`div`,{className:`px-1 py-1`,children:e.render()},e.id):(0,H.jsxs)(yL,{onClick:e.onSelect,className:`gap-2`,children:[e.icon,(0,H.jsx)(`span`,{className:U(`flex-1 truncate`,e.secondary&&`pr-8`),children:e.label}),e.secondary&&(0,H.jsx)(`button`,{className:`ml-auto flex items-center justify-center size-5 rounded text-primary hover:bg-primary/10 transition-colors`,title:e.secondary.label,onClick:t=>{t.stopPropagation(),e.secondary?.onSelect()},children:e.secondary.icon})]},e.id),a=r.filter(e=>e.nav),o=r.filter(e=>!e.nav);return r.length===0?null:(0,H.jsxs)(gL,{children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(W,{variant:`ghost`,size:`icon`,"aria-label":`Page options`,className:U(`text-muted-foreground`,`2xl:hidden`),children:[(0,H.jsx)(ge,{className:`size-5`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Page options`})]})}),(0,H.jsxs)(vL,{align:`end`,className:`min-w-56 max-h-[calc(100dvh-6rem)] overflow-y-auto`,children:[a.length>0&&(0,H.jsxs)(`div`,{className:`2xl:hidden`,children:[a.map(i),(0,H.jsx)(xL,{})]}),o.map(i)]})]})}var EY=Hz("# My Workout\n\n```time\n$CURSOR\n```\n"),DY={content:EY.content,cursorOffset:EY.cursorOffset};function OY({mode:e,currentWorkout:t,index:n,onReset:r}){let i=Sn(),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(!1),l=tR(),u=UL(),d=l&&u;return d&&e!==`playground`?null:(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[e===`playground`&&(0,H.jsx)(TU,{primary:{id:`new-playground`,label:a?`Creating…`:`New`,icon:ye,action:{type:`call`,handler:async()=>{if(!a){o(!0);try{let e=await hH(DY.content);i(`/playground/${encodeURIComponent(e)}`)}finally{o(!1)}}}}},secondary:{id:`reset-playground`,label:s?`Resetting…`:`Reset to default`,icon:We,action:{type:`call`,handler:async()=>{if(!(!r||s)){c(!0);try{await r()}finally{c(!1)}}}}},size:`sm`}),!d&&(0,H.jsx)(IR,{}),!d&&(0,H.jsx)(YG,{}),!d&&(0,H.jsx)(TY,{currentWorkout:t,items:n&&n.length>0?Gz(n):void 0})]})}function kY({feedSlug:e,feedDate:t,feedItem:n,theme:r,onViewCreated:i}){let a=Sn(),o=sD(),{item:s,feed:c}=(0,V.useMemo)(()=>{if(!o)return{item:void 0,feed:void 0};let r=pz(o).find(t=>t.id===e);return{item:r?.items.find(e=>e.feedDate===t&&e.id===n),feed:r}},[o,e,t,n]),{content:l,noteBlocks:u,sourceRevision:d,onIdentityChange:f,onSaved:p,onChange:m,onLineChange:h,onBlur:g,flush:_}=ZJ({category:`feed/${e}/${t}`,name:n,mdContent:s?.content??`# ${n}\n\n*Feed item not found.*\n`,seedOnMount:!1}),[v,y]=(0,V.useState)([]),b=`feed/${e}/${t}/${n}`,x=(0,V.useCallback)(async r=>{try{let i=C(),o=await zJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),l=Object.values(o.blocks??{}).find(e=>e.kind===`wod`);if(!l)throw Error(`The saved journal workout is unavailable.`);QJ.set(i,{block:{...r,id:l.id},noteId:o.id}),a(JA(o.journalDate??``,i))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[c,t,n,e,s,a,b]),S=(0,V.useCallback)(async r=>{try{let i=await zJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),o=FJ(new Date);Z({title:`Added to journal`,description:i.journalDate===o?`Added to today's journal`:`Added to ${i.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>a(KA(i.journalDate??o)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[c,t,n,e,s,a]),[w,T]=(0,V.useState)(null),E=(0,V.useCallback)(async(r,i)=>{let o=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,`0`)}-${String(i.getDate()).padStart(2,`0`)}`;try{await zJ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content,date:i}),a(KA(o)),Z({title:`Scheduled`,description:`Added to journal for ${o}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>a(KA(o)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[c,t,n,e,s,a]),D=tY({content:l,scriptBlocks:v,onStartWorkout:x}),O=`feeds/${e}/${t}/${n}`,k=(0,V.useMemo)(()=>oY({id:O,type:`collection`}),[O]),A=fY({noteId:O,stamps:k.stamps}),j=mY(`collection-readonly`,{onPlay:x,onShare:bY,onAddToToday:S,onSchedule:T,onOpenInPlayground:e=>_Y(e,a)});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fL,{title:s?.name??n,actions:(0,H.jsx)(nR,{label:`Workout actions`,children:(0,H.jsx)(OY,{mode:`collection-readonly`,currentWorkout:{name:s?.name??n,content:l},index:D})}),editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(pY,{data:A,up:k.up}),(0,H.jsx)(vK,{value:l,onChange:m,onCursorPositionChange:h,onBlur:g,noteId:b,noteBlocks:u,sourceRevision:d,onIdentityChange:e=>f({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:p,onSaveRequest:_,onCommitChange:_,commands:j,enableInlineRuntime:!1,onViewCreated:i,theme:r,showLineNumbers:!1,onBlocksChange:y})]})}),w&&(0,H.jsx)(lS,{open:!0,onClose:()=>T(null),title:`Schedule workout`,children:(0,H.jsx)(JJ,{selectedDate:null,onDateSelect:e=>{E(w,e),T(null)}})})]})}function AY(e,t){if(e.startsWith(`# 👋`))return e;let n=t?.replace(/^shared by:?\s*/i,``).trim();return`${n?`# 👋 ${n} sent you this workout`:`# 👋 Edit Me`}\n\nChange the reps, distance, or load below — this is live.\n\n${e}\n\n> Press **Run** ↑ to start the Clock.\n`}var jY=`wodwiki.homeShared.v1`;function MY(){return typeof window<`u`&&window.localStorage?window.localStorage:null}function NY(e){try{MY()?.setItem(jY,JSON.stringify(e)),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`wodwiki:home-shared`,{detail:e}))}catch{}}function PY(){try{let e=MY()?.getItem(jY);if(!e)return null;let t=JSON.parse(e);return typeof t?.content==`string`?{content:t.content,by:typeof t.by==`string`?t.by:void 0}:null}catch{return null}}function FY(){try{MY()?.removeItem(jY)}catch{}}function IY({pageRoute:e,quests:t,running:n}){let{markComplete:r}=OH(e,t),i=(0,V.useMemo)(()=>t.filter(e=>e.validation?.type===`run-started`),[t]);(0,V.useEffect)(()=>{if(n)for(let e of i)r(e.id)},[n,i,r])}var LY={"session-insights":`qs-tour-analytics`},RY={"workout-complete":!0,"run-started":!0};function zY(e,t){let{markComplete:n}=OH(e,t),r=(0,V.useRef)(new Set);return r.current=new Set(t.filter(e=>!e.validation||!RY[e.validation.type]).map(e=>e.id)),(0,V.useCallback)(e=>{let t=LY[e];t&&r.current.has(t)&&n(t)},[n])}var BY=(0,V.createContext)(null);function VY({children:e}){let t=(0,V.useRef)({"editor.window":null,"editor.wodBlock":null,"editor.runButton":null,"editor.typeahead":null,"timer.floor":null,"timer.nextButton":null,"timer.castButton":null,"metrics.efforts":null,"metrics.data":null,"metrics.compound":null,"analytics.vocab":null,"analytics.table":null,"analytics.graphs":null,"analytics.dashboard":null}),[n,r]=(0,V.useState)(0),i=(0,V.useCallback)((e,n)=>{t.current[e]!==n&&(t.current[e]=n,r(e=>e+1))},[]);return(0,H.jsx)(BY.Provider,{value:{register:i,registry:t,version:n},children:e})}function HY(){return(0,V.useContext)(BY)||{registry:{current:{}},register:()=>()=>{},version:0}}function UY(e){let t=(0,V.useContext)(BY)?.register;return(0,V.useCallback)(n=>t?.(e,n),[e,t])}function WY({ringKey:e,el:t}){let{register:n}=HY();return(0,V.useLayoutEffect)(()=>{n(e,t)},[e,t,n]),null}function GY({target:e,accent:t,canvasRef:n}){let{registry:r,version:i}=HY(),[a,o]=(0,V.useState)(null),s=e?.key??null;return(0,V.useLayoutEffect)(()=>{if(!s){o(null);return}let e=()=>{let e=r.current[s],t=n.current;if(!e||!t){o(null);return}let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),c=Math.round(i.left-a.left),l=Math.round(i.top-a.top),u=Math.round(i.width),d=Math.round(i.height);if(u<=0||d<=0||c+u<0||l+d<0||c>a.width||l>a.height){o(null);return}o({x:c,y:l,w:u,h:d})};e();let t=window.setTimeout(e,120),i=window.setTimeout(e,480),a=null,c=r.current[s];c&&typeof ResizeObserver<`u`&&(a=new ResizeObserver(e),a.observe(c));let l=new MutationObserver(e);return c&&l.observe(c,{attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`resize`,e),()=>{window.clearTimeout(t),window.clearTimeout(i),a?.disconnect(),l.disconnect(),window.removeEventListener(`resize`,e)}},[s,i,r,n]),!e||!a?null:(0,H.jsx)(`div`,{"data-testid":`tour-ring`,className:`pointer-events-none absolute z-30 rounded-2xl transition-all duration-500 ease-out`,style:{left:a.x-6,top:a.y-6,width:a.w+12,height:a.h+12,boxShadow:`0 0 0 2px ${t}`}})}var KY=`hsl(var(--primary))`,qY={ink:`hsl(var(--foreground))`,editor:KY,timer:KY,analytics:KY,library:KY,rounds:KY},JY={editor:`WOD Editor & Autocomplete`,timer:`Clock`,analytics:`WQL Analytics`,metrics:`Own the Metrics`,result:`Run Results`},YY={start:`/guide/start`,protocols:`/guide/protocols`,structure:`/guide/structure`,metrics:`/guide/metrics`,clock:`/guide/clock`,wql:`/guide/wql`,dashboards:`/guide/dashboards`,sessions:`/guide/sessions`,basics:`/guide/start`,"custom-metrics":`/guide/metrics`,dialects:`/guide/sessions#intent`,complex:`/guide/sessions#full-session`};function XY(){return(0,H.jsxs)(`div`,{className:`@container flex w-full flex-col items-center text-center`,children:[(0,H.jsxs)(`h1`,{className:`text-[clamp(32px,6.5cqi,64px)] font-extrabold leading-[1.02] tracking-[-0.04em]`,children:[(0,H.jsxs)(`span`,{className:`block`,children:[(0,H.jsx)(`span`,{className:`mr-[0.35em]`,children:`Write it.`}),(0,H.jsx)(`span`,{children:`Time it.`})]}),(0,H.jsxs)(`span`,{className:`block`,children:[(0,H.jsx)(`span`,{className:`mr-[0.35em]`,children:`Track it.`}),(0,H.jsx)(`span`,{children:`Own it.`})]})]}),(0,H.jsxs)(`p`,{className:`mt-4 xl:mt-6 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[15px] sm:text-base xl:text-lg leading-relaxed text-muted-foreground`,children:[`Plain-text Markdown becomes a step-through workout clock, `,(0,H.jsx)(`br`,{}),`line and splits become queryable training data points.`]})]})}var ZY=`https://github.com/bitcobblers/wod-wiki`;function QY(){return(0,H.jsx)(`footer`,{"data-testid":`tour-footer`,className:`border-t border-border px-6 py-8`,children:(0,H.jsxs)(`p`,{className:`mx-auto flex max-w-3xl flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground`,children:[(0,H.jsxs)(`span`,{children:[`© `,new Date().getFullYear(),` WOD Wiki`]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsx)(`a`,{href:ZY,target:`_blank`,rel:`noopener noreferrer`,className:`underline-offset-4 transition-colors hover:text-foreground hover:underline`,children:`GitHub repository`})]})})}async function $Y(){await xD.wipe();try{for(let e=localStorage.length-1;e>=0;e--){let t=localStorage.key(e);t&&t!==`wodwiki.dataSettings.v1`&&localStorage.removeItem(t)}}catch{}try{sessionStorage.clear()}catch{}}function eX({index:e,before:t,accentText:n,after:r,accent:i,blurb:a}){return(0,H.jsx)(`header`,{className:`flex items-center border-b border-border/60 px-6 py-14 lg:px-12 xl:py-20 2xl:py-24 xl:px-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px]`,children:[(0,H.jsxs)(`h2`,{className:`flex items-baseline gap-4 xl:gap-6 text-[clamp(26px,3.6vw,52px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[(0,H.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:e}),(0,H.jsxs)(`span`,{children:[t,n,r]})]}),(0,H.jsx)(`p`,{className:`mt-3 xl:mt-4 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:a})]})})}var tX=`https://github.com/bitcobblers/wod-wiki`,nX=`https://forms.gle/6YHpxwAJh6PAsyAQ6`,rX=`underline-offset-4 transition-colors hover:text-foreground hover:underline`;function iX(e){let t=`inline-flex items-center gap-1.5 font-medium text-foreground underline-offset-4 transition-colors hover:underline`,n=(0,H.jsxs)(H.Fragment,{children:[e.children,(0,H.jsx)(h,{className:`size-3.5 text-muted-foreground/50`,"aria-hidden":!0})]});return e.href===void 0?e.onClick===void 0?(0,H.jsx)(Wn,{to:e.to,className:t,children:n}):(0,H.jsx)(`button`,{type:`button`,onClick:e.onClick,className:`text-left ${t}`,children:n}):(0,H.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noopener noreferrer`,className:t,children:n})}function aX({children:e}){return(0,H.jsxs)(`li`,{className:`flex gap-2.5 text-sm leading-6 text-muted-foreground`,children:[(0,H.jsx)(`span`,{"aria-hidden":!0,className:`mt-[11px] size-1 shrink-0 rounded-full bg-muted-foreground/50`}),(0,H.jsx)(`span`,{children:e})]})}function oX(){return(0,H.jsx)(`span`,{className:`rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 font-mono text-[11px] font-medium text-emerald-600`,children:`Active`})}function sX(e){let t=e.icon;return(0,H.jsxs)(`article`,{className:`flex flex-col rounded-xl border border-border bg-background p-5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,H.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),e.badge]}),(0,H.jsx)(`h3`,{className:`mt-4 text-base font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.text}),(0,H.jsx)(`div`,{className:`mt-4 flex flex-1 flex-col gap-2 text-sm`,children:e.children})]})}function cX(){let[e,t]=(0,V.useState)(!1),n=Sn(),[r]=(0,V.useState)(hD),i=async()=>{window.confirm(`Wipe every note, result, and setting stored in this browser? This cannot be undone.`)&&(t(!0),await $Y(),window.location.reload())},a=async()=>{let e=Vj(),t=await Kj.create({journalDate:e,title:e,rawContent:``});oH.record(sH.noteCreated),n(qA(t.id))};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`section`,{id:`tour-section-offerings`,"data-testid":`tour-section-offerings`,"aria-label":`You own your data`,children:[(0,H.jsx)(eX,{index:`03`,before:`You `,accentText:`Own the Data`,after:``,accent:qY.library,blurb:`Browser modes run from IndexedDB, with optional backup and sync to your own Turso database. API deployments use a server you choose.`}),(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 pb-16 pt-10 lg:px-12 xl:px-16`,children:[(0,H.jsxs)(`p`,{className:`mx-auto mb-5 flex max-w-5xl flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground`,role:`status`,children:[(0,H.jsx)(`span`,{children:`Current mode: API server`}),(0,H.jsx)(Wn,{to:Q.settingsStorage,className:rX,children:`Configure data storage`})]}),(0,H.jsxs)(`div`,{className:`mx-auto grid max-w-5xl grid-cols-1 gap-5 md:grid-cols-3`,children:[(0,H.jsxs)(sX,{icon:je,title:`Browser only`,badge:void 0,text:`Everything lives in this browser's IndexedDB — the default mode. Works offline, no account, no server copy.`,children:[(0,H.jsx)(iX,{onClick:()=>void a(),children:`Create your journal`}),(0,H.jsx)(iX,{to:Q.playgroundRoot,children:`Start Writing in a Playground`}),(0,H.jsx)(iX,{to:`/feeds`,children:`Explore the notebooks`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(aX,{children:`Offline and fast. Notes and results stay in this browser.`}),(0,H.jsx)(aX,{children:`Tied to this browser — export or back it up before switching browsers or clearing site data.`})]}),(0,H.jsx)(`button`,{type:`button`,onClick:i,disabled:e,className:`mt-1 text-left text-xs text-muted-foreground disabled:opacity-50 ${rX}`,children:e?`Clearing…`:`Clear my data`})]}),(0,H.jsxs)(sX,{icon:ie,title:`Browser + your Turso`,badge:void 0,text:`Same local execution — plus a background backup of your data to a free Turso database you own, so multiple browsers stay in sync.`,children:[(0,H.jsx)(iX,{to:Q.settingsStorage,children:`Configure backup & sync`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(aX,{children:`Queries still run locally in the browser — sync copies committed changes in the background.`}),(0,H.jsx)(aX,{children:`Bring your own free Turso database — URL and auth token, kept in this browser only.`}),(0,H.jsx)(aX,{children:`Sync needs network; without it you keep working locally and changes upload later.`})]})]}),(0,H.jsxs)(sX,{icon:ln,title:`API server`,badge:(0,H.jsx)(oX,{}),text:`Build the app for API storage and run the Wod Wiki server yourself — local or cloud data access through a server you administer.`,children:[(0,H.jsx)(iX,{href:tX,children:`View source`}),(0,H.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,H.jsx)(aX,{children:`Centralized data for a team or gym — one SQLite, Turso, or Postgres backend.`}),(0,H.jsx)(aX,{children:`You run the server — network required, and server admin is on you.`})]})]})]})]})]}),(0,H.jsxs)(`section`,{id:`tour-section-hosted`,"data-testid":`tour-section-hosted`,"aria-label":`Wod-Wiki hosted`,children:[(0,H.jsx)(eX,{index:`04`,before:`Wod-Wiki `,accentText:`Hosted`,after:``,accent:qY.library,blurb:`Rather hand the caretaking to us? Wod-Wiki hosted is still taking shape — fill out the survey and help shape the plans.`}),(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 pb-16 pt-10 lg:px-12 xl:px-16`,children:(0,H.jsxs)(`div`,{className:`mx-auto grid max-w-5xl grid-cols-1 gap-5 md:grid-cols-2`,children:[(0,H.jsxs)(sX,{icon:vr,title:`Individuals`,text:`For people who don't want dev-level configuration — we host the database for you and keep every device in sync.`,children:[(0,H.jsxs)(`ul`,{className:`space-y-1.5`,children:[(0,H.jsx)(aX,{children:`Managed hosting — we run the database; you just sign in.`}),(0,H.jsx)(aX,{children:`Profile page with a public feed.`}),(0,H.jsx)(aX,{children:`Sync across your apps and devices.`})]}),(0,H.jsxs)(`div`,{className:`mt-auto pt-3`,children:[(0,H.jsx)(iX,{href:nX,children:`Fill out interest survey`}),(0,H.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:`Takes two minutes — tell us what you'd like in a hosted personal account.`})]})]}),(0,H.jsxs)(sX,{icon:Ne,title:`Coaching & gyms`,text:`For gyms and coaches — member accounts, coach views, and your brand on the surface.`,children:[(0,H.jsxs)(`ul`,{className:`space-y-1.5`,children:[(0,H.jsx)(aX,{children:`Member accounts with coach views of athlete data.`}),(0,H.jsx)(aX,{children:`Coaches portal — programming dashboards and leaderboards.`}),(0,H.jsx)(aX,{children:`Athlete portal — private journals that roll up to their coach.`}),(0,H.jsx)(aX,{children:`Gym website hosting, competition timers, and whiteboard displays.`}),(0,H.jsx)(aX,{children:`Website branding — your gym's brand on pages and feeds.`})]}),(0,H.jsxs)(`div`,{className:`mt-auto pt-3`,children:[(0,H.jsx)(iX,{href:nX,children:`Fill out interest survey`}),(0,H.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:`Takes two minutes — help shape our coaching and gym features.`})]})]})]})})]})]})}var lX=({doc:e,onDocChange:t,onBlocksChange:n,onRun:r,theme:i,withRingTargets:a=!1})=>{let o=UY(`editor.wodBlock`),s=UY(`editor.runButton`),c=(0,V.useRef)(null),l=(0,V.useRef)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(null),m=(0,V.useCallback)(()=>{if(!a)return null;let e=c.current;if(!e)return null;let t=null,n=e.querySelector(`.cm-wod-fence-open`),r=e.querySelector(`.cm-wod-fence-close`);if(n&&r){let i=e.getBoundingClientRect(),a=n.getBoundingClientRect(),o=r.getBoundingClientRect();if(a.top>=i.top-2&&o.bottom<=i.bottom+2){let n=e.offsetWidth?i.width/e.offsetWidth:1;t={top:(a.top-i.top)/n,left:(Math.min(a.left,o.left)-i.left)/n,width:(Math.max(a.right,o.right)-Math.min(a.left,o.left))/n,height:(o.bottom-a.top)/n}}}d(t);let i=null,o=e.querySelector(`[data-testid="${sB.EDITOR_START_WORKOUT}"]`);if(o){let t=e.getBoundingClientRect(),n=o.getBoundingClientRect();if(n.width>0&&n.height>0&&n.top>=t.top-2&&n.bottom<=t.bottom+2&&n.left>=t.left-2&&n.right<=t.right+2){let r=e.offsetWidth?t.width/e.offsetWidth:1;i={top:(n.top-t.top)/r,left:(n.left-t.left)/r,width:n.width/r,height:n.height/r}}}return p(i),{block:t,run:i}},[a]);(0,V.useLayoutEffect)(()=>{if(!a)return;let e=c.current;if(!e)return;m();let t=window.setTimeout(m,120),n=window.setTimeout(m,480),r=null;if(typeof ResizeObserver<`u`){r=new ResizeObserver(m),r.observe(e);let t=l.current?.contentDOM;t&&r.observe(t)}let i=new MutationObserver(e=>{e.some(e=>e.target instanceof Element&&e.target.closest(`.cm-note-editor`))&&m()});i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`]});let o=0,s=0,u=()=>{m(),performance.now()-s<3e3&&(o=requestAnimationFrame(u))},d=()=>{s=performance.now(),cancelAnimationFrame(o),o=requestAnimationFrame(u)};d(),document.fonts?.ready?.then(d).catch(()=>{});let f=l.current?.scrollDOM;return f?.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m),()=>{window.clearTimeout(t),window.clearTimeout(n),r?.disconnect(),i.disconnect(),f?.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),cancelAnimationFrame(o)}},[e,a,m]);let h=(0,V.useCallback)(()=>{r()},[r]),g=(0,V.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,H.jsx)(Ht,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:h},{id:`playground`,label:`Playground`,icon:(0,H.jsx)(k,{className:`h-3 w-3`}),onClick:e=>{vY(e)},splitIcon:(0,H.jsx)(nt,{className:`h-3 w-3`}),splitSuccessIcon:(0,H.jsx)(Zn,{className:`h-3 w-3 text-emerald-500`}),onSplitClick:e=>{bY(e)}}],[h]);return(0,H.jsx)(`div`,{className:`relative flex h-full flex-col bg-background text-left`,children:(0,H.jsxs)(`div`,{ref:c,className:`relative flex-1 min-h-0`,children:[(0,H.jsx)(vK,{noteId:`canvas:home`,value:e,onChange:t,onBlocksChange:n,onStartWorkout:h,commands:g,onViewCreated:e=>{l.current=e,a&&m()},theme:i,readonly:!1,showLineNumbers:!1,showFrontmatter:!1,enableOverlay:!1,enableInlineRuntime:!1,className:`h-full`}),a&&u&&(0,H.jsx)(`div`,{ref:o,"data-testid":`tour-wod-block-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:u.top,left:u.left,width:u.width,height:u.height}}),a&&f&&(0,H.jsx)(`div`,{ref:s,"data-testid":`tour-run-button-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:f.top,left:f.left,width:f.width,height:f.height}})]})})},uX=e=>{let t=Math.max(0,Math.round(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`};function dX({result:e,onDismiss:t,dismissLabel:n}){let[r,i]=(0,V.useState)(Hx),a=e.logs??[];return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden p-4`,"data-testid":`tour-session-result`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3 border-b border-border/60 pb-3`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{className:`font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground`,children:`Session recorded`}),(0,H.jsx)(`div`,{className:`text-2xl font-extrabold tabular-nums tracking-tight`,children:uX(e.duration)})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-muted-foreground`,children:[(0,H.jsx)(`span`,{className:e.completed?`rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 font-semibold text-emerald-600 dark:text-emerald-400`:`rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 font-semibold text-amber-600 dark:text-amber-400`,children:e.completed?`Completed`:`Stopped early`}),e.roundsCompleted!=null&&(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[`Rounds `,e.roundsCompleted,e.totalRounds==null?``:`/${e.totalRounds}`]}),e.repsCompleted!=null&&(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[`Reps `,e.repsCompleted]})]}),t&&(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-md border border-border px-3 py-1.5 text-[12px] font-medium transition-colors hover:bg-accent`,"data-testid":`tour-session-result-dismiss-top`,children:n})]}),(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto py-3`,children:[(0,H.jsx)(Kx,{presets:Ux,filter:r,onChange:i}),(0,H.jsx)(Jx,{outputs:a,filter:r,timeOrigin:e.startTime,onClearFilter:()=>i(``)})]}),t&&(0,H.jsx)(`div`,{className:`flex justify-end border-t border-border/60 pt-3`,children:(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-md border border-border px-3 py-1.5 text-[12px] font-medium transition-colors hover:bg-accent`,"data-testid":`tour-session-result-dismiss`,children:n??`Back`})})]})}function fX(e){let t=Number.isFinite(e.startTime)?e.startTime:0,n=[];for(let r of e.logs??[]){if(r.outputType!==`segment`||r.stackLevel!==1||r.line==null)continue;let e=r.timeSpan;if(!e||typeof e.started!=`number`||typeof e.ended!=`number`||e.ended<=e.started)continue;let i=r.metrics??[],a=e=>i.some(t=>t.type===e),o=i.find(e=>e.type===`effort`&&typeof e.value==`string`),s=a(`duration`)&&!a(`rep`)?`clock`:r.completionReason===`user-advance`?`next`:null;s&&n.push({start:e.started-t,end:e.ended-t,kind:s,label:o?.value??`Line ${r.line+1}`})}return n.length===0?null:{segments:n,totalMs:Number.isFinite(e.duration)&&e.duration>0?e.duration:Math.max(...n.map(e=>e.end)),clockMs:n.filter(e=>e.kind===`clock`).reduce((e,t)=>e+(t.end-t.start),0),nextMs:n.filter(e=>e.kind===`next`).reduce((e,t)=>e+(t.end-t.start),0),reactions:n.filter(e=>e.kind===`next`).map(e=>e.end-e.start)}}var pX=e=>{let t=Math.max(0,Math.round(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},mX=e=>`${(Math.round(e/100)/10).toFixed(1)}s`;function hX({result:e,onRun:t}){let n=(0,V.useMemo)(()=>e?fX(e):null,[e]);if(!e||!n)return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-4 p-8 text-center`,"data-testid":`tour-insights-empty`,children:[(0,H.jsx)(`p`,{className:`max-w-sm text-sm leading-relaxed text-muted-foreground`,children:`Run the workout and this window turns your run into data — rest vs. work, how fast you answered the clock, round by round.`}),(0,H.jsxs)(`button`,{type:`button`,onClick:t,"data-testid":`tour-insights-run`,className:`inline-flex min-h-11 items-center gap-2 rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow transition-colors hover:bg-primary/90`,children:[(0,H.jsx)(Ht,{className:`size-4`}),`Run to view the results`]})]});let{segments:r,totalMs:i,clockMs:a,nextMs:o,reactions:s}=n,c=s.length>0?s.reduce((e,t)=>e+t,0)/s.length:0,l=s.length>0?Math.max(...s):0,u=o>0?a/o:0;return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col gap-4 overflow-y-auto p-4`,"data-testid":`tour-insights`,children:[(0,H.jsxs)(`div`,{"data-testid":`tour-insights-timeline`,children:[(0,H.jsx)(`div`,{className:`flex h-3 w-full overflow-hidden rounded-full border border-border/60 bg-muted/40`,children:r.map((e,t)=>(0,H.jsx)(`div`,{title:`${e.label} — ${e.kind===`clock`?`countdown`:`to Next`} ${pX(e.end-e.start)}`,className:`h-full`,style:{flexGrow:e.end-e.start,flexBasis:0,backgroundColor:e.kind===`clock`?`hsl(var(--metric-rest))`:`hsl(var(--metric-time))`,marginLeft:+(t>0)}},t))}),(0,H.jsxs)(`div`,{className:`mt-1.5 flex items-center gap-4 font-mono text-[10px] uppercase tracking-wider text-muted-foreground`,children:[(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-rest))`}}),`Countdown`]}),(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-time))`}}),`To Next click`]}),(0,H.jsxs)(`span`,{className:`ml-auto`,children:[pX(i),` total`]})]})]}),(0,H.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,H.jsxs)(`div`,{"data-testid":`tour-insights-ratio`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,H.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Rest / Test Ratio`}),(0,H.jsxs)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:[`1 : `,u>0?(o/Math.max(a,1)).toFixed(1):`∞`]}),(0,H.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[pX(a),` on countdown timers · `,pX(o),` to click Next`]})]}),(0,H.jsxs)(`div`,{"data-testid":`tour-insights-reaction`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,H.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Reaction Time`}),(0,H.jsx)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:s.length>0?mX(c):`—`}),(0,H.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[s.length,` click`,s.length===1?``:`s`,s.length>1?` · slowest ${mX(l)}`:``]})]})]})]})}var gX=864e5;function _X(e){let t=new Date(e);return Math.round(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())/gX)}function vX(e,t){let n=[...e.keys()].filter(e=>e<=t);if(n.length===0)return[];let r=Math.min(...n),i=t=>e.get(t)??0,a=[];for(let e=r;e<=t;e++){let t=0,n=0;for(let r=0;r<28;r++){let a=i(e-r);n+=a,r<7&&(t+=a)}let r=t/7,o=n/28,s=0;for(let t=0;t<7;t++){let n=i(e-t)-r;s+=n*n}let c=Math.sqrt(s/7),l={day:e};o>0&&(l.acwr=r/o),c>0&&(l.monotony=r/c,l.strain=l.monotony*t),(l.acwr!==void 0||l.monotony!==void 0)&&a.push(l)}return a}var yX=864e5;function bX(e){return Math.round(e*10)/10}function xX(e,t,n=9){let r=new Date(e-t*yX);return r.setHours(n,0,0,0),r.getTime()}function SX(e,t,n,r,i,a={}){let o={canonicalKey:i};a.effortSlug&&(o.effortSlug=a.effortSlug),a.discipline&&(o.effortDiscipline=a.discipline),a.intensityTier&&(o.effortIntensityTier=a.intensityTier),e.push({id:e.length,outputType:`analytics`,timeSpan:{started:0},metrics:[{type:G.Label,value:t,origin:`analyzed`},{type:G.Metric,value:n,unit:r,origin:`analyzed`,metadata:o}],sourceBlockKey:``,stackLevel:0})}var CX=new Set([`tis`,`calc.acwr`,`calc.adherence`,`calc.ef`,`calc.pct1rm`]);function wX(e,t){return cg(e,{noteId:t.noteId,resultId:t.resultId,blockId:`example-block`,blockVersion:1,blockContentId:t.blockContentId,origin:`journal`,workoutTimestamp:t.timestamp}).map(e=>{let t=e.metrics[0];if(!t||!(`metadata`in t))return e;let n=t.metadata?.canonicalKey;return typeof n!=`string`||!CX.has(n)||typeof t.value!=`number`?e:{...e,reducerStats:{observedCount:1,sum:t.value,min:t.value,max:t.value}}})}function TX(e=Date.now()){let t=[],n=new Map,r=[],i=[],a=(e,t)=>{let r=_X(e);n.set(r,(n.get(r)??0)+t)};for(let n=0;n<16;n++){let o=(15-n)*7+1,s=xX(e,o);{let e=[{slug:`back-squat`,top:100+4*n,reps:5,tis:12.5},{slug:`bench-press`,top:80+2.5*n,reps:5,tis:10},{slug:`deadlift`,top:140+4*n,reps:3,tis:8.4}],r=[],i=0,o=0;for(let t of e){let e=t.reps*t.top;i+=e,o+=t.tis;let n={effortSlug:t.slug,discipline:`strength`,intensityTier:`high`};SX(r,`Total reps`,t.reps,`reps`,`totalReps`,n),SX(r,`Training intensity score`,t.tis,`pts`,`tis`,n),SX(r,`Total volume`,e,`kg`,`totalVolume`,n),SX(r,`Estimated 1RM`,bX(t.top*(1+t.reps/30)),`kg`,`calc.e1rm`,n),SX(r,`%1RM intensity`,bX(100/(1+t.reps/30)),`%`,`calc.pct1rm`,n)}let c=bX(i/100+13+o/10);SX(r,`Session load`,c,`AU`,`sessionLoad`,{discipline:`strength`,intensityTier:`high`}),t.push(...wX(r,{noteId:`example-strength-w${n}`,resultId:`example-strength-w${n}-r`,blockContentId:`example-content-strength`,timestamp:s})),a(s,c)}let c=xX(e,o+2);{let e=[],r;if(n%3==0){r=`high`;for(let[t,n,i,a]of[[`thruster`,45,2.2,42.5],[`pull-up`,45,1.6,0]]){let o={effortSlug:t,discipline:a?`strength`:`gymnastics`,intensityTier:r};SX(e,`Total reps`,n,`reps`,`totalReps`,o),SX(e,`Training intensity score`,bX(n*i),`pts`,`tis`,o),a&&SX(e,`Total volume`,n*a,`kg`,`totalVolume`,o)}}else if(n%3==1){r=`moderate`;let t=16+n%5;for(let[n,i,a]of[[`pull-up`,5,1.5],[`push-up`,10,1.2],[`air-squat`,15,1.1]]){let o=t*i,s={effortSlug:n,discipline:`gymnastics`,intensityTier:r};SX(e,`Total reps`,o,`reps`,`totalReps`,s),SX(e,`Training intensity score`,bX(o*a),`pts`,`tis`,s)}}else{r=`moderate`;for(let[t,n,i]of[[`double-under`,150,.5],[`sit-up`,150,1.3]]){let a={effortSlug:t,discipline:`gymnastics`,intensityTier:r};SX(e,`Total reps`,n,`reps`,`totalReps`,a),SX(e,`Training intensity score`,bX(n*i),`pts`,`tis`,a)}}let i=bX(30.6);SX(e,`Session load`,i,`AU`,`sessionLoad`,{intensityTier:r}),t.push(...wX(e,{noteId:`example-conditioning-w${n}`,resultId:`example-conditioning-w${n}-r`,blockContentId:`example-content-conditioning`,timestamp:c})),a(c,i)}let l=xX(e,o+4,8);if(n%4==1)r.push(_X(l));else{let e=6e3+100*n,r=bX(e/2.8),o=[],s={effortSlug:`running`,discipline:`running`,intensityTier:`low`};SX(o,`Total distance`,e,`m`,`totalDistance`,s),SX(o,`Elapsed time`,r,`s`,`elapsed`,s),SX(o,`Training intensity score`,r,`pts`,`tis`,s);let c=bX(r/10);SX(o,`Session load`,c,`AU`,`sessionLoad`,{intensityTier:`low`}),t.push(...wX(o,{noteId:`example-run-w${n}`,resultId:`example-run-w${n}-r`,blockContentId:`example-content-run`,timestamp:l})),a(l,c),i.push({day:_X(l),pace:e/r})}let u=xX(e,o+6,10);{let e=4e3+50*n,r=bX(e/2),i=[],o={effortSlug:`rowing`,discipline:`rowing`,intensityTier:`moderate`};SX(i,`Total distance`,e,`m`,`totalDistance`,o),SX(i,`Elapsed time`,r,`s`,`elapsed`,o),SX(i,`Training intensity score`,r,`pts`,`tis`,o);let s=bX(r/10);SX(i,`Session load`,s,`AU`,`sessionLoad`,{intensityTier:`moderate`}),t.push(...wX(i,{noteId:`example-row-w${n}`,resultId:`example-row-w${n}-r`,blockContentId:`example-content-row`,timestamp:u})),a(u,s)}}let o=Math.max(...n.keys()),s=(e,t=10)=>{let n=new Date(e*yX);return n.setHours(t,0,0,0),n.getTime()},c=(e,n,r)=>{let i=[];for(let[e,t,n]of r)SX(i,e,t,n,e);t.push(...wX(i,{noteId:`example-calc`,resultId:e,blockContentId:`example-content-calc`,timestamp:n}))};for(let e of vX(n,o))e.acwr!==void 0&&c(`example-calc-d${e.day}`,s(e.day),[[`calc.acwr`,bX(e.acwr),`ratio`]]);let l=0,u=0,d=Math.min(...n.keys());for(let e=d;e<=o;e++){let t=n.get(e)??0;l+=(t-l)/42,u+=(t-u)/7,n.has(e)&&c(`example-calc-pmc-d${e}`,s(e),[[`calc.ctl`,bX(l),`AU`],[`calc.atl`,bX(u),`AU`],[`calc.tsb`,bX(l-u),`AU`]])}let f=new Set([...n.keys()]);for(let e of r)f.add(e);for(let e of f){let t=+!!n.has(e);c(`example-calc-adh-d${e}`,s(e,7),[[`calc.adherence`,t,`ratio`]])}for(let e of i)c(`example-calc-ef-d${e.day}`,s(e.day,8),[[`calc.ef`,bX(e.pace/141*1e5),`pts`]]);return t}function EX(e=Date.now()){return new Vg(O_(TX(e)))}var DX=null;function OX(){return DX??=EX()}var kX=[4,8,16],AX={parse(e){let t=Number.parseInt(e,10);return kX.includes(t)?t:null},serialize(e){return String(e)},withDefault(e){return{...this,defaultValue:e}}};function jX(){return Gt(`weeks`,AX.withDefault(16))}function MX(e){let t=e.trim().split(/\s+/).filter(e=>e!==``);if(t.length===0)return;let n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)continue;let r=e.slice(0,t),i=e.slice(t+1);i.startsWith(`"`)&&i.endsWith(`"`)&&i.length>=2&&(i=i.slice(1,-1)),n[r]=i}return Object.keys(n).length===0?void 0:n}var NX=[{label:`Auto`,spanCols:void 0,spanFull:!1},{label:`1 col`,spanCols:1,spanFull:!1},{label:`2 cols`,spanCols:2,spanFull:!1},{label:`4 cols`,spanCols:4,spanFull:!1},{label:`Full row`,spanCols:void 0,spanFull:!0}],PX=300;function FX({open:e,...t}){return e?(0,H.jsx)(IX,{...t}):null}function IX({onClose:e,mode:t,initialWql:n,initial:r,subsetQuery:i,destination:a,executor:o,rangeStart:s,rangeEnd:c,preferredUnit:l,tokenValues:u,onApply:d,footerExtra:f,applyLabel:p=t===`edit`?`Apply changes`:`Add widget`}){let m=t===`inspect`,[h,g]=(0,V.useState)(n),[_,v]=(0,V.useState)(r?.title??``),[y,b]=(0,V.useState)(r?.question??``),[x,S]=(0,V.useState)(r?.type||`table`),[C,w]=(0,V.useState)({spanCols:r?.spanCols,spanFull:r?.spanFull}),[T,E]=(0,V.useState)(Object.entries(r?.attributes??{}).map(([e,t])=>`${e}=${t}`).join(` `)),[D,O]=(0,V.useState)(!1),[k,A]=(0,V.useState)(()=>!Y(n).error),[j,M]=(0,V.useState)(null),N=(0,V.useMemo)(()=>Y(h.trim()),[h]),P=x===``?`table`:x,F=!N.error&&h.trim()!==``&&(tm(N)?P===`table`||P===`list`:P!==`list`),[I,ee]=(0,V.useState)({status:`idle`}),te=(0,V.useRef)(0);(0,V.useEffect)(()=>{if(!F||!o){ee(e=>e.status===`ok`?e:{status:`idle`});return}let e=t_(h.trim(),u??{});if(e.missing.length>0){ee({status:`blocked`,message:Kg(e.missing)});return}let t=++te.current;ee({status:`loading`});let n=setTimeout(()=>{o.runQuery(e.query,{rangeStart:s,rangeEnd:c,preferredUnit:l}).then(e=>{te.current===t&&ee({status:`ok`,result:e})}).catch(e=>{te.current===t&&ee({status:`error`,message:e instanceof Error?e.message:String(e)})})},PX);return()=>clearTimeout(n)},[h,F,o,s,c,l,u]);let ne=!F&&I.status===`ok`,re=F&&k,ie=async()=>{if(!(!re||!d||D)&&!(Y(h.trim()).error||h.trim()===``)){O(!0),M(null);try{await d({title:_.trim()||void 0,question:y.trim()||void 0,type:x===`table`?``:x,spanCols:C.spanFull?void 0:C.spanCols,spanFull:C.spanFull||void 0,wql:h.trim(),attributes:MX(T)}),e()}catch(e){M(e instanceof Error?e.message:String(e))}finally{O(!1)}}};return(0,H.jsx)(lS,{open:!0,onClose:e,presentation:`sheet`,title:t===`inspect`?`Inspect widget`:t===`edit`?`Edit widget`:`Add widget`,description:m?`Read-only — clone the dashboard to edit this widget.`:`Dataset, calculation, visualization, preview — then apply.`,footer:m&&!f?void 0:(0,H.jsxs)(H.Fragment,{children:[f,(0,H.jsx)(`div`,{className:`flex-1`}),!m&&(0,H.jsxs)(H.Fragment,{children:[(0,H.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,H.jsx)(`button`,{type:`button`,"data-testid":`widget-composer-apply`,disabled:!re||D,title:N.error?N.error:void 0,onClick:()=>void ie(),className:`min-h-12 px-3 py-1.5 text-xs font-medium text-primary-foreground bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg shadow transition-colors`,children:D?`Applying…`:p})]})]}),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[i!==void 0&&(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Dataset — the subset`}),i?(0,H.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-subset`,children:i}):(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`widget-composer-subset`,children:`No subset — the calculation runs over the whole store.`})]}),a,(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Calculation`}),m?(0,H.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-query`,children:h}):(0,H.jsx)(EC,{query:h,onQueryChange:g,onValidationChange:e=>A(e.valid),showDiagnostics:!0,...o?{execute:e=>o.runQuery(e.raw,{rangeStart:s,rangeEnd:c,preferredUnit:l})}:{}}),!m&&h.trim()!==``&&(0,H.jsx)(`code`,{className:`mt-1.5 block rounded-md border border-primary/30 bg-primary/[0.04] px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-wql`,children:h.trim()}),!m&&(0,H.jsxs)(`label`,{className:`mt-3 flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Visualization`}),(0,H.jsx)(`select`,{value:x,onChange:e=>S(e.target.value),"data-testid":`widget-composer-type`,className:`min-h-12 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary sm:min-h-0`,children:Hg.map(e=>(0,H.jsx)(`option`,{value:e,children:e},e))})]})]}),!m&&(0,H.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Title`}),(0,H.jsx)(`input`,{type:`text`,value:_,onChange:e=>v(e.target.value),placeholder:`Weekly volume`,"data-testid":`widget-composer-title`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,H.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Coaching question `,(0,H.jsx)(`span`,{className:`normal-case font-normal`,children:`(optional)`})]}),(0,H.jsx)(`input`,{type:`text`,value:y,onChange:e=>b(e.target.value),placeholder:`How much work per week?`,"data-testid":`widget-composer-question`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,H.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Size`}),(0,H.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1 self-start`,children:NX.map(e=>{let t=e.spanFull?C.spanFull===!0:e.spanCols==null?!C.spanFull&&C.spanCols==null:!C.spanFull&&C.spanCols===e.spanCols;return(0,H.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:()=>w(e.spanFull?{spanFull:!0}:{spanCols:e.spanCols}),className:`text-xs px-2.5 py-1 rounded-md transition-colors ${t?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.label},e.label)})})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1 sm:col-span-2`,children:[(0,H.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Parameters `,(0,H.jsx)(`span`,{className:`normal-case font-normal`,children:`(goal targets, space-separated)`})]}),(0,H.jsx)(`input`,{type:`text`,value:T,onChange:e=>E(e.target.value),placeholder:`300 200`,"data-testid":`widget-composer-params`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-mono text-foreground focus:outline-none focus:border-primary`})]})]}),m&&(0,H.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs text-muted-foreground`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Title`}),(0,H.jsx)(`div`,{className:`text-foreground`,children:r?.title||`—`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Question`}),(0,H.jsx)(`div`,{className:`text-foreground`,children:r?.question||`—`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Type`}),(0,H.jsx)(`div`,{className:`font-mono text-foreground`,children:x||`table`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Size`}),(0,H.jsx)(`div`,{className:`font-mono text-foreground`,children:r?.spanFull?`full row`:r?.spanCols?`${r.spanCols} cols`:`default`})]})]}),(0,H.jsxs)(`section`,{children:[(0,H.jsxs)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5 flex items-center gap-2`,children:[`Preview`,ne&&(0,H.jsx)(`span`,{"data-testid":`widget-preview-stale`,className:`font-medium normal-case tracking-normal text-amber-600`,children:`stale — showing the last valid query`})]}),(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-background/50 p-3 h-56 overflow-hidden`,children:[I.status===`idle`&&(F?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Preview runs as you compose…`}):(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:N.error?N.error:tm(N)?`find: queries return things — use a table or list widget instead`:`Compose a calculation to preview.`})),I.status===`loading`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Running preview…`}),I.status===`blocked`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`error`&&(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`ok`&&(0,H.jsx)(ox,{type:x,result:I.result,label:_.trim()||void 0,unit:l,attributes:MX(T)})]})]}),j&&(0,H.jsx)(`p`,{role:`alert`,"data-testid":`widget-composer-error`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive font-mono`,children:j})]})})}function LX({boardSlug:e}){let t=OX(),n=sD(),r=(0,V.useMemo)(()=>n?Pj(n):[],[n]),i=(0,V.useMemo)(()=>r.find(t=>t.slug===e)??r[0],[r,e]),a=(0,V.useMemo)(()=>{if(!i?.rawContent)return null;try{let{meta:e,sections:t}=u_(i.rawContent);return i_(t,e)}catch{return null}},[i]),[o,s]=jX(),[c,l]=(0,V.useMemo)(()=>{let e=Date.now();return[e-o*7*864e5,e]},[o]),[u,d]=(0,V.useState)(null);return(0,H.jsxs)(`div`,{className:`flex h-full w-full flex-col`,"data-testid":`tour-session-dashboard`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 px-5 pt-4`,children:[(0,H.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`truncate text-[11px] font-semibold uppercase tracking-wide text-primary`,children:i?.title??e}),(0,H.jsx)(`span`,{"data-testid":`tour-session-dashboard-source`,className:`flex-none rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground`,children:`Example data`})]}),(0,H.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,H.jsx)(Sx,{weeks:o,onWeeksChange:s})})]}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto px-5 pb-5 pt-3 [&_[data-testid=dashboard-view]>div.grid]:grid-cols-1 [&_[data-testid=dashboard-view]>div.grid]:sm:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid]:lg:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid>*]:col-span-1`,children:a?(0,H.jsx)(xx,{document:a,executor:t,onInspectWidget:d,rangeStart:c,rangeEnd:l}):(0,H.jsx)(`p`,{className:`pt-8 text-center text-sm text-muted-foreground`,children:`Loading board…`})}),(0,H.jsx)(FX,{open:u!==null,onClose:()=>d(null),mode:`inspect`,initialWql:u?.body??`sum:totalVolume{}`,initial:u?{title:u.title,question:u.question,type:u.type,spanCols:u.spanCols,spanFull:u.spanFull,attributes:u.attributes}:void 0,executor:t,rangeStart:c,rangeEnd:l,tokenValues:a?Qg(a.tokens):void 0,onApply:void 0})]})}function RX({session:e,onRun:t}){return(0,H.jsxs)(`section`,{id:`tour-section-insights`,"data-testid":`tour-section-insights`,className:`flex flex-col gap-4 border-b border-border/60 pb-12`,children:[(0,H.jsx)(eX,{index:`01`,before:`Your Session, `,accentText:`Analyzed`,after:``,accent:qY.analytics,blurb:`The run you just did is already data — time on countdown timers against time to the next click, and how fast you answered the clock. Nothing to fill in; it comes straight from the run.`}),(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-[820px] px-5 2xl:max-w-[920px]`,children:(0,H.jsx)(PH,{title:`Session Insights`,className:`h-[460px]`,children:(0,H.jsx)(hX,{result:e,onRun:t})})})]})}var zX=[`road-to-560-total`,`polarized-base-marathon`];function BX(){return(0,H.jsxs)(`section`,{id:`tour-section-boards`,"data-testid":`tour-section-boards`,className:`flex flex-col gap-4 border-b border-border/60 pb-12`,children:[(0,H.jsx)(eX,{index:`02`,before:`One Run Becomes `,accentText:`Many`,after:``,accent:qY.analytics,blurb:`The same recorded facts roll up across workouts — tonnage toward a total, easy vs. hard work over weeks. These boards answer over example data; yours updates as you log.`}),(0,H.jsx)(`div`,{className:`grid gap-4 px-5 lg:grid-cols-2 2xl:gap-6`,children:zX.map(e=>(0,H.jsx)(PH,{title:`Example Board`,className:`h-[520px]`,children:(0,H.jsx)(LX,{boardSlug:e})},e))})]})}function VX(e){let[t,n]=(0,V.useState)(!1),[r,i]=(0,V.useState)({});(0,V.useEffect)(()=>{i(SH()),n(!0);let e=e=>{e.key===`wodwiki.quests.v1`&&i(SH())};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 HX({chapters:e,className:t}){let{chapters:n}=VX(e),r=n.find(e=>e.chapter.id===`home-tour`),i=r?.isComplete??!1,a=r?.completedCount??0,o=r?.totalCount??5;return(0,H.jsx)(`section`,{"data-testid":`celebration-bridge`,className:U(`py-12 px-4 sm:px-6 xl:py-20 2xl:py-24 border-b border-border/60 text-center`,t),children:(0,H.jsxs)(`div`,{className:`mx-auto max-w-2xl xl:max-w-3xl 2xl:max-w-4xl flex flex-col items-center gap-4 xl:gap-6`,children:[(0,H.jsx)(`div`,{"data-testid":`celebration-badge`,className:U(`inline-flex items-center gap-2 rounded-full px-3.5 py-1.5 font-mono text-[11px] font-bold transition-colors`,i?`border border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400`:`border border-border bg-muted/30 text-muted-foreground`),children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Zn,{className:`size-3.5 stroke-[2.5]`}),(0,H.jsx)(`span`,{children:`Take the Tour — complete ✓`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`size-2 rounded-full bg-primary`}),(0,H.jsxs)(`span`,{children:[`Take the Tour — `,a,`/`,o]})]})}),(0,H.jsx)(`h2`,{className:`text-2xl sm:text-3xl xl:text-4xl 2xl:text-5xl font-black tracking-tight text-foreground`,children:`You've seen how it works. Now master the syntax.`}),(0,H.jsxs)(`p`,{className:`text-[14px] sm:text-[15px] xl:text-base 2xl:text-lg leading-relaxed text-muted-foreground max-w-xl xl:max-w-2xl 2xl:max-w-3xl`,children:[`From your first `,(0,H.jsx)(`code`,{className:`font-mono text-[12px] bg-muted px-1.5 py-0.5 rounded text-foreground`,children:`wod`}),` block to a full training session: time-capped protocols like AMRAP and EMOM, repeating rounds and dash-format rep schemes (`,(0,H.jsx)(`code`,{className:`font-mono text-[12px] bg-muted px-1 py-0.5 rounded text-foreground`,children:`21-15-9`}),`), inline metrics for effort and heart rate, dialect fences for workout, log, plan, and climb notes — and complex workouts that chain it all into one session. Six chapters on the syntax, each with a runnable example and quests to earn. Keep scrolling to start.`]})]})})}var UX=`w-[290px] sm:w-[320px] md:w-[340px] shrink-0 snap-start flex flex-col justify-between rounded-xl border border-border bg-card p-5 text-left transition-colors hover:border-primary/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`;function WX(e){let t=e.icon;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,H.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),(0,H.jsx)(`h3`,{className:`mt-4 text-base font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.description})]}),e.note?(0,H.jsx)(`span`,{className:`mt-4 text-xs font-medium text-muted-foreground`,children:e.note}):(0,H.jsxs)(`span`,{className:`mt-4 inline-flex items-center gap-1.5 text-sm font-medium text-foreground`,children:[(0,H.jsx)(`span`,{children:e.action}),(0,H.jsx)(h,{className:`size-4 transition-transform group-hover:translate-x-0.5`,"aria-hidden":!0})]})]})}function GX(e){switch(e.phase){case`checking`:return`Checking source…`;case`fetching`:return`Downloading ${e.chunkId??`package`}…`;case`applying`:return`Importing ${e.chunkId??`package`}…`;case`committed`:return`Committed ${e.chunkId??`package`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??`Done`}}function KX(e){let{pkg:t,anyBusy:n,onBusyChange:r}=e,[i,a]=(0,V.useState)(()=>MO(t.id)),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null);(0,V.useEffect)(()=>(a(MO(t.id)),PO(()=>a(MO(t.id)))),[t.id]);let f=async()=>{s(!0),r(!0),d(null),l(`Checking source…`);try{let e=await Nk(t.id,{onProgress:e=>l(GX(e))});if(e===`imported`||e===`current`){let n=NO(t.id,!0);a(!0),l(n?e===`imported`?`Imported — package added to your library.`:`Already up to date.`:`Subscribed for this session only — browser storage is unavailable.`)}else l(null),d(e===`server-stale`?`Published version is older than stored copy.`:e===`busy`?`Another tab is syncing. Try again shortly.`:`Sync failed. Check connection and try again.`)}catch(e){l(null),d(e instanceof Error?e.message:String(e))}finally{s(!1),r(!1)}},p=async()=>{s(!0),r(!0),d(null),l(`Removing package…`);try{await Ik(t.id),a(!1),l(`Removed from library.`)}catch(e){d(e instanceof Error?e.message:`Failed to delete package`)}finally{s(!1),r(!1)}},m=()=>{i?p():f()},h=o||n;return(0,H.jsxs)(`article`,{className:UX,"data-testid":`demo-feed-${t.id}`,"aria-label":`${t.label} package`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`rounded-full border border-border bg-muted/60 px-2 py-0.5 font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground`,children:t.sourceLabel}),(0,H.jsx)(`span`,{className:`rounded-full border border-border/80 bg-accent/40 px-2 py-0.5 font-mono text-[10px] text-muted-foreground`,children:t.category}),t.category===`feeds`&&(0,H.jsx)(`span`,{className:`rounded-full border border-border px-2 py-0.5 font-mono text-[10px] text-muted-foreground`,children:`Demo`})]}),(0,H.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":i,"aria-label":`Toggle ${t.label} in library`,onClick:m,disabled:h,"data-testid":`demo-feed-toggle-${t.id}`,title:i?`Remove from library`:`Add to library`,className:`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:opacity-50 ${i?`bg-emerald-600`:`bg-muted-foreground/30`}`,children:(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-3.5 transform rounded-full bg-background shadow transition-transform ${i?`translate-x-4.5`:`translate-x-0.5`}`})})]}),(0,H.jsx)(`h3`,{className:`mt-3.5 text-base font-semibold text-foreground`,children:t.label}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground line-clamp-3`,children:t.description})]}),(0,H.jsxs)(`div`,{className:`mt-4 pt-2 border-t border-border/60`,children:[(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:i?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-medium text-emerald-600`,children:[(0,H.jsx)(yn,{className:`size-3.5`,"aria-hidden":!0}),`In library`]}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Not in library`})}),c&&(0,H.jsxs)(`p`,{role:`status`,"aria-live":`polite`,className:`mt-1.5 flex items-center gap-1.5 text-xs text-muted-foreground`,"data-testid":`demo-feed-progress-${t.id}`,children:[o&&(0,H.jsx)(pn,{className:`size-3 animate-spin motion-reduce:animate-none`,"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`truncate`,children:c})]}),u&&(0,H.jsxs)(`p`,{role:`alert`,className:`mt-1.5 flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`demo-feed-error-${t.id}`,children:[(0,H.jsx)(Kn,{className:`mt-0.5 size-3 shrink-0`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:u})]}),(0,H.jsx)(`div`,{className:`mt-3 flex items-center gap-2`,children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{f()},disabled:h,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted disabled:opacity-50`,"data-testid":`demo-feed-sync-${t.id}`,children:[(0,H.jsx)(pn,{className:`size-3 ${o?`animate-spin motion-reduce:animate-none`:``}`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:o?`Syncing…`:`Sync now`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{p()},disabled:h,className:`inline-flex items-center gap-1 rounded-md border border-destructive/20 px-2 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40`,"data-testid":`demo-feed-unsubscribe-${t.id}`,title:`Remove package from library`,children:[(0,H.jsx)(j,{className:`size-3`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:`Delete`})]})]}):(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{f()},disabled:h,className:`inline-flex items-center gap-1.5 rounded-md bg-foreground px-2.5 py-1 text-xs font-medium text-background transition-colors hover:opacity-90 disabled:opacity-50`,"data-testid":`demo-feed-subscribe-${t.id}`,children:[(0,H.jsx)(pn,{className:`size-3 ${o?`animate-spin motion-reduce:animate-none`:``}`,"aria-hidden":!0}),(0,H.jsx)(`span`,{children:o?`Syncing…`:`Subscribe & sync`})]})})]})]})}function qX(){let e=Sn(),[t,n]=(0,V.useState)(``),[r,i]=(0,V.useState)(!1),a=(0,V.useRef)(null),o=(0,V.useMemo)(()=>yO(),[]),s=(0,V.useMemo)(()=>{let e=t.trim().toLowerCase();return e?o.filter(t=>t.label.toLowerCase().includes(e)||t.category.toLowerCase().includes(e)||t.sourceLabel.toLowerCase().includes(e)||t.description.toLowerCase().includes(e)):o},[o,t]),c=e=>{if(!a.current)return;let t=a.current.clientWidth*.75;a.current.scrollBy({left:e===`left`?-t:t,behavior:`smooth`})},l=(0,V.useCallback)(()=>{oH.record(sH.libraryOpened)},[]),[u,d]=(0,V.useState)(!0);(0,V.useEffect)(()=>{let e=!1,t=()=>{Lk().then(t=>{e||d(t.libraryImported)}).catch(()=>{})};t();let n=PO(t);return()=>{e=!0,n()}},[r]);let f=(0,V.useCallback)(async()=>{let t=Vj(),n=await Kj.create({journalDate:t,title:t,rawContent:``});oH.record(sH.noteCreated),e(qA(n.id))},[e]);return(0,H.jsxs)(`section`,{id:`tour-section-community-feeds`,"data-testid":`tour-jump-section`,className:`flex flex-col border-b border-border bg-muted/20 pb-8 xl:pb-12`,"aria-label":`Library and community feeds`,children:[(0,H.jsx)(eX,{index:`00`,before:`Library & `,accentText:`Community Feeds`,after:``,accent:``,blurb:`Subscribe to Markdown repositories and sync while you keep scrolling. Publishers run npx wod build to compile manifests and chunks, then deploy them through GitHub Pages. CrossFit Programming and Dan John 40-Day Program are demo feeds; other packages and workspace shortcuts are available here too.`}),(0,H.jsxs)(`div`,{className:`mx-auto w-full max-w-6xl px-4 sm:px-6`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[(0,H.jsxs)(`div`,{className:`relative w-full sm:w-64`,children:[(0,H.jsx)(Xn,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground`,"aria-hidden":!0}),(0,H.jsx)(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Filter packages…`,"data-testid":`package-search-input`,className:`w-full rounded-md border border-border bg-background py-1.5 pl-8 pr-7 text-xs text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`}),t&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(``),"aria-label":`Clear search`,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3.5`})})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(`left`),"aria-label":`Previous cards`,className:`flex size-7 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Tt,{className:`size-4`})}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(`right`),"aria-label":`Next cards`,className:`flex size-7 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(Vn,{className:`size-4`})})]})]}),(0,H.jsxs)(`div`,{ref:a,"data-testid":`jump-carousel-track`,className:`mt-6 flex w-full gap-4 overflow-x-auto pb-4 pt-1 snap-x snap-mandatory scroll-smooth`,style:{scrollbarWidth:`thin`},children:[u?(0,H.jsx)(Wn,{to:`/catalogs`,onClick:l,"data-testid":`jump-library`,className:`group ${UX}`,children:(0,H.jsx)(WX,{icon:an,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`})}):(0,H.jsx)(`div`,{"data-testid":`jump-library`,"aria-disabled":`true`,className:`${UX} cursor-not-allowed opacity-60`,children:(0,H.jsx)(WX,{icon:an,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`,note:`0 feeds synchronized`})}),(0,H.jsx)(`button`,{type:`button`,onClick:f,"data-testid":`jump-new-note`,className:`group ${UX}`,children:(0,H.jsx)(WX,{icon:Ut,title:`Start your own journal`,description:`Create today's note and log your first workout.`,action:`Create today's note`})}),s.map(e=>(0,H.jsx)(KX,{pkg:e,anyBusy:r,onBusyChange:i},e.id)),s.length===0&&t&&(0,H.jsxs)(`div`,{className:`flex w-64 shrink-0 flex-col items-center justify-center rounded-xl border border-dashed border-border p-6 text-center text-xs text-muted-foreground`,children:[(0,H.jsxs)(`p`,{children:[`No packages match “`,t,`”.`]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(``),className:`mt-2 font-medium text-foreground underline underline-offset-4`,children:`Clear filter`})]})]}),(0,H.jsx)(`p`,{className:`mt-2 font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:`— or keep scrolling ↓`})]})]})}var JX=`wods/examples/home/welcome-1.md`;function YX({wodFiles:e,theme:t,quests:n,chapters:r}){let i=jH(`(prefers-reduced-motion: reduce)`),a=cH()?.track;uH(`/`);let o=(0,V.useMemo)(()=>BL(JX,e),[e]),[s,c]=(0,V.useState)(()=>PY()),l=s?.content??o,u=s?s.by?.trim()||`anonymous`:void 0;(0,V.useEffect)(()=>{let e=e=>{let t=e.detail;t?.content&&(c(t),f(t.content))};return window.addEventListener(`wodwiki:home-shared`,e),()=>window.removeEventListener(`wodwiki:home-shared`,e)},[]);let[d,f]=(0,V.useState)(l),p=(0,V.useRef)(d);p.current=d;let m=(0,V.useRef)([]),h=(0,V.useRef)(!1),{run:g,start:_,finalize:v,end:y}=vH(),b=(0,V.useRef)(g);b.current=g;let x=(0,V.useRef)(!1),S=(0,V.useRef)(!1),C=(0,V.useRef)(null),[w,T]=(0,V.useState)(!1),E=(0,V.useRef)(!1),D=(0,V.useRef)(null),[O,k]=(0,V.useState)(null),[A,j]=(0,V.useState)(null),[M,N]=(0,V.useState)(null),P=M===`hero`,[F,I]=(0,V.useState)(!1),ee=(0,V.useRef)(!1),te=(0,V.useRef)(()=>{}),[ne,re]=(0,V.useState)(0),[ie,ae]=(0,V.useState)(!1),oe=(0,V.useCallback)(()=>{k(null),N(null),I(!1),le(null)},[]),[se,ce]=(0,V.useState)(!1),[L,le]=(0,V.useState)(null),ue=(0,V.useCallback)(async(e,t,n,r)=>{if(!t||ee.current)return!1;ee.current=!0,S.current=!1,x.current=!1,C.current=null,le(t),re(e=>e+1),ae(!0),k(null),j(null),N(r),I(!0);try{await _(e,t,{pageTitle:`Home`,sectionTitle:n})}catch(e){return console.error(`[HomeTour] failed to persist playground run note:`,e),I(!1),le(null),Z({title:`Could not start workout`,description:`The playground entry could not be saved.`,variant:`destructive`}),!1}finally{ee.current=!1}return!0},[_]),R=(0,V.useCallback)(async()=>{if(E.current=!1,T(!1),C.current)try{await v(C.current,!1),C.current=null}catch(e){console.error(`[HomeTour] retry save failed:`,e),Z({title:`Session still not saved`,description:`The run is kept — try again.`,variant:`destructive`});return}let e=D.current;if(D.current=null,e)switch(e.kind){case`apply-doc`:h.current=!1,f(e.doc),oe(),re(e=>e+1),ae(!1);break;case`restart`:await ue(e.doc,e.block,e.sectionTitle,e.location)}},[ue,oe,v]),de=(0,V.useCallback)(e=>{if(!D.current){if(!b.current||S.current||!x.current||C.current){D.current=e,R();return}D.current=e,E.current=!0,T(!0)}},[R]),fe=(0,V.useRef)(null),pe=(0,V.useRef)(null);RK(`hero`,pe);let me=(0,V.useRef)(!0),he=(0,V.useRef)(P);he.current=P;let ge=(0,V.useCallback)(()=>{he.current||de({kind:`apply-doc`,doc:l})},[l,de]);(0,V.useEffect)(()=>{let e=fe.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{let t=e.isIntersecting;t&&!me.current&&ge(),me.current=t});return t.observe(e),()=>t.disconnect()},[ge]);let _e=(0,V.useCallback)(()=>{FY(),c(null),de({kind:`apply-doc`,doc:o})},[o,de]);AH({pageRoute:`/`,quests:n,initialSource:l,currentSource:d}),kH({pageRoute:`/`,quests:n,completedResults:O}),te.current=zY(`/`,n),IY({pageRoute:`/`,quests:n,running:se}),(0,V.useEffect)(()=>{let e=document.getElementById(`tour-section-insights`);if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&te.current?.(`session-insights`)});return t.observe(e),()=>t.disconnect()},[]);let ve=(0,V.useCallback)(e=>{f(e),e!==l&&!h.current&&(h.current=!0,a?.(sH.demoEdited))},[l,a]),ye=(0,V.useCallback)(e=>{m.current=e},[]),be=(0,V.useCallback)((e,t,n,r,i)=>{if(n){if(a?.(sH.demoRun),r&&ce(!0),le(n),N(i),I(!0),ae(!0),re(e=>e+1),k(null),ee.current||D.current){D.current={kind:`restart`,doc:t,block:n,sectionTitle:e,location:i};return}if(b.current&&x.current&&!S.current){D.current={kind:`restart`,doc:t,block:n,sectionTitle:e,location:i},E.current=!0,T(!0);return}if(b.current&&!S.current){y().then(()=>ue(t,n,e,i));return}ue(t,n,e,i)}},[ue,y,a]),xe=(0,V.useCallback)(()=>{be(`Run`,p.current,m.current[0],!0,`hero`)},[be]),Se=(0,V.useCallback)(()=>{be(`Run`,p.current,m.current[0],!0,`cta`)},[be]),{setL3Items:Ce}=hA();(0,V.useEffect)(()=>(Ce([{id:`tour-hero`,label:`Welcome`,level:3,action:{type:`scroll`,sectionId:`tour-hero`}},{id:`insights`,label:`Your Session, Analyzed`,level:3,action:{type:`scroll`,sectionId:`tour-section-insights`},secondaryAction:{id:`run-start`,label:`Run the workout`,action:{type:`call`,handler:Se}}},{id:`boards`,label:`One Run Becomes Many`,level:3,action:{type:`scroll`,sectionId:`tour-section-boards`}},{id:`community-feeds`,label:`Library & Community Feeds`,level:3,action:{type:`scroll`,sectionId:`tour-section-community-feeds`}},{id:`offerings`,label:`You Own the Data`,level:3,action:{type:`scroll`,sectionId:`tour-section-offerings`}},{id:`hosted`,label:`Wod-Wiki Hosted`,level:3,action:{type:`scroll`,sectionId:`tour-section-hosted`}}]),()=>Ce([])),[Ce,Se]);let we=(0,V.useCallback)((e,t)=>{if(!(S.current&&!C.current))return k(t),(t.logs??[]).length===0?(S.current=!0,j(t),I(!1),R()):(S.current=!0,v(t,t.completed).then(()=>(C.current=null,j(t),I(!1),R())).catch(e=>{throw S.current=!1,x.current=!1,C.current=t,E.current=!1,T(!1),D.current=null,Z({title:`Session not saved`,description:`The run could not be recorded. Nothing was lost — your next action retries the save.`,variant:`destructive`}),e}))},[v,R]),Te=(0,V.useCallback)(()=>{I(!1)},[]),Ee=(0,V.useRef)(null),De=(0,V.useCallback)(e=>{Ee.current=e},[]),Oe=(0,V.useCallback)(()=>{x.current=!0;let e=Ee.current;ie&&e&&e.handle(new mf(void 0,e.nowProvider)),ae(!1)},[ie]),ke=(0,V.useRef)(!1),Ae=(0,V.useCallback)(()=>{if(ke.current){oe();return}let e=fe.current,t=document.querySelector(`[data-gate-id="hero-pane"]`);if(!e||!t){oe();return}let n=e.getBoundingClientRect().top+window.scrollY,r=t.getBoundingClientRect().top+window.scrollY,a=Math.max(0,r-n);if(typeof requestAnimationFrame!=`function`){oe();return}ke.current=!0,window.scrollTo({top:a,behavior:i?`auto`:`smooth`});let o=performance.now(),s=()=>{if(Math.abs(window.scrollY-a)<=2||performance.now()-o>1200){ke.current=!1,oe();return}requestAnimationFrame(s)};requestAnimationFrame(s)},[oe,i]),je=P&&O?`result`:`editor`,Me=(0,V.useRef)(`editor`);(0,V.useEffect)(()=>{let e=Me.current;if(Me.current=je,je===e)return;let t=()=>{let e=fe.current,t=document.querySelector(`[data-gate-id="hero-pane"]`);if(!e||!t)return null;let n=e.getBoundingClientRect().top+window.scrollY,r=t.getBoundingClientRect().top+window.scrollY;return Math.max(0,r-n)};if(je===`result`){let e=t();if(e==null)return;window.scrollTo({top:e,behavior:i?`auto`:`smooth`})}let n=[150,450].map(e=>setTimeout(()=>{let e=t();e!=null&&Math.abs(window.scrollY-e)>2&&window.scrollTo({top:e,behavior:`auto`})},e));return()=>n.forEach(clearTimeout)},[je,i]);let Ne=g?.block??L,Pe=F&&Ne&&(0,H.jsx)(ZG,{block:Ne,autoStart:ie,externalStop:w,onRunStarted:Oe,onRuntimeReady:De,onClose:Te,onCompleteWorkout:we},ne),Fe=(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(cX,{}),(0,H.jsxs)(`p`,{className:`-mt-8 text-center font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:[`— or learn the language with examples`,` `,(0,H.jsx)(Wn,{to:`/syntax`,className:`text-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:`on the syntax page →`})]})]});return i?(0,H.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,H.jsxs)(`section`,{id:`tour-hero`,"data-testid":`tour-hero`,className:`grid h-[calc(100dvh-65px)] grid-rows-[2fr_3fr] gap-4 px-6 py-4 lg:h-[calc(100dvh-104px)]`,children:[(0,H.jsx)(`div`,{className:`flex min-h-0 items-center justify-center overflow-y-auto`,children:(0,H.jsx)(XY,{})}),(0,H.jsxs)(`div`,{className:`relative min-h-0 overflow-hidden rounded-xl border border-border`,children:[u&&(0,H.jsx)(`button`,{type:`button`,onClick:_e,"data-testid":`tour-hero-reset-shared`,className:`absolute right-3 top-3 z-10 rounded-md border border-border bg-background px-3 py-2 text-xs hover:bg-accent`,children:`Reset`}),je===`result`&&O?(0,H.jsx)(dX,{result:O,onDismiss:Ae,dismissLabel:`Edit again`}):(0,H.jsx)(lX,{doc:d,theme:t,onDocChange:ve,onBlocksChange:ye,onRun:xe})]})]}),(0,H.jsx)(RX,{session:A,onRun:Se}),(0,H.jsx)(BX,{}),(0,H.jsx)(HX,{chapters:r}),(0,H.jsx)(qX,{}),Fe,(0,H.jsx)(Gq,{}),(0,H.jsx)(QY,{}),Pe]}):(0,H.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,H.jsx)(`div`,{ref:fe,"aria-hidden":!0,className:`h-px`}),(0,H.jsxs)(`section`,{ref:pe,id:`tour-hero`,"data-testid":`tour-hero`,className:`relative flex min-h-[calc(100dvh-65px)] flex-col items-center gap-4 px-5 py-4 text-center lg:min-h-[calc(100dvh-104px)] lg:px-10 xl:gap-8 xl:py-8 2xl:gap-10 2xl:py-10 2xl:px-16`,children:[(0,H.jsx)(`div`,{className:`flex w-full shrink grow-[2] basis-0 items-center justify-center`,children:(0,H.jsx)(XY,{})}),(0,H.jsx)(zK,{gateId:`hero-pane`,segmentId:`hero`,className:U(`w-full max-w-[720px] grow-[3] basis-0 xl:max-w-[820px] 2xl:max-w-[920px]`,je===`result`&&`[&>div:first-child]:min-h-fit`),children:(0,H.jsxs)(PH,{title:je===`result`?JY.metrics:u?u.toLowerCase().startsWith(`shared by`)?u:`shared by: ${u}`:`welcome-1.md`,headerActions:u&&(0,H.jsx)(`button`,{type:`button`,onClick:_e,title:`Reset`,className:`rounded-md border border-border px-2 py-1 text-[10px] transition-colors hover:bg-accent`,"data-testid":`tour-hero-reset-shared`,children:`Reset`}),className:je===`result`?`h-full min-h-fit [&>div:last-child]:min-h-fit`:`h-full`,children:[je===`editor`&&(0,H.jsx)(lX,{doc:d,theme:t,onDocChange:ve,onBlocksChange:ye,onRun:xe}),je===`result`&&O&&(0,H.jsx)(dX,{result:O,onDismiss:Ae,dismissLabel:`Edit again`})]})})]}),(0,H.jsx)(RX,{session:A,onRun:Se}),(0,H.jsx)(BX,{}),(0,H.jsx)(HX,{chapters:r}),(0,H.jsx)(qX,{}),Fe,(0,H.jsx)(Gq,{}),(0,H.jsx)(QY,{}),Pe]})}function XX(e){return(0,H.jsx)(VY,{children:(0,H.jsx)(LK,{children:(0,H.jsx)(YX,{...e})})})}function ZX({wodFiles:e,theme:t}){let n=MP(`/`);return n?(0,H.jsx)(XX,{wodFiles:e,theme:t,quests:n.quests??[],chapters:n.chapters??[]}):(0,H.jsx)(`div`,{className:`flex items-center justify-center p-20 text-muted-foreground`,children:`Home canvas content not found (markdown/canvas/routes/home.md)`})}var QX=`idle`,$X=new Set,eZ=null,tZ=null;function nZ(){for(let e of $X)e()}function rZ(e){typeof document>`u`||(document.documentElement.dataset.seedState=e)}function iZ(e){typeof document>`u`||(e===null?delete document.documentElement.dataset.seedOutcome:document.documentElement.dataset.seedOutcome=e)}rZ(QX);function aZ(e){QX!==e&&(QX=e,rZ(e),nZ())}function oZ(){eZ&&=(clearTimeout(eZ),null),tZ&&=(tZ.close(),null)}function sZ(){oZ(),iZ(null),aZ(`preparing`)}function cZ(e){switch(iZ(e),e){case`busy`:if(QX!==`preparing`)return;typeof BroadcastChannel<`u`&&!tZ&&(tZ=new BroadcastChannel(z_),tZ.onmessage=e=>{e.data?.kind===`seed-imported`&&(oZ(),aZ(`ready`))}),eZ=setTimeout(()=>{jk().then(cZ)},pk);break;case`error`:oZ(),aZ(`error`);break;default:oZ(),aZ(`ready`)}}function lZ(){return QX===`idle`?`ready`:QX}function uZ(e){return $X.add(e),()=>$X.delete(e)}function dZ(){return(0,V.useSyncExternalStore)(uZ,lZ)}var fZ=null;function pZ(e={}){return fZ??=mZ(e),fZ}async function mZ(e){let t=e.sources??hk();await RO(t,e.storage).catch(e=>console.error(`[seedSync] subscription migration failed`,e));let n=e.storage??new SO,r;try{r=await n.getSeedMeta(V_(`core`))}catch{r=void 0}if(!r||r.seedVersion<=0){sZ(),cZ(await jk({...e,sources:t,onFirstPaint:()=>cZ(`imported`)})),t.some(e=>e.id!==`core`&&MO(e.id))&&await jk({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e));return}cZ(`current`),await jk({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e))}function hZ(){let[e,t]=(0,V.useState)(null);return(0,V.useEffect)(()=>{let e=!1,n=()=>{Lk().then(n=>{e||t(!n.libraryImported)}).catch(()=>{e||t(!0)})};n();let r=hb(()=>n()),i=Ck(()=>n()),a=null;if(typeof BroadcastChannel<`u`)try{a=new BroadcastChannel(z_),a.onmessage=()=>n()}catch{}return()=>{e=!0,r(),i(),a?.close()}},[]),e}var gZ=UO.ICONS,_Z=({open:e,onOpenChange:t,onCreate:n})=>{let[r,i]=(0,V.useState)(``),[a,o]=(0,V.useState)(``),[s,c]=(0,V.useState)(`📓`),[l,u]=(0,V.useState)(!1),d=async()=>{if(!(!r.trim()||l)){u(!0);try{if(!await n(r.trim(),a.trim(),s))return;i(``),o(``),c(`📓`),t(!1)}finally{u(!1)}}};return(0,H.jsx)(UB,{open:e,onOpenChange:t,children:(0,H.jsxs)(WB,{className:`bg-popover text-popover-foreground border border-border`,children:[(0,H.jsxs)(GB,{children:[(0,H.jsx)(KB,{className:`text-foreground`,children:`Create Notebook`}),(0,H.jsx)(qB,{children:`Organize your sessions into collections.`})]}),(0,H.jsxs)(`div`,{className:`space-y-4 mt-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{className:`text-sm font-medium text-foreground/80 mb-2 block`,children:`Icon`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:gZ.map(e=>(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(e),className:U(`w-9 h-9 rounded-md flex items-center justify-center text-lg transition-all`,`hover:bg-accent hover:scale-110`,s===e?`bg-primary/20 ring-2 ring-primary scale-110`:`bg-muted/50`),children:e},e))})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Name `,(0,H.jsx)(`span`,{className:`text-destructive`,children:`*`})]}),(0,H.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&r.trim()&&(e.preventDefault(),d())},placeholder:`e.g., Morning Routines`,autoFocus:!0,className:U(`w-full px-3 py-2 rounded-md text-sm`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Description `,(0,H.jsx)(`span`,{className:`text-muted-foreground text-xs`,children:`(optional)`})]}),(0,H.jsx)(`textarea`,{value:a,onChange:e=>o(e.target.value),placeholder:`A brief description of this notebook...`,rows:2,className:U(`w-full px-3 py-2 rounded-md text-sm resize-none`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,H.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>t(!1),children:`Cancel`}),(0,H.jsx)(W,{variant:`default`,size:`sm`,onClick:()=>void d(),disabled:!r.trim()||l,children:l?`Creating…`:`Create`})]})]})]})})};function vZ({value:e,max:t,label:n,className:r}){let i=Math.max(1,t),a=Math.min(Math.max(e,0),i),o=Math.round(a/i*100),s=(0,V.useRef)(a),[c,l]=(0,V.useState)(!1);return(0,V.useEffect)(()=>{if(a>s.current){l(!0);let e=setTimeout(()=>l(!1),200);return s.current=a,()=>clearTimeout(e)}s.current=a},[a]),(0,H.jsxs)(`div`,{className:U(`w-full`,r),children:[n?(0,H.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.14em] text-brand-deep dark:text-brand-light`,children:[(0,H.jsx)(`span`,{children:n}),(0,H.jsxs)(`span`,{className:`tabular-nums text-muted-foreground`,children:[a,`/`,i]})]}):null,(0,H.jsx)(`div`,{role:`progressbar`,"aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":i,"aria-label":n??`Progress`,className:`h-2 w-full overflow-hidden rounded-pill bg-brand/10`,children:(0,H.jsx)(`div`,{className:U(`h-full rounded-pill transition-[width] duration-500 ease-out`,c?`bg-brand-deep`:`bg-brand`),style:{width:`${o}%`}})})]})}function yZ(e,t,n){UR.getState().open({placeholder:`Craft the query…`,wql:{initialQuery:e,execute:t,onApply:n},sources:[Mz()]})}function bZ({query:e,onQueryChange:t,scopeOptions:n,execute:r,defaultQuery:i,compact:a=!1,className:o}){let s=(0,V.useCallback)(()=>yZ(e,r,t),[e,r,t]);return a?(0,H.jsx)(`div`,{"data-testid":`stream-query-bar-dock`,className:U(`flex min-h-12 w-full items-stretch overflow-hidden rounded-xl border border-border bg-muted/40 shadow-xs`,o),children:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`stream-query-bar`,onClick:s,className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 px-3 text-left transition-colors hover:bg-muted/70`,children:[(0,H.jsx)(Xn,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{"data-testid":`stream-query-summary`,className:`min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground`,children:e||i||`Filter or search…`}),(0,H.jsx)(wn,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`})]})}):(0,H.jsx)(`div`,{"data-testid":`stream-query-bar`,className:U(`flex min-w-0 flex-1 items-center gap-1 text-xs`,o),children:(0,H.jsx)(EC,{query:e,onQueryChange:t,compact:!0,showDiagnostics:!1,preferredChoices:n,placeholder:`Filter or search…`,className:`min-w-0 flex-1`})})}function xZ(e,t){let n=t??Y(e);return n.error?null:n.groupBy?.length?n.groupBy.map(e=>String(e).toLowerCase()):null}function SZ(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)||`default`}function CZ(e,t=`date`,n){let r=(Array.isArray(t)?t:[t]).map(e=>String(e).toLowerCase()).filter(Boolean);r.length===0&&r.push(`date`);let i=(e,t)=>{let r=wZ(e,t[0],n);return t.length===1?r:r.flatMap(e=>e.key===`shelf`?[e]:i(e.entries,t.slice(1)).map(t=>({...t,key:`${e.key}/${t.key}`,id:`${e.id}--${t.id}`,label:`${e.label} / ${t.label}`,isToday:e.isToday||t.isToday})))};return i(e,r)}function wZ(e,t,n){let r=t.toLowerCase(),i=_z();if(r===`date`||r===`day`){let t=new Map,r=[],a=[];for(let i of e){let e=i.date??(i.sourceCatalog===`playground`&&i.createdAt&&i.createdAt>9466848e5?new Date(i.createdAt).toISOString().slice(0,10):null);if(n?.shelfVisible&&(i.kind===`session`||e==null))r.push(i);else if(e){let n=t.get(e);n?n.push(i):t.set(e,[i])}else a.push(i)}let o=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)),s=[];n?.shelfVisible&&r.length>0&&s.push({id:`group-shelf`,key:`shelf`,label:`Catalog Sessions`,entries:r});for(let e of o)s.push({id:`date-group-${e}`,key:e,label:e===i?`Today`:vz(e),isToday:e===i,entries:t.get(e)??[]});return a.length>0&&s.push({id:`group-date-undated`,key:`undated`,label:`Undated`,entries:a}),s}if(r===`week`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let[e,i,a]=r.date.split(`-`).map(Number),o=new Date(Date.UTC(e,i-1,a)),s=o.getUTCDay(),c=o.getUTCDate()-s+(s===0?-6:1),l=new Date(Date.UTC(e,i-1,c)),u=l.toISOString().slice(0,10),d=`Week of ${l.toLocaleDateString(`en`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`})}`,f=t.get(u);f?f.entries.push(r):t.set(u,{label:d,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-week-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-week-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`month`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,7),[i,a]=e.split(`-`).map(Number),o=new Date(Date.UTC(i,a-1,1)).toLocaleDateString(`en`,{month:`long`,year:`numeric`,timeZone:`UTC`}),s=t.get(e);s?s.entries.push(r):t.set(e,{label:o,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-month-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-month-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`year`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,4),i=t.get(e);i?i.push(r):t.set(e,[r])}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-year-${e}`,key:e,label:e,entries:t.get(e)??[]}));return n.length>0&&r.push({id:`group-year-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`discipline`){let t=new Map;for(let n of e){let e=n.effort?.discipline||n.tags?.find(e=>[`strength`,`gymnastics`,`cardio`,`running`,`rowing`,`weightlifting`,`olympic-weightlifting`].includes(e.toLowerCase()))||`General`,r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=t.get(r);i?i.push(n):t.set(r,[n])}let n=[`Strength`,`Gymnastics`,`Cardio`,`Running`,`Rowing`,`Weightlifting`];return Array.from(t.keys()).sort((e,t)=>{let r=n.indexOf(e),i=n.indexOf(t);return r!==-1&&i!==-1?r-i:r===-1?i===-1?e.localeCompare(t):1:-1}).map(e=>({id:`group-discipline-${SZ(e)}`,key:e,label:e,entries:t.get(e)??[]}))}if(r===`origin`){let t=new Map;for(let n of e){let e=n.effort?.registrySource===`bundled`?`Bundled Standards`:`Custom Movements`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-origin-${SZ(e)}`,key:e,label:e,entries:t}))}if(r===`source`||r===`notebook`){let t=new Map;for(let n of e){let e=n.sourceCatalog||`Other`,r=e.charAt(0).toUpperCase()+e.slice(1),i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t.entries()).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({id:`group-source-${SZ(e)}`,key:e,label:e,entries:t}))}if(r===`kind`||r===`type`){let t=new Map;for(let n of e){let e=n.kind.charAt(0).toUpperCase()+n.kind.slice(1)+`s`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-kind-${SZ(e)}`,key:e,label:e,entries:t}))}if(!Dp.includes(r)){let t=new Map;for(let n of e){let e=n.typedTags?.find(e=>e.type?.toLowerCase()===r)?.label??`Unassigned`,i=t.get(e);i?i.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`group-property-${SZ(r)}-${SZ(e)}`,key:e,label:e,entries:t}))}let a=new Map;for(let t of e){let e=t.tags?.[0]?`#${t.tags[0]}`:`Untagged`,n=a.get(e);n?n.push(t):a.set(e,[t])}return Array.from(a.entries()).map(([e,t])=>({id:`group-tag-${SZ(e)}`,key:e,label:e,entries:t}))}var TZ=pt,EZ=Jn,DZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(sn,{ref:n,className:U(`fixed inset-0 z-50 bg-black/80 dark:bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t}));DZ.displayName=sn.displayName;var OZ=V.forwardRef(({className:e,children:t,...n},r)=>(0,H.jsxs)(EZ,{children:[(0,H.jsx)(DZ,{}),(0,H.jsxs)(Rn,{ref:r,className:U(`fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg`,e),...n,children:[t,(0,H.jsxs)(xn,{className:`absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground`,children:[(0,H.jsx)(Te,{className:`h-4 w-4`}),(0,H.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]}));OZ.displayName=Rn.displayName;var kZ=({className:e,...t})=>(0,H.jsx)(`div`,{className:U(`flex flex-col space-y-1.5 text-center sm:text-left`,e),...t});kZ.displayName=`DialogHeader`;var AZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(Dt,{ref:n,className:U(`text-lg font-semibold leading-none tracking-tight`,e),...t}));AZ.displayName=Dt.displayName;var jZ=V.forwardRef(({className:e,...t},n)=>(0,H.jsx)(St,{ref:n,className:U(`text-sm text-muted-foreground`,e),...t}));jZ.displayName=St.displayName;var MZ=[`date`,`datetime-local`,`month`,`time`,`week`],NZ=(0,V.forwardRef)(function({className:e,...t},n){return(0,H.jsx)(`span`,{"data-slot":`control`,className:U(`relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`sm:focus-within:after:ring-2 sm:focus-within:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:(0,H.jsx)(de,{ref:n,...t,className:U(t.type&&MZ.includes(t.type)&&[`[&::-webkit-datetime-edit-fields-wrapper]:p-0`,`[&::-webkit-date-and-time-value]:min-h-[1.5em]`,`[&::-webkit-datetime-edit]:inline-flex`,`[&::-webkit-datetime-edit]:p-0`,`[&::-webkit-datetime-edit-year-field]:p-0`,`[&::-webkit-datetime-edit-month-field]:p-0`,`[&::-webkit-datetime-edit-day-field]:p-0`,`[&::-webkit-datetime-edit-hour-field]:p-0`,`[&::-webkit-datetime-edit-minute-field]:p-0`,`[&::-webkit-datetime-edit-second-field]:p-0`,`[&::-webkit-datetime-edit-millisecond-field]:p-0`,`[&::-webkit-datetime-edit-meridiem-field]:p-0`],`relative block w-full appearance-none rounded-lg px-[calc(theme(spacing.3.5)-1px)] py-[calc(theme(spacing.2.5)-1px)]`,`sm:px-[calc(theme(spacing.3)-1px)] sm:py-[calc(theme(spacing.1.5)-1px)]`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6`,`border border-border/60 hover:border-border data-[hover]:border-border`,`bg-transparent dark:bg-white/5`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 dark:data-[disabled]:border-border/30 dark:data-[disabled]:bg-white/2.5`,`dark:scheme-dark`,e)})})}),PZ=e=>WP(new Date(e)),FZ=e=>{if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`};function IZ(e,t){Z(e===`imported`?{title:`${t} synced`,description:`Content was imported from the published seed. Your own edits were kept.`}:e===`error`?{title:`${t} sync failed`,description:`Check your connection and the browser console for details.`,variant:`destructive`}:e===`busy`?{title:`Another tab is already syncing`,description:`Wait for it to finish, then try again.`}:{title:`${t}: nothing to import (${e})`})}var LZ={imported:`Synced`,current:`Up to date`,"server-stale":`Published version is older than the stored version`,"update-pending":`Update available`,busy:`Another tab is syncing`,disabled:`Seed import is disabled`,error:`Sync failed`};function RZ(e){switch(e.phase){case`checking`:return`Checking source…`;case`fetching`:return`Downloading ${e.chunkId}…`;case`applying`:return`Importing ${e.chunkId}…`;case`committed`:return`Committed ${e.chunkId}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??LZ[e.outcome]}}function zZ({source:e,running:t,disabled:n,onSync:r,onSubscribe:i,onUnsubscribe:a,onDelete:o,onAutoSync:s}){let c=(0,V.useSyncExternalStore)(PO,()=>IO(e.id)),l=e.autoImport,u=e.subscribed&&!e.upToDate&&e.remote!==null;return(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-source-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0 flex-wrap`,children:[(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground truncate`,children:e.label}),(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0 ${e.subscribed?`bg-emerald-500/10 text-emerald-600`:`bg-muted text-muted-foreground`}`,children:e.subscribed?`Subscribed`:`Not subscribed`}),l&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0`,children:`Core`})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0 flex-wrap justify-end`,children:[e.subscribed?u?(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>r(e.id),disabled:n,"data-testid":`seed-sync-${e.id}`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${t?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:t?`Syncing…`:`Sync`})]}):(0,H.jsxs)(`span`,{className:`text-xs text-muted-foreground flex items-center gap-1.5`,"data-testid":`seed-current-${e.id}`,children:[(0,H.jsx)(yn,{className:`size-3.5 text-emerald-500`}),e.remote===null?`Remote unreachable`:`Up to date`]}):(0,H.jsxs)(W,{size:`sm`,onClick:()=>i(e.id),disabled:n,"data-testid":`seed-subscribe-${e.id}`,className:`gap-2`,children:[(0,H.jsx)(ot,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Subscribe`})]}),(0,H.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:e.subscribed?`Apply new published versions automatically during the load-time check. Turning it off never removes content.`:`Unsubscribed sources never auto-import.`,children:[(0,H.jsx)(`input`,{type:`checkbox`,className:`size-3.5 accent-primary`,checked:c,disabled:n||!e.subscribed,onChange:t=>s(e.id,t.target.checked),"aria-label":`Auto-sync ${e.label}`,"data-testid":`seed-autosync-${e.id}`}),(0,H.jsx)(`span`,{children:`Auto-sync`})]}),(0,H.jsxs)(`details`,{className:`relative shrink-0`,"data-testid":`seed-more-${e.id}`,children:[(0,H.jsx)(`summary`,{"aria-label":`More actions for ${e.label}`,className:`flex cursor-pointer list-none items-center justify-center rounded-md border border-border px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden`,children:`…`}),(0,H.jsxs)(`div`,{className:`absolute right-0 z-20 mt-1 flex w-64 max-w-[80vw] flex-col items-stretch gap-1.5 rounded-lg border border-border bg-card p-2 text-xs shadow-lg`,children:[e.url?(0,H.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all font-mono text-primary hover:underline`,children:[`Published HTML: `,e.url]}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Published HTML: bundled with this app (no standalone URL)`}),e.repositoryUrl?(0,H.jsx)(`a`,{href:e.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-primary hover:underline`,children:`Git source directory`}):(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Git repository: not published`}),!l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>a(e.id),disabled:n||!e.subscribed,"data-testid":`seed-unsubscribe-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Unsubscribe`}),!l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(e.id),disabled:n,"data-testid":`seed-delete-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Delete source`})]})]})]})]}),e.url&&(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground font-mono break-all`,"data-testid":`seed-origin-${e.id}`,children:e.url}),(0,H.jsxs)(`div`,{className:`grid gap-1 text-sm`,"data-testid":`seed-status-card`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Library`}),(0,H.jsxs)(`span`,{className:`font-medium text-foreground text-xs tabular-nums`,"data-testid":`seed-source-size`,children:[e.count.toLocaleString(),` catalog `,e.count===1?`item`:`items`,` · `,FZ(e.bytes)]})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Local database`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-local-version`,children:e.stored?`v${e.stored.version} · schema ${e.stored.schema} · imported ${PZ(e.stored.importedAt)}`:`Not imported yet`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Published version`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs flex items-center gap-1.5`,"data-testid":`seed-remote-version`,children:e.remote?`v${e.remote.version} · schema ${e.remote.schema}`:e.remoteError?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(gt,{className:`size-3.5 text-muted-foreground`}),`Unavailable`]}):`Checking…`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last check`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-check`,children:e.checkedAt?PZ(e.checkedAt):`—`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last sync`}),(0,H.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-sync`,children:e.stored?PZ(e.stored.importedAt):`Never`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Status`}),(0,H.jsx)(`span`,{className:`font-medium text-xs flex items-center gap-1.5`,"data-testid":`seed-sync-status`,children:e.subscribed?e.upToDate?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(yn,{className:`size-3.5 text-emerald-500`}),`Up to date`]}):e.remote==null?`Unknown (remote unreachable)`:c?`Update available — applied automatically on next load`:`Update available — sync to apply`:`Not subscribed`})]})]})]})}function BZ(){let[e,t]=(0,V.useState)(null),[n,r]=(0,V.useState)(!0),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)([]),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(null),g=(0,V.useCallback)(async()=>{a(null);try{t(await Rk())}catch(e){a(e instanceof Error?e.message:String(e))}finally{r(!1)}},[]);(0,V.useEffect)(()=>{g()},[g]),(0,V.useEffect)(()=>PO(()=>{g()}),[g]),(0,V.useEffect)(()=>Ck(()=>{g()}),[g]);let _=(0,V.useCallback)(async t=>{s(t??`all`),l([]);let n=e=>l(t=>{let n=t.find(t=>t.event.sourceId===e.sourceId),r={event:e,imported:e.phase===`checking`||e.phase===`finished`?n?.imported??null:e,chunks:e.phase===`committed`&&e.chunkId!==null?[...n?.chunks??[],e.chunkId]:n?.chunks??[]};return n?t.map(t=>t.event.sourceId===e.sourceId?r:t):[...t,r]});try{IZ(t?await Nk(t,{force:!0,onProgress:n}):await Ak({force:!0,onProgress:n}),t?e?.sources.find(e=>e.id===t)?.label??t:`All sources`),await g()}finally{s(null)}},[g,e]),v=(0,V.useCallback)(async()=>{h(null);let e;try{e=lO(u,f)}catch(e){h(e instanceof Error?e.message:String(e));return}d(``),p(``),await _(e.id)},[u,f,_]),y=(0,V.useCallback)((e,t)=>{LO(e,t)||Z({title:`Couldn't save Auto-sync`,description:`Browser storage is unavailable — the choice lasts this session only.`,variant:`destructive`}),g()},[g]),b=(0,V.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Unsubscribe from "${n}"? Imported content for this catalog is removed from your library; the source stays listed so you can subscribe again. Your own notes are never touched.`)){try{let{deleted:e}=await Pk(t);Z({title:`${n} unsubscribed`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed. The source stays listed for a later Subscribe.`})}catch(e){Z({title:`${n} unsubscribe failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await g()}},[e,g]),x=(0,V.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Delete "${n}"? Imported content is removed and the source is unregistered. Your own notes are never touched.`)){try{let{deleted:e}=await Fk(t);Z({title:`${n} deleted`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed and the source unregistered.`})}catch(e){Z({title:`${n} delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await g()}},[e,g]),S=c.at(-1)?.event;return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(ot,{className:`size-4 text-primary`}),`Content Sources`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Notebooks, notes, guides, dashboards, and efforts import into your active data location from seed sources. Subscribed sources are checked against their published manifest on every load: Auto-sync applies updates by itself, otherwise you press Sync when an update is pending. The core seed imports automatically at launch and is always subscribed.`})]}),i&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-destructive`,"data-testid":`seed-status-error`,children:[(0,H.jsx)(gt,{className:`size-3.5 shrink-0`}),`Couldn't read the seed status from the active storage: `,i]}),S&&(0,H.jsxs)(`div`,{className:`space-y-3 rounded-xl border border-border bg-card p-4`,"data-testid":`seed-sync-progress`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-sm font-medium`,children:[(0,H.jsx)(`span`,{children:o===null?c.some(e=>e.event.phase===`finished`&&e.event.outcome===`error`)?`Sync finished with errors`:`Sync finished`:`Syncing…`}),(0,H.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[`Source `,S.sourceIndex,` of `,S.totalSources]})]}),(0,H.jsxs)(`p`,{role:`status`,"aria-live":`polite`,className:`sr-only`,"data-testid":`seed-sync-live-status`,children:[S.sourceLabel,`: `,RZ(S)]}),c.map(({event:e,imported:t,chunks:n})=>(0,H.jsxs)(`div`,{className:`space-y-2 border-t border-border/50 pt-3`,children:[(0,H.jsxs)(`p`,{className:`text-xs ${e.phase===`finished`&&e.outcome===`error`?`text-destructive`:`text-muted-foreground`}`,children:[(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:e.sourceLabel}),` · `,RZ(e)]}),t&&t.totalChunks>0?(0,H.jsx)(vZ,{value:t.completedChunks,max:t.totalChunks,label:`Chunks committed · ${e.sourceLabel}`}):e.phase===`finished`?null:(0,H.jsx)(`progress`,{"aria-label":`Checking ${e.sourceLabel}`,className:`h-2 w-full`}),t&&(0,H.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-xs tabular-nums`,"data-testid":`seed-sync-totals`,children:[(0,H.jsxs)(`span`,{children:[t.totalNotes.toLocaleString(),` notes`]}),(0,H.jsxs)(`span`,{children:[t.totalEfforts.toLocaleString(),` efforts`]}),(0,H.jsxs)(`span`,{children:[t.totalBlocks.toLocaleString(),` blocks`]}),t.skippedUserOwned>0&&(0,H.jsxs)(`span`,{children:[t.skippedUserOwned.toLocaleString(),` user-owned rows preserved`]}),t.deleted>0&&(0,H.jsxs)(`span`,{children:[t.deleted.toLocaleString(),` seed rows removed`]})]}),n.length>0&&(0,H.jsxs)(`details`,{className:`text-xs`,"data-testid":`seed-sync-chunks`,children:[(0,H.jsxs)(`summary`,{className:`cursor-pointer text-muted-foreground`,children:[`Committed chunks (`,n.length,`)`]}),(0,H.jsx)(`ul`,{className:`mt-2 max-h-32 space-y-1 overflow-y-auto font-mono text-muted-foreground`,children:n.map(e=>(0,H.jsx)(`li`,{children:e},e))})]})]},e.sourceId))]}),(0,H.jsxs)(`div`,{className:`grid gap-3`,"data-testid":`seed-source-list`,children:[e?.sources.map(e=>(0,H.jsx)(zZ,{source:e,running:o===e.id||o===`all`,disabled:o!==null,onSync:e=>{_(e)},onSubscribe:e=>{_(e)},onUnsubscribe:e=>{b(e)},onDelete:e=>{x(e)},onAutoSync:y},e.id)),n&&e===null&&(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,children:`Checking sources…`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between pt-3 border-t border-border/50`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sync re-applies every published chunk. Your own notes, results, and edits are never overwritten.`}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>{_(null)},disabled:o!==null||n,"data-testid":`seed-resync-button`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${o===`all`?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:o===`all`?`Syncing all…`:`Sync All Sources`})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(be,{className:`size-4 text-primary`}),`Add a Source`]}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Register any URL serving a Wod Wiki seed (a directory with `,(0,H.jsx)(`code`,{children:`manifest.json`}),` and`,` `,(0,H.jsx)(`code`,{children:`chunks/`}),`) — a community library mirror or one you compiled yourself. The host must allow cross-origin reads (CORS). Added sources sync immediately and start subscribed; manage Auto-sync, Unsubscribe, and Delete on each source card above.`]})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-add-source-form`,children:[(0,H.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`seed-source-label`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Label`}),(0,H.jsx)(NZ,{id:`seed-source-label`,value:u,onChange:e=>d(e.target.value),placeholder:`My library (optional — defaults to the host name)`,disabled:o!==null})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`seed-source-url`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Seed directory URL`}),(0,H.jsx)(NZ,{id:`seed-source-url`,type:`text`,autoComplete:`off`,spellCheck:!1,value:f,onChange:e=>p(e.target.value),placeholder:`https://example.com/seed/library/`,className:`font-mono`,disabled:o!==null})]})]}),m&&(0,H.jsxs)(`p`,{role:`alert`,className:`flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`seed-add-error`,children:[(0,H.jsx)(gt,{className:`size-3.5 mt-0.5 shrink-0`}),(0,H.jsx)(`span`,{children:m})]}),(0,H.jsx)(`div`,{className:`flex justify-end`,children:(0,H.jsxs)(W,{size:`sm`,onClick:()=>{v()},disabled:o!==null||!f.trim(),"data-testid":`seed-add-button`,className:`gap-2`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Add & Sync`})]})})]})]})]})}function VZ({open:e,onOpenChange:t}){return(0,H.jsx)(TZ,{open:e,onOpenChange:t,children:(0,H.jsxs)(OZ,{className:`max-h-[85vh] w-full max-w-2xl overflow-y-auto`,"data-testid":`catalogs-manager-drawer`,children:[(0,H.jsxs)(kZ,{children:[(0,H.jsx)(AZ,{children:`Notebook Subscriptions & Local Libraries`}),(0,H.jsx)(jZ,{children:`Manage the workout notebooks stored in your active data location — compare versions, sync updates, and subscribe, unsubscribe, or delete sources. Your own notes are never touched.`})]}),(0,H.jsx)(BZ,{})]})})}var HZ={stream:`cards`,table:`rows`},UZ=`wodwiki.viewSettings.v1`,WZ={"/sessions":`/results`,"/feeds":`/collections`},GZ=new qy(UZ);function KZ(e,t){return{level:e,layout:t??`cards`,visibleFields:PL(e),groupBy:void 0}}function qZ(e,t,n=GZ,r){let i=KZ(t,r),a=e.startsWith(`/`)?e:`/${e}`,o=WZ[a],s=n.get(a,{alias:o});if(!s)return i;let c=typeof s.layout==`string`?s.layout:``,l=c===`cards`||c===`rows`||c===`feed`?c:HZ[c]??`cards`,u=new Set(NL(t).map(e=>e.id)),d=Array.isArray(s.visibleFields)?s.visibleFields.filter(e=>typeof e==`string`&&u.has(e)):i.visibleFields,f=typeof s.groupBy==`string`?s.groupBy:void 0;return{level:t,layout:l,visibleFields:d.length>0?d:i.visibleFields,groupBy:f}}function JZ(e,t,n=GZ){let r=e.startsWith(`/`)?e:`/${e}`;n.set(r,{level:t.level,layout:t.layout,visibleFields:t.visibleFields,groupBy:t.groupBy})}function YZ(e,t,n=GZ){let r=e.startsWith(`/`)?e:`/${e}`,i=WZ[r];return n.remove(r,i),KZ(t)}function XZ(e,t,n){let[r,i]=(0,V.useState)(()=>qZ(e,t,GZ,n));(0,V.useEffect)(()=>{i(qZ(e,t,GZ,n))},[e,t,n]);let a=(0,V.useCallback)(t=>{i(n=>{let r=t(n);return JZ(e,r),r})},[e]);return{settings:r,setLayout:(0,V.useCallback)(e=>{a(t=>({...t,layout:e}))},[a]),toggleField:(0,V.useCallback)(e=>{a(t=>{let n=new Set(t.visibleFields);return n.has(e)?n.delete(e):n.add(e),{...t,visibleFields:Array.from(n)}})},[a]),setVisibleFields:(0,V.useCallback)(e=>{a(t=>({...t,visibleFields:e}))},[a]),setGroupBy:(0,V.useCallback)(e=>{a(t=>({...t,groupBy:e}))},[a]),resetSettings:(0,V.useCallback)(()=>{let n=YZ(e,t);i(n)},[e,t])}}function ZZ(e,t=200){let[n,r]=(0,V.useState)(t),i=(0,V.useRef)(null);(0,V.useEffect)(()=>{r(t)},[e,t]);let a=n<e.length,o=(0,V.useCallback)(t=>r(n=>Math.max(n,Math.min(Math.max(t,0),e.length))),[e.length]);return(0,V.useEffect)(()=>{let n=i.current;if(!n||!a)return;let o=new IntersectionObserver(n=>{n.some(e=>e.isIntersecting)&&r(n=>Math.min(n+t,e.length))},{rootMargin:`400px`});return o.observe(n),()=>o.disconnect()},[a,e.length,t]),{visible:e.slice(0,n),hasMore:a,sentinelRef:i,total:e.length,growTo:o}}function QZ(e,t){let n=Y(e);return n.error||!nm(n)?e:Km({...n,metric:t})}function $Z(e){let t=Y(e);return t.error?e:Km({...t,window:void 0})}function eQ(e){let t=Y(e);return t.error?e:Km({...t,filters:t.filters.filter(e=>e.key===`source`)})}function tQ(e,t){let n=Y(e);return n.error?e:Km({...n,groupBy:[t]})}function nQ(e){return e.kind===`session`&&!e.sourceItem?!1:e.kind===`note`||e.kind===`session`||e.kind===`post`}async function rQ(e){if(e.wodBlock?.content.trim())return e.wodBlock.content;let t=await Kj.resolve(e.id),n=fz(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``),r=n.find(e=>e.dialect===`time`)??n[0];if(!r)throw Error(`No runnable workout block in this entry.`);return r.script}function iQ(e,t){return{id:e.wodBlock?.blockId??e.block?.blockId??C(),contentId:e.wodBlock?.blockContentId??e.blockContentId,dialect:`time`,startLine:0,endLine:t.split(`
167
+ `).length,content:t,state:`idle`,widgetIds:{},version:1,createdAt:Date.now()}}async function aQ(e,t){let n=await rQ(e),r=iQ(e,n),i=C();if(wz(e)){let n=await Kj.getById(e.id),a=e.wodBlock||e.block?n.blocks?.[r.id]:Object.values(n.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The selected saved workout is unavailable.`);QJ.set(i,{block:{...r,id:a.id},noteId:e.id,origin:`playground`,returnTo:Cz(e)}),t(QA(i));return}let a=await zJ({workoutName:e.title,category:e.sourceCatalog,sourceNoteLabel:e.subtitle??e.title,sourceNotePath:Cz(e),wodContent:n}),o=Object.values(a.blocks??{}).find(e=>e.kind===`wod`);if(!o)throw Error(`The saved journal workout is unavailable.`);QJ.set(i,{block:{...r,id:o.id},noteId:a.id}),t(JA(a.journalDate??``,i))}var oQ={note:N,session:Rt,post:qt,effort:ce,result:Ue,segment:me,event:S,dashboard:tn,equipment:D},sQ={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},cQ={note:`bg-primary/10 text-primary group-hover:bg-primary/20`,session:`bg-amber-500/10 text-amber-600 group-hover:bg-amber-500/20`,post:`bg-violet-500/10 text-violet-600 group-hover:bg-violet-500/20`,effort:`bg-emerald-500/10 text-emerald-600 group-hover:bg-emerald-500/20`,result:`bg-sky-500/10 text-sky-600 group-hover:bg-sky-500/20`,segment:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,event:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,dashboard:`bg-cyan-500/10 text-cyan-600 group-hover:bg-cyan-500/20`,equipment:`bg-orange-500/10 text-orange-600 group-hover:bg-orange-500/20`};function lQ({entry:e,leading:t,actions:n,dateLabel:r,visibleFieldIds:i,tone:a=`secondary`,onAddToToday:o,onRunStart:s}){let c=Sn(),l=e.kind===`note`?e.sourceCatalog:void 0,d=l===`playground`?u:l===`guides`?lr:oQ[e.kind],f=l===`playground`?`Playground`:l===`guides`?`Guide`:sQ[e.kind],p=a===`primary`,m=Tz(e),h=Cz(e),g=i?new Set(i):null,_=!g||g.has(`date`),v=!g||g.has(`catalog`)||g.has(`protocol`)||g.has(`elapsedTime`)||g.has(`splitDuration`)||g.has(`discipline`)||g.has(`met`)||g.has(`canonicalSlug`),y=!g||g.has(`excerpt`)||g.has(`movements`)||g.has(`tags`)||g.has(`aliases`);return(0,H.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:()=>c(Cz(e)),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),c(Cz(e)))},className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group w-full cursor-pointer ${p?`bg-primary/[0.025]`:``}`,"data-testid":`library-row-${e.kind}`,children:[t,(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl flex items-center justify-center transition-colors ${cQ[e.kind]}`,children:(0,H.jsx)(d,{className:`size-4`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:e.title}),e.block&&(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-sky-600 border border-sky-500/40 bg-sky-500/10 rounded-full px-1.5 py-0.5`,"data-testid":`library-row-block-type`,children:e.block.dataType}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:f}),e.execution?.effortSlug&&(0,H.jsx)(Wn,{to:cj(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`library-row-effort-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors shrink-0`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:e.detail??e.execution.effortSlug}),m&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(Wn,{to:h,"data-testid":`library-row-details-link`,className:`text-[9px] font-bold tracking-wide text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border rounded-full px-2 py-0.5 transition-colors`,title:`View catalog details`,children:`Details`}),(0,H.jsx)(Wn,{to:m,"data-testid":`library-row-feed-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors`,title:`View feed`,children:`Feed`})]}),e.subtitle&&v&&(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/60 truncate`,children:e.subtitle})]}),y&&(e.block?(0,H.jsx)(`div`,{className:`mt-0.5`,"data-testid":`library-row-block-preview`,children:e.block.preview.map((e,t)=>(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate font-mono`,children:e},t))}):e.detail?(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate mt-0.5`,children:e.detail}):null)]}),r&&_&&(0,H.jsx)(`span`,{className:`flex-shrink-0 text-[10px] text-muted-foreground/70 tabular-nums`,"data-testid":`library-row-date`,children:r}),n??(0,H.jsx)(uQ,{entry:e,onAddToToday:o,onRunStart:s})]})}function uQ({entry:e,onAddToToday:t,onRunStart:n}){let r=Sn(),i=Ez(e),a=Tz(e),o=Dz(e)&&!!t,s=nQ(e)&&!!n;return(0,H.jsxs)(`div`,{className:`flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(dQ,{title:a?`Details`:`Open`,testId:`action-open`,onClick:()=>r(Cz(e)),children:(0,H.jsx)(Ht,{className:`size-3.5`})}),a&&(0,H.jsx)(dQ,{title:`Feed`,testId:`action-feed`,onClick:()=>r(a),children:(0,H.jsx)(Rt,{className:`size-3.5`})}),o&&(0,H.jsx)(dQ,{title:`Add to today`,testId:`action-add`,onClick:()=>t?.(e),children:(0,H.jsx)(Kt,{className:`size-3.5`})}),s&&(0,H.jsx)(dQ,{title:`Run`,testId:`action-run`,onClick:()=>n?.(e),children:(0,H.jsx)(Ht,{className:`size-3.5`})}),i&&(0,H.jsx)(dQ,{title:`Compare`,testId:`action-compare`,onClick:()=>r(i),children:(0,H.jsx)(At,{className:`size-3.5`})})]})}function dQ({title:e,testId:t,onClick:n,children:r}){return(0,H.jsx)(`button`,{type:`button`,title:e,onClick:n,"data-testid":t,className:`size-8 rounded-lg flex items-center justify-center text-muted-foreground hover:text-primary hover:bg-primary/10 transition-colors`,children:r})}function fQ({entries:e,level:t,visibleFieldIds:n,onRowClick:r,emptyMessage:i=`No entries to display`,className:a=``,stickyHeaderTop:o}){let s=Sn(),c=(0,V.useMemo)(()=>t||(e.length>0?AL(e[0]):`note`),[t,e]),l=(0,V.useMemo)(()=>NL(c),[c]),u=(0,V.useMemo)(()=>{let e=new Set(n??PL(c));return l.filter(t=>e.has(t.id))},[l,n,c]),d=e=>{r?r(e):s(Cz(e))},[f,p]=(0,V.useState)(null),[m,h]=(0,V.useState)(`asc`),g=e=>{f===e?h(e=>e===`asc`?`desc`:`asc`):(p(e),h(`asc`))},_=(0,V.useMemo)(()=>{if(!f)return e;let t=l.find(e=>e.id===f);return t?[...e].sort((e,n)=>{let r=t.getValue(e),i=t.getValue(n);if(r==null&&i==null)return 0;if(r==null)return m===`asc`?1:-1;if(i==null)return m===`asc`?-1:1;if(typeof r==`number`&&typeof i==`number`)return m===`asc`?r-i:i-r;if(Array.isArray(r)&&Array.isArray(i)){let e=r.join(`, `),t=i.join(`, `);return m===`asc`?e.localeCompare(t):t.localeCompare(e)}let a=String(r),o=String(i);return m===`asc`?a.localeCompare(o):o.localeCompare(a)}):e},[e,f,m,l]);return e.length===0?(0,H.jsx)(`div`,{className:`w-full py-16 text-center text-sm text-muted-foreground ${a}`,"data-testid":`property-table-empty`,children:i}):(0,H.jsx)(`div`,{className:`w-full border-y border-border bg-card/50 ${o===void 0?`overflow-x-auto`:`overflow-x-clip`} ${a}`,"data-testid":`property-table`,children:(0,H.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,H.jsx)(`thead`,{className:o===void 0?void 0:`sticky z-10`,style:o===void 0?void 0:{top:`${o}px`},children:(0,H.jsx)(`tr`,{className:`border-b border-border`,children:u.map(e=>{let t=e.align===`right`?`text-right`:e.align===`center`?`text-center`:`text-left`;return(0,H.jsx)(`th`,{scope:`col`,onClick:()=>g(e.id),className:`px-4 py-3 font-semibold uppercase tracking-wider text-[11px] text-muted-foreground whitespace-nowrap border-b border-border cursor-pointer select-none hover:text-foreground transition-colors group/th ${o===void 0?`bg-muted/30`:`bg-muted/95 backdrop-blur-sm`} ${t}`,"data-testid":`property-table-header-${e.id}`,children:(0,H.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 ${t===`text-right`?`justify-end`:t===`text-center`?`justify-center`:`justify-start`}`,children:[(0,H.jsx)(`span`,{children:e.label}),f===e.id?(0,H.jsx)(`span`,{className:`text-primary font-bold text-xs`,"aria-label":m===`asc`?`sorted ascending`:`sorted descending`,children:m===`asc`?`↑`:`↓`}):(0,H.jsx)(`span`,{className:`opacity-0 group-hover/th:opacity-40 text-muted-foreground text-[10px]`,"aria-hidden":`true`,children:`↕`})]})},e.id)})})}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border/60`,children:_.map(e=>{let t=Tz(e),n=Cz(e);return(0,H.jsx)(`tr`,{role:`button`,tabIndex:0,onClick:()=>d(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),d(e))},className:`hover:bg-muted/40 transition-colors cursor-pointer group`,"data-testid":`property-table-row-${e.id}`,children:u.map(r=>{let i=r.getValue(e),a=r.formatValue(i,e),o=r.align===`right`?`text-right tabular-nums`:r.align===`center`?`text-center`:`text-left`;return(0,H.jsx)(`td`,{className:`px-4 py-3 whitespace-nowrap text-foreground/90 ${o}`,"data-testid":`property-table-cell-${r.id}`,children:r.id===`pacingTier`&&e.execution?.effortSlug?(0,H.jsx)(Wn,{to:cj(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`property-table-effort-link`,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:a}):r.id===`title`||r.id===`label`?(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`font-medium text-foreground group-hover:text-primary transition-colors`,children:a}),t&&(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-auto`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(Wn,{to:n,"data-testid":`property-table-details-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border transition-colors`,title:`View catalog details`,children:`Details`}),(0,H.jsx)(Wn,{to:t,"data-testid":`property-table-feed-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View feed`,children:`Feed`})]})]}):a},r.id)})},e.id)})})]})})}var pQ={note:N,session:Rt,post:N,effort:ce,result:Ue,segment:me,event:S,dashboard:tn,equipment:D},mQ={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},hQ=8;function gQ({entry:e}){let t=e.execution;if(!t)return null;let n=[];return t.elapsedMs!=null&&n.push(_I(t.elapsedMs)),t.reps!=null&&n.push(`${t.reps} reps`),t.loadLbs!=null&&n.push(`${t.loadLbs} lb`),t.distanceMeters!=null&&n.push(`${(t.distanceMeters/1e3).toFixed(2)} km`),t.tis!=null&&n.push(`TIS ${t.tis}`),n.length===0?null:(0,H.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1.5`,"data-testid":`stream-feed-metrics`,children:n.map(e=>(0,H.jsx)(`span`,{className:`rounded-full bg-muted/70 border border-border/60 px-2 py-0.5 text-[10px] font-bold tabular-nums text-muted-foreground`,children:e},e))})}function _Q({entry:e}){let[t,n]=(0,V.useState)(!1),r=e.wodBlock?.content.trim(),i=r?r.split(`
168
+ `):e.excerpt??e.block?.preview??[],a=i.length>hQ,o=t||!a?i:i.slice(0,hQ);return i.length===0&&!e.detail?null:(0,H.jsxs)(`div`,{className:`mt-1.5`,"data-testid":`stream-feed-preview`,children:[i.length>0&&(0,H.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground ${a&&!t?`max-h-40 overflow-hidden`:``}`,children:o.join(`
169
+ `)}),i.length===0&&e.detail&&(0,H.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.detail}),a&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>n(e=>!e),"data-testid":`stream-feed-preview-toggle`,className:`mt-1 min-h-[44px] px-2 -ml-2 text-[10px] font-black uppercase tracking-widest text-primary hover:text-primary/80 transition-colors`,children:t?`Show less`:`Show more (${i.length-hQ} lines)`})]})}function vQ({groups:e,batch:t,onRunEntry:n,onSendToPlayground:r,stickyOffset:i}){return(0,H.jsxs)(`div`,{className:`flex-1 divide-y divide-border/40`,"data-testid":`stream-feed`,children:[e.map(e=>(0,H.jsxs)(`section`,{id:e.id,"data-testid":`stream-feed-group-${e.key}`,children:[(0,H.jsx)(oL,{top:i,icon:(0,H.jsx)(qt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,H.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${e.entries.length} ${e.entries.length===1?`entry`:`entries`}`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(e=>{let t=e.kind===`note`?e.sourceCatalog:void 0,i=t===`playground`?u:t===`guides`?lr:pQ[e.kind],a=t===`playground`?`Playground`:t===`guides`?`Guide`:mQ[e.kind],o=Cz(e),s=Tz(e),c=!wz(e)&&(e.kind===`note`||e.kind===`session`||e.kind===`post`);return(0,H.jsx)(`article`,{"data-testid":`stream-feed-item`,className:`px-6 py-4`,children:(0,H.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center`,children:(0,H.jsx)(i,{className:`size-4 text-primary`})}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:(0,H.jsx)(Wn,{to:o,className:`hover:text-primary transition-colors`,children:e.title})}),(0,H.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:a}),e.subtitle&&(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground/70 truncate`,children:e.subtitle})]}),(0,H.jsx)(_Q,{entry:e}),(0,H.jsx)(gQ,{entry:e}),(0,H.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,H.jsx)(Wn,{to:o,"data-testid":`stream-feed-open`,className:`inline-flex min-h-[44px] items-center rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:s?`Details`:`Open`}),s&&(0,H.jsxs)(Wn,{to:s,"data-testid":`stream-feed-collection-feed`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,H.jsx)(Rt,{className:`size-3`}),`Feed`]}),nQ(e)&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e),"data-testid":`stream-feed-run`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,H.jsx)(Ht,{className:`size-3`}),`Run`]}),c&&r&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"data-testid":`stream-feed-playground`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:[(0,H.jsx)(er,{className:`size-3`}),`Playground`]})]})]})]})},e.id)})})]},e.id)),t.hasMore&&(0,H.jsxs)(`div`,{ref:t.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-feed-load-more`,children:[`Loading more — `,t.total-t.visible.length,` remaining…`]})]})}function yQ(e,t,n){return{journalDate:n,title:e.title,rawContent:t,sourceId:e.sourceId,type:`journal`}}var bQ=/\[([^\]]*)\]\((:[^)]*)\)!/g;function xQ(e){let t=e.trim();try{return decodeURIComponent(t)}catch{return t}}function SQ(e){let t=xQ(e);return t.startsWith(`:`)&&!Y(t).error}function CQ(e){let t=[],n=0;for(let r of e.matchAll(bQ)){let i=r.index??0,a=xQ(r[2]);SQ(a)&&(i>n&&t.push({kind:`markdown`,text:e.slice(n,i)}),t.push({kind:`query`,query:a.trim(),heading:r[1]}),n=i+r[0].length)}n<e.length&&t.push({kind:`markdown`,text:e.slice(n)});let r=[];for(let e of t){let t=r[r.length-1];e.kind===`markdown`&&t?.kind===`markdown`?t.text+=e.text:r.push(e)}return r}function wQ(e){return e.some(e=>e.kind===`query`)}var TQ=`9999-12-31`;function EQ(e,t){return(e.date??TQ).localeCompare(t.date??TQ)||e.title.localeCompare(t.title,void 0,{numeric:!0,sensitivity:`base`})}function DQ(e){let t=new Date(`${e}T12:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`,year:`numeric`})}function OQ({query:e,heading:t,onAddToToday:n,onRunStart:r}){let[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(null);(0,V.useEffect)(()=>{let t=!1;return a(null),s(null),OI.query(e).then(e=>{t||a([...e].sort(EQ))}).catch(e=>{t||s(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let c=(0,V.useMemo)(()=>{if(!i)return null;let t=Y(e);if(t.error||!(`groupBy`in t)||!t.groupBy?.includes(`date`))return null;let n=new Map;for(let e of i){let t=e.date??``,r=n.get(t);r?r.push(e):n.set(t,[e])}return[...n.entries()]},[i,e]);if(o)return(0,H.jsxs)(`p`,{className:`my-3 text-xs text-destructive`,"data-testid":`readme-query-error`,children:[`Query failed: `,o]});if(i===null)return(0,H.jsx)(`div`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-loading`,children:`Loading…`});if(i.length===0)return(0,H.jsx)(`p`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-empty`,children:`No entries match this query.`});let l=e=>(0,H.jsx)(lQ,{entry:e,onAddToToday:n,onRunStart:r},e.id);return(0,H.jsxs)(`div`,{className:`my-3 not-prose`,"data-testid":`readme-query-block`,children:[t&&(0,H.jsx)(`p`,{className:`mt-4 mb-1 text-sm font-bold text-foreground`,"data-testid":`readme-query-heading`,children:t}),c?c.map(([e,t])=>(0,H.jsxs)(`div`,{className:`mt-3`,"data-testid":`readme-query-date-group`,children:[(0,H.jsx)(`p`,{className:`mb-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,children:e?DQ(e):`Undated`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:t.map(l)})]},e||`undated`)):(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:i.map(l)})]})}var kQ=new ID,AQ=[{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`}];function jQ({batch:e,testId:t=`stream-load-more`}){return e.hasMore?(0,H.jsxs)(`div`,{ref:e.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":t,children:[`Loading more — `,e.total-e.visible.length,` remaining…`]}):null}var MQ=150;function NQ(e){switch(e.phase){case`checking`:return`Checking the community library…`;case`fetching`:return`Downloading ${e.chunkId??`library`}…`;case`applying`:return`Importing ${e.chunkId??`library`}…`;case`committed`:return`Committed ${e.chunkId??`chunk`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??`Done`}}function PQ({error:e,target:t,matched:n,total:r,loading:i,applied:a,ignored:o,advisories:s,groupDims:c,groupingSource:l}){return(0,H.jsxs)(`div`,{role:`status`,"data-testid":`stream-query-status`,className:`flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground`,children:[e?(0,H.jsx)(`span`,{className:`font-semibold text-destructive`,children:`Invalid query — showing previous results`}):t?(0,H.jsxs)(`span`,{className:`font-mono`,children:[`:`,t]}):null,(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{"data-testid":`stream-query-counts`,className:i?`motion-safe:animate-pulse`:void 0,children:[n,` of `,r]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{"data-testid":`stream-query-filters`,children:[a,` applied`,o>0?`, ${o} ignored`:``]}),(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,H.jsxs)(`span`,{children:[`by `,c.join(`, `),` `,(0,H.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`(`,l,`)`]})]}),s.map(e=>(0,H.jsx)(`p`,{className:`w-full break-words text-amber-700 dark:text-amber-400`,children:e},e))]})}function FQ({profile:e,actions:t,queryEngine:n,onAddToToday:r,registerStreamDraft:i}){let a=Sn(),o=mt(),s=dZ(),c=hZ(),[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),{query:_,setQuery:v,urlQueryError:y}=bA({defaultQuery:()=>e.defaultWql,legacy:e.legacy});(0,V.useEffect)(()=>i?.(()=>_),[i,_]);let{settings:b,setLayout:x,toggleField:S,setGroupBy:C}=XZ(e.route,e.level,e.defaultLayout),[w,T]=(0,V.useState)([]),[E,D]=(0,V.useState)(void 0),[O,k]=(0,V.useState)(null),[A,j]=(0,V.useState)(!0),[M,N]=(0,V.useState)(!1),[P,F]=(0,V.useState)(null),I=UL(),ee=dL(),te=e.route===`/catalogs`,ne=(0,V.useMemo)(()=>te&&new URLSearchParams(o.search).get(`manage`)===`1`,[te,o.search]),re=(0,V.useCallback)(e=>{let t=new URLSearchParams(o.search);e?t.set(`manage`,`1`):t.delete(`manage`);let n=t.toString();a({pathname:o.pathname,search:n?`?${n}`:``},{replace:!e})},[a,o.pathname,o.search]),ie=te?(0,H.jsx)(VZ,{open:ne,onOpenChange:re}):null,[ae,oe]=(0,V.useState)(!1),se=(0,V.useCallback)(async(e,t,n)=>{let r=await WO.create(e,t,n);return await X.saveNote(WO.createNotebookLandingNote(r)),Se(e=>e+1),r},[]),ce=te?(0,H.jsx)(_Z,{open:ae,onOpenChange:oe,onCreate:se}):null,L=(0,V.useMemo)(()=>Y(_),[_]),le=(0,V.useMemo)(()=>L.error||rm(L)?!1:L.filters.some(e=>e.key===`source`&&!e.negate&&e.values.some(e=>e.value===`playground`)),[L]),ue=(0,V.useMemo)(()=>{if(e.catalog)return e.catalog;if(e.route.startsWith(`/c/`)){let t=e.route.slice(3);if(t&&!t.includes(`/`))return t}if(!L.error&&tm(L)){let e=L.filters.find(e=>(e.key===`notebook`||e.key===`catalog`)&&!e.negate)?.values[0]?.value;if(e)return xa(e)}},[e,L]),R=sD(),[de,fe]=(0,V.useState)(null),pe=(0,V.useMemo)(()=>de?CQ(de):[],[de]),me=wQ(pe);(0,V.useEffect)(()=>{if(!ue){fe(null);return}let e=`markdown/collections/${ue}/README.md`,t=R?.[e];t&&fe(t.replace(/\{\{workouts\}\}/g,``).trim());let n=!1;return Kv(e).then(async e=>{try{let t=await kQ.getEntry(e);!n&&t?.rawContent&&fe(t.rawContent.replace(/\{\{workouts\}\}/g,``).trim())}catch{}}),()=>{n=!0}},[ue,R]);let he=(0,V.useMemo)(()=>{let e=n??OI;return b.layout===`feed`?e.withNoteBlockInfo():e},[n,b.layout]),ge=(0,V.useCallback)(async e=>{let t=_z(),n=``,r=e.kind===`result`||e.kind===`segment`?e.execution?.noteId:e.kind===`note`?e.sourceItem:e.id;if(r){if(e.kind===`segment`&&e.blockContentId){let t=(await XF.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]})).blocks.find(t=>t.id===e.blockContentId);t?.rawContent&&(n=t.rawContent)}if(!n&&(e.kind===`note`||e.kind===`result`||e.kind===`segment`)){let e=await Kj.getById(r);e&&typeof e==`object`&&`rawContent`in e&&typeof e.rawContent==`string`&&(n=e.rawContent)}if(!n&&e.kind!==`note`){let e=await XF.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]});e.blocks.length>0&&(n=[...e.blocks].sort((e,t)=>(e.position??0)-(t.position??0)).filter(e=>e.rawContent.trim()!==``).map(e=>e.dataType===`frontmatter`?`---\n${e.rawContent}\n---`:e.rawContent).join(`
158
170
 
159
- `))}}let i=cQ(e,n,t);await Kj.create(i)},[]),_e=r??ge,ve=(0,V.useCallback)(async e=>{F(null);try{await JZ(e,a)}catch(e){F(e instanceof Error?e.message:`Could not start the workout.`)}},[a]),ye=(0,V.useCallback)(async e=>{F(null);try{let t=await Kj.resolve(e.id),{routeId:n}=await aH(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``,{title:e.title});a(WA(n.replace(/^playground\//,``)))}catch(e){F(e instanceof Error?e.message:`Could not create the playground entry.`)}},[a]),be=(0,V.useCallback)(e=>tm(e)?XF.runFind(e):XF.runQuery(e.raw),[]),[xe,Se]=(0,V.useState)(0);(0,V.useEffect)(()=>xV(()=>Se(e=>e+1)),[]),(0,V.useEffect)(()=>{let e=mb().result?.id??-1;return hb(()=>{let t=mb().result?.id??-1;t!==e&&(e=t,Se(e=>e+1))})},[]);let Ce=(0,V.useCallback)(async()=>{f(!0),g(null),m(null);try{let e=await Nk(`community`,{force:!0,onProgress:m});e===`imported`||e===`current`?(u(!0),Se(e=>e+1)):e===`busy`?g(`Another tab is already syncing — wait for it to finish, then try again.`):e===`disabled`&&g(`Seed import is disabled.`)}finally{f(!1)}},[]);(0,V.useEffect)(()=>{if(s===`preparing`)return;if(L.error){N(!1);return}let e=!1,t=setTimeout(()=>{N(!0),D(void 0),he.query(_,t=>{e||D(t)}).then(t=>{e||(T(t),k(uZ(_,L)),eN({pathname:o.pathname,query:_,entries:t}))}).catch(()=>{e||(T([]),eN({pathname:o.pathname,query:_,entries:[]}))}).finally(()=>{e||N(!1)})},xQ);return()=>{e=!0,clearTimeout(t)}},[_,he,L,o.pathname,s,xe]);let we=(0,V.useMemo)(()=>O?.length?O:b.groupBy?[b.groupBy]:[e.level===`effort`?`discipline`:`date`],[O,b.groupBy,e.level]),Te=O?.length?`query`:b.groupBy?`view`:`level`,Ee=(0,V.useMemo)(()=>new Set(L.error||!tm(L)?[]:zp(L.target,`find`)),[L]),De=L.error||rm(L)?0:L.filters.filter(e=>Ee.has(e.key)).length,Oe=(L.error||rm(L)?0:L.filters.length)-De,ke=e.shelfVisible&&!le,Ae=(0,V.useMemo)(()=>fZ(w,we,{shelfVisible:ke}),[w,we,ke]),je=BZ(w),{visible:Me,growTo:Ne}=je,Pe=(0,V.useMemo)(()=>fZ(Me,we,{shelfVisible:ke}),[Me,we,ke]),Fe=(0,V.useMemo)(()=>new Map(Ae.map(e=>[e.id,e.entries.length])),[Ae]),{setL3Items:Ie,scrollToSection:Le,navState:Re,setStreamControls:ze}=hA();(0,V.useEffect)(()=>{if(Ae.length===0){Ie([]);return}let e=Ae.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return Ie(e),()=>Ie([])},[Ae,Ie]);let Be=(0,V.useMemo)(()=>{let t=Bp(L.error||!tm(L)?e.level===`effort`?`effort`:`note`:L.target,`find`);return yQ.filter(e=>t.includes(e.id))},[L,e.level]),Ve=(0,V.useCallback)(e=>{let t=WZ(_,e);t===_?C(e):v(t)},[_,v,C]),He=(0,V.useCallback)(e=>{let t=we.some(t=>t.toLowerCase()===e.toLowerCase()),n=xN(_,e,!t);v(n);let r=Y(n);!r.error&&tm(r)&&Ve(r.groupBy?.[0]??``)},[we,_,v,Ve]);(0,V.useEffect)(()=>(ze?.({query:_,onQueryChange:v,groupDims:we,onToggleGroupDim:He,availableGroupDims:Be,settings:b,onLayoutChange:x,onToggleField:S,level:e.level}),()=>ze?.(null)),[_,v,we,He,Be,ze,b,x,S,e.level]);let Ue=`activeL3Id`in Re&&typeof Re.activeL3Id==`string`?Re.activeL3Id:null,We=(0,V.useRef)(null);(0,V.useEffect)(()=>{let e=Ue;if(!e||We.current===e||document.getElementById(e))return;let t=Ae.find(t=>t.id===e);if(!t)return;We.current=e;let n=t.entries[t.entries.length-1],r=n?w.findIndex(e=>e.id===n.id):-1;Ne(r>=0?r+1:w.length)},[Ue,Ae,w,Ne]),(0,V.useEffect)(()=>{let e=We.current;!e||!document.getElementById(e)||(We.current=null,Le(e))},[Pe,Le]);let Ge=aL(104),Ke=L.error&&_!==e.defaultWql?L.error:null,qe=y??Ke,Je=(0,V.useMemo)(()=>{let e=[];if(!L.error&&L.advisories?.length&&e.push({id:`edit-query`,label:`Edit query`,apply:()=>cZ(_,be,v)}),!L.error&&L.window){let t=L.window,n=t.kind===`relative`?`last ${t.size}${t.unit}`:`from ${t.start}${t.end?` to ${t.end}`:``}`;e.push({id:`remove-window`,label:`Remove time window (${n})`,apply:()=>v(HZ(_))})}let t=L.error?[]:L.filters.filter(e=>e.key!==`source`);return t.length>0&&e.push({id:`clear-filters`,label:t.length===1?`Clear filter`:`Clear filters (${t.length})`,apply:()=>v(UZ(_))}),e},[L,_,v,be]),Ye=(0,H.jsxs)(`div`,{className:`px-6 py-16 text-center text-muted-foreground flex flex-col items-center justify-center gap-3`,"data-testid":`stream-empty-state`,children:[(0,H.jsx)(`p`,{className:`text-sm font-medium`,children:e.emptyMessage??(L.window?`No entries found within the selected time window.`:`No entries match your search.`)}),Je.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2 mt-1`,children:Je.map(e=>(0,H.jsx)(W,{variant:`outline`,size:`sm`,onClick:e.apply,className:`text-xs`,children:e.label},e.id))})]}),Xe=!!L.error&&w.length>0;return s===`preparing`?(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`stream-preparing`,role:`status`,"aria-busy":`true`,children:[ie,ce,(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-4 p-6`,children:[(0,H.jsxs)(`div`,{className:`w-full max-w-2xl space-y-3`,"aria-hidden":`true`,children:[(0,H.jsx)(`div`,{className:`h-4 w-2/3 animate-pulse rounded bg-muted`}),(0,H.jsx)(`div`,{className:`h-4 w-1/2 animate-pulse rounded bg-muted`}),(0,H.jsx)(`div`,{className:`h-4 w-3/4 animate-pulse rounded bg-muted`})]}),(0,H.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:`Loading library…`})]})]}):(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`queriable-stream-view`,children:[ie,ce,(0,H.jsx)($I,{className:`max-lg:hidden`,actions:(0,H.jsxs)(nR,{primary:e.route===`/efforts`?(0,H.jsxs)(W,{size:`sm`,onClick:()=>a(cj(`new`,void 0,{mode:`create`})),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`efforts-catalog-create-btn`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New`})]}):te?(0,H.jsxs)(W,{size:`sm`,onClick:()=>oe(!0),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`notebooks-create-button`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New Notebook`})]}):void 0,label:`Stream actions`,children:[te&&(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>re(!0),"data-testid":`manage-catalogs-button`,className:`h-9 gap-1.5 px-2.5 text-xs`,children:[(0,H.jsx)(wt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Manage Notebooks`})]}),t]}),queryBar:(0,H.jsx)(lZ,{query:_,onQueryChange:v,scopeOptions:e.scopeOptions,execute:be,defaultQuery:e.defaultWql,route:e.route})}),(0,H.jsx)(`div`,{className:`px-4 pt-2 sm:px-6 lg:px-8`,"data-testid":`stream-query-status-row`,children:(0,H.jsx)(CQ,{error:qe,target:L.error?null:tm(L)?L.target:L.family,matched:w.length,total:Math.max(E?.selected??0,w.length),loading:M,applied:De,ignored:Oe,advisories:L.error?[]:L.advisories??[],groupDims:we,groupingSource:Te})}),e.scopeOptions.length===0&&(0,H.jsx)(`p`,{"data-testid":`route-wql-empty-options`,className:`px-4 pt-3 text-xs text-muted-foreground sm:px-6 lg:px-8`,children:`No source options are set for this route — pick a source by editing the query.`}),e.seedNotice&&c&&!l&&(0,H.jsx)(`div`,{className:`px-4 pt-3 sm:px-6 lg:px-8`,"data-testid":`seed-library-notice`,children:(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex flex-col sm:flex-row sm:items-center gap-3`,children:[(0,H.jsxs)(`div`,{className:`flex-1 space-y-1`,children:[(0,H.jsxs)(`p`,{className:`text-sm font-medium text-foreground flex items-center gap-2`,children:[(0,H.jsx)(ot,{className:`size-4 text-primary`}),`Only the core seed is imported`]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:`The content for this page comes from community libraries, which are not imported yet. Sync now to import the community library — or open Sync settings to add more sources (mirrors, your own libraries).`}),p&&(0,H.jsxs)(`div`,{className:`space-y-1.5 pt-1`,"data-testid":`seed-library-notice-progress`,children:[(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-xs text-muted-foreground`,children:SQ(p)}),p.phase!==`checking`&&p.phase!==`finished`?(0,H.jsx)(sZ,{value:p.completedChunks,max:p.totalChunks,label:`Community library import progress`,className:`max-w-sm`}):d?(0,H.jsx)(`progress`,{"aria-label":`Checking the community library`,className:`h-2 max-w-sm w-full`}):null]}),(h??(p?.phase===`finished`?p.error:null))&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`seed-library-notice-error`,children:h??(p?.phase===`finished`?p.error:null)})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,H.jsxs)(W,{size:`sm`,onClick:()=>void Ce(),disabled:d,"data-testid":`seed-library-notice-sync`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${d?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:d?`Syncing…`:`Sync now`})]}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>a(Q.settingsSync),"data-testid":`seed-library-notice-settings`,className:`gap-2`,children:[(0,H.jsx)(wt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Sync settings`})]})]})]})}),I&&ee&&(0,aS.createPortal)((0,H.jsx)(lZ,{query:_,onQueryChange:v,scopeOptions:e.scopeOptions,execute:be,defaultQuery:e.defaultWql,route:e.route,compact:!0}),ee),qe&&(0,H.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-query-error`,children:[(0,H.jsx)(Ze,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,H.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,H.jsx)(`p`,{className:`font-bold`,children:`Query error`}),(0,H.jsx)(`p`,{className:`mt-1 font-mono text-[11px] opacity-90`,children:qe})]})]}),P&&(0,H.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-action-error`,children:[(0,H.jsx)(Ze,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,H.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,H.jsx)(`p`,{className:`font-bold`,children:`Action failed`}),(0,H.jsx)(`p`,{className:`mt-1 text-[11px] opacity-90`,children:P})]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>F(null),className:`text-[11px] font-bold uppercase tracking-wider hover:opacity-80`,"data-testid":`stream-action-error-dismiss`,children:`Dismiss`})]}),de&&(0,H.jsx)(`div`,{className:`border-b border-border/60 bg-card/20 px-6 py-4`,"data-testid":`collection-readme-note`,children:pe.map((e,t)=>e.kind===`markdown`?(0,H.jsx)(dq,{prose:e.text},t):(0,H.jsx)(_Q,{query:e.query,heading:e.heading,onAddToToday:_e,onRunStart:ve},t))}),me?null:b.layout===`rows`?(0,H.jsx)(`div`,{className:Xe?`flex-1 opacity-50 transition-opacity`:`flex-1`,children:(0,H.jsx)(tQ,{entries:w,level:e.level,visibleFieldIds:b.visibleFields,stickyHeaderTop:Ge,emptyMessage:e.emptyMessage??`No matching records found.`})}):b.layout===`feed`?Pe.length>0?(0,H.jsx)(sQ,{groups:Pe,batch:je,stickyOffset:Ge,onRunEntry:ve,onSendToPlayground:ye}):M&&w.length===0?(0,H.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):w.length===0&&!M?Ye:null:(0,H.jsx)(`div`,{className:Xe?`flex-1 divide-y divide-border/60 opacity-50 transition-opacity`:`flex-1 divide-y divide-border/60`,children:Pe.length>0?(0,H.jsxs)(`div`,{className:`divide-y divide-border/40`,"data-testid":`stream-dated-content`,children:[Pe.map(e=>{let t=Fe.get(e.id)??e.entries.length;return e.key===`shelf`?(0,H.jsxs)(`div`,{id:e.id,className:`border-b border-border/60`,"data-testid":`stream-shelf`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>j(e=>!e),className:`w-full flex items-center justify-between px-6 py-2.5 bg-muted/20 hover:bg-muted/40 transition-colors text-left`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[A?(0,H.jsx)(un,{className:`size-3.5 text-muted-foreground`}):(0,H.jsx)(Vn,{className:`size-3.5 text-muted-foreground`}),(0,H.jsx)(Rss,{className:`size-3.5 text-amber-500`}),(0,H.jsx)(`span`,{className:`text-xs font-bold text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 bg-muted px-1.5 py-0.5 rounded-full`,children:t})]})}),A&&(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:e.entries.map(e=>(0,H.jsx)(QZ,{entry:e,visibleFieldIds:b.visibleFields,onAddToToday:_e,onRunStart:ve},e.id))})]},e.id):(0,H.jsxs)(`div`,{id:e.id,className:`group/date`,"data-testid":`date-group-${e.key}`,children:[(0,H.jsx)(oL,{top:Ge,icon:(0,H.jsx)(qt,{className:`size-3.5 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,H.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${t} ${t===1?`entry`:`entries`}`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(t=>(0,H.jsx)(QZ,{entry:t,visibleFieldIds:b.visibleFields,tone:e.isToday?`primary`:`secondary`,onAddToToday:_e,onRunStart:ve},t.id))})]},e.id)}),(0,H.jsx)(bQ,{batch:je})]}):M&&w.length===0?(0,H.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):w.length===0&&!M?Ye:null})]})}function TQ({pageRoute:e,quests:t,challengeSectionMap:n,onScrollToSection:r}){let{quests:i,stepsComplete:a,totalSteps:o,isComplete:s}=_H(e,t),[c,l]=(0,V.useState)(!1),u=(0,V.useRef)(null),d=(0,V.useRef)(null),f=(0,V.useRef)(null);if(o===0)return null;let p=e=>{let t=n.get(e);t&&r?.(t),l(!1)};(0,V.useEffect)(()=>{if(!c)return;let e=e=>{e.key===`Escape`&&(l(!1),u.current?.focus())},t=e=>{let t=e.relatedTarget,n=u.current?.parentElement;n&&t&&!n.contains(t)&&l(!1)},n=e=>{let t=u.current?.parentElement;t&&!t.contains(e.target)&&l(!1)};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,n),document.addEventListener(`touchstart`,n),d.current?.addEventListener(`focusout`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,n),document.removeEventListener(`touchstart`,n),d.current?.removeEventListener(`focusout`,t)}},[c]),(0,V.useEffect)(()=>()=>{f.current&&=(window.clearTimeout(f.current),null)},[]);let m=()=>{f.current&&=(window.clearTimeout(f.current),null)},h=()=>{m(),f.current=window.setTimeout(()=>l(!1),150)};return(0,H.jsxs)(`div`,{className:`relative py-1.5 shrink-0`,onPointerEnter:e=>{e.pointerType===`mouse`&&(m(),l(!0))},onPointerLeave:e=>{e.pointerType===`mouse`&&h()},children:[(0,H.jsxs)(`button`,{ref:u,type:`button`,"aria-haspopup":`menu`,"aria-expanded":c,"aria-label":`${a} of ${o} challenges complete`,title:`${a} of ${o} challenges complete`,onClick:()=>l(!0),className:`flex items-center gap-1.5 cursor-pointer focus:outline-none select-none text-left rounded-full border border-border/70 bg-background px-3 py-1 hover:bg-muted/40 hover:border-border transition-colors shadow-sm`,children:[s?(0,H.jsx)(Zn,{className:`size-4 text-emerald-500`}):(0,H.jsx)(vn,{className:`size-4 text-muted-foreground`}),(0,H.jsxs)(`span`,{className:U(`text-[10px] font-black uppercase tracking-wider`,s?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`),children:[a,`/`,o]})]}),c&&(0,H.jsxs)(`div`,{ref:d,role:`menu`,"aria-orientation":`vertical`,className:`absolute left-0 top-full mt-1.5 w-64 rounded-xl border border-border bg-popover text-popover-foreground shadow-2xl p-3 z-50 origin-top-left before:content-[''] before:absolute before:-top-1.5 before:left-0 before:right-0 before:h-1.5 before:bg-transparent`,children:[(0,H.jsxs)(`div`,{className:`mb-2.5 pb-2 border-b border-border/60 flex items-center justify-between gap-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h5`,{className:`text-[10px] font-black uppercase tracking-widest text-foreground`,children:`Syntax Challenges`}),(0,H.jsx)(`p`,{className:`text-[9px] text-muted-foreground mt-0.5`,children:`Click a challenge to jump to its section.`})]}),(0,H.jsxs)(`span`,{className:`text-[9px] font-black uppercase tracking-wider text-muted-foreground tabular-nums`,children:[a,`/`,o]})]}),(0,H.jsx)(`div`,{className:`flex flex-col gap-1`,children:i.map(e=>{let t=n.get(e.id);return(0,H.jsx)(Oq,{quest:e,onClick:t?()=>p(e.id):void 0,disabled:!t,compact:!0,className:`border-0 bg-transparent hover:bg-muted/40`},e.id)})})]})]})}function EQ(e){return(0,H.jsx)(DQ,{...e},e.entry.id)}function DQ({entry:e,onChange:t,registerRun:n,...r}){let[i,a]=(0,V.useState)({blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}),[o,s]=(0,V.useState)(null),c=(0,V.useRef)(i.sourceRevision),l=(0,V.useRef)({rawContent:e.rawContent,...i}),u=(0,V.useCallback)(e=>{c.current=e.sourceRevision;let t=l.current,n=t.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));a(t=>({blocks:n?e.blocks:t.blocks,sourceRevision:e.sourceRevision}))},[]),d=(0,V.useCallback)(async t=>{let n=await Nj.saveNote({noteId:e.id,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:c.current}),r={rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0};return u(r),r},[e.id,u]),f=RJ({onSave:async e=>{await d(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])}),p=(0,V.useCallback)(e=>{let t=l.current.rawContent!==e.rawContent||JSON.stringify(Object.values(l.current.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));l.current=e,t&&f.onChange(e)},[f.onChange]);return(0,V.useEffect)(()=>(n?.(async(t,n)=>{await f.flush();let r=l.current,i=await hF({noteId:e.id,rawContent:r.rawContent,blocks:r.blocks,expectedSourceRevision:c.current},t,n);return u({rawContent:i.note.rawContent,blocks:i.note.blocks,sourceRevision:i.note.sourceRevision}),i}),()=>n?.(null)),[e.id,n,f.flush,u]),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(sK,{...r,noteId:e.id,value:o??e.rawContent,noteBlocks:i.blocks,sourceRevision:i.sourceRevision,onIdentityChange:p,onSaved:u,beforeRun:async()=>(await f.flush(),c.current),onSaveRequest:f.flush,onChange:e=>{s(null),t(e)},onBlur:f.onBlur,onCursorPositionChange:f.onLineChange,onCommitChange:f.flush}),f.error?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,f.error instanceof Error?f.error.message:String(f.error),` Your draft is kept.`]}):null,(0,H.jsx)(qP,{noteId:e.id,blocks:i.blocks,sourceRevision:i.sourceRevision,onRevert:async e=>{await f.flush();let n=KP({...l.current,sourceRevision:c.current},e),r=await d(n);l.current=r,s(n.rawContent),t(n.rawContent)}})]})}var OQ=new ID;function kQ({journalDate:e,theme:t,onViewCreated:n}){let[r,i]=(0,V.useState)(null),[a,o]=Ct(),s=Sn(),[c,l]=(0,V.useState)(!1),[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(null),[m,h]=(0,V.useState)(null),[g,_]=(0,V.useState)(null),v=(0,V.useRef)(null),y=(0,V.useRef)(null),b=(0,V.useRef)(new Map),[x,S]=(0,V.useState)(null),w=(0,V.useCallback)(async()=>{let e=v.current;if(!e||!m)throw Error(`The pending workout is unavailable.`);return e.captured?(y.current=e.captured,e.captured.block):(y.current||=e.snapshot?await hF(e.snapshot,e.block,m,e.origin):await gF(e.noteId,e.block,m,e.origin),y.current.block)},[m]),[T,E]=(0,V.useState)({}),D=(0,V.useCallback)((e,t)=>{E(n=>n[e]===t?n:{...n,[e]:t})},[]),O=(0,V.useRef)(new Map),k=(0,V.useRef)(null),[A,j]=(0,V.useState)(null),M=(0,V.useCallback)((e,t)=>{O.current.set(e,t),k.current||(k.current=t,j(t),n?.(t))},[n]),N=a.get(`note`);(0,V.useEffect)(()=>{if(!N||!r)return;let e=document.getElementById(`note-${N}`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},[N,r]);let P=a.toString();(0,V.useEffect)(()=>{let e=new URLSearchParams(P).get(`autoStart`);if(!e)return;let t=VJ.get(e);t&&(VJ.delete(e),v.current=t,y.current=null,p(t.block),h(e),_(t.noteId),d(!0)),o(e=>(e.delete(`autoStart`),e),{replace:!0})},[P,o]);let F=(0,V.useCallback)((e,t)=>{i(n=>n?.map(n=>n.id===e?{...n,rawContent:t}:n)??n)},[]),I=(0,V.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=y.current;if(!a)return Promise.reject(Error(`The saved run pin is unavailable.`));let o=a.session.id,s=O.current.get(a.session.noteId);if(s&&!s.state.doc.toString().includes(GT(o))){let e=KT(s.state,a.session.blockId,o);e&&s.dispatch({changes:e})}return wV.record({blockId:a.session.blockId,noteId:a.session.noteId,resultId:o,data:t,createdAt:t.endTime})},[]);(0,V.useEffect)(()=>{let t=!1;return Kj.listByDate(e).then(e=>{t||i(e)}).catch(()=>{t||i([])}),()=>{t=!0}},[e]);let ee=/^\d{4}-\d{2}-\d{2}$/.test(e),te=(0,V.useMemo)(()=>{if(!ee)return null;let[t,n,r]=e.split(`-`).map(Number);return{prev:Bj(new Date(t,n-1,r-1)),next:Bj(new Date(t,n-1,r+1))}},[e,ee]),{setL3Items:ne}=hA(),[re,ie]=(0,V.useState)({}),ae=r?.map(e=>e.id).join(`|`)??``,oe=(0,V.useMemo)(()=>ae?ae.split(`|`):[],[ae]);(0,V.useEffect)(()=>{if(oe.length===0)return;let e=!1;for(let t of oe)X.getSessionsForNote(t).then(n=>{e||ie(e=>({...e,[t]:n}))}).catch(()=>{});return()=>{e=!0}},[oe]),(0,V.useEffect)(()=>xV(e=>{X.getSessionsForNote(e.noteId).then(t=>{ie(n=>({...n,[e.noteId]:t}))}).catch(()=>{})}),[]);let se=r!==null&&r.length===1?r[0]:null,ce=se?re[se.id]:void 0,L=(0,V.useCallback)(async(t,n)=>{try{let r=b.current.get(t);if(!r)throw Error(`The saved note editor is unavailable.`);let i=C(),a=await r(n,i);VJ.set(i,{noteId:t,block:a.block,captured:a,returnTo:GA(e)}),s(QA(i))}catch(e){S(e instanceof Error?e.message:String(e))}},[e,s]),le=(0,V.useCallback)(e=>{se&&L(se.id,e)},[se,L]);WJ({content:se?.rawContent??``,scriptBlocks:se?T[se.id]??[]:[],onStartWorkout:le,results:ce});let ue=(0,V.useCallback)(e=>t=>{L(e,t)},[L]),R=(0,V.useMemo)(()=>{if(!r||r.length<=1)return[];let e=[];for(let t of r){let n=t.title||`Untitled note`,r=UJ(Wz(t.rawContent),T[t.id]??[],ue(t.id),re[t.id]);for(let i of r)e.push(...Gz([{...i,id:`note-${t.id}:${i.id}`,label:`${n} · ${i.label}`}]))}return e},[r,T,re,ue]),de=(0,V.useRef)(!1);return(0,V.useEffect)(()=>{if(R.length!==0)return de.current=!0,ne(R),()=>{de.current&&(de.current=!1,ne([]))}},[R,ne]),r?N?(0,H.jsx)(_n,{to:qA(N),replace:!0}):(0,H.jsxs)(TF,{notePersistence:Nj,provider:OQ,children:[(0,H.jsx)(fL,{title:e,subtitle:`${r.length} ${r.length===1?`note`:`notes`}`,actions:(0,H.jsx)(nR,{primary:(0,H.jsxs)(W,{type:`button`,onClick:()=>l(!0),children:[(0,H.jsx)(Kt,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`New note`]})}),editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-8 px-4 py-6 sm:px-6`,children:[x&&(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,x,` Your draft is kept.`]}),(0,H.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,H.jsx)(`button`,{type:`button`,onClick:()=>Uz()?s(-1):s(`/journal`),className:`rounded-pill border border-border px-2 py-0.5 hover:bg-accent hover:text-foreground transition-colors`,children:`‹ Journal`}),te&&(0,H.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,H.jsxs)(Wn,{to:GA(te.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:[`‹ `,te.prev]}),(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:e}),(0,H.jsxs)(Wn,{to:GA(te.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:[te.next,` ›`]})]})]}),r.length>1&&(0,H.jsx)(`nav`,{"aria-label":`Notes on this date`,className:`flex flex-wrap gap-2`,children:r.map(e=>(0,H.jsx)(Wn,{to:qA(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,H.jsxs)(`div`,{className:`flex flex-col items-start gap-3 rounded-lg border border-dashed border-border p-6`,children:[(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Notes on this date yet.`}),(0,H.jsxs)(W,{type:`button`,size:`lg`,onClick:()=>l(!0),children:[(0,H.jsx)(Kt,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Create a note`]})]}):r.length===1?(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,H.jsx)(Wn,{to:qA(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,H.jsx)(EQ,{entry:r[0],registerRun:e=>{e?b.current.set(r[0].id,e):b.current.delete(r[0].id)},onChange:e=>F(r[0].id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>D(r[0].id,e),onCompleteWorkout:(e,t,n,i)=>I(e,t,n,i,r[0].id),onViewCreated:e=>M(r[0].id,e)},r[0].id)]}):(0,H.jsx)(`div`,{className:`space-y-6`,children:r.map((e,n)=>(0,H.jsxs)(`div`,{id:`note-${e.id}`,className:`rounded-lg border border-border/60 p-4 space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,H.jsx)(Wn,{to:qA(e.id),className:`text-sm font-semibold hover:underline text-foreground`,children:e.title||`Note ${n+1}`})}),(0,H.jsx)(EQ,{entry:e,registerRun:t=>{t?b.current.set(e.id,t):b.current.delete(e.id)},onChange:t=>F(e.id,t),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:t=>D(e.id,t),onCompleteWorkout:(t,n,r,i)=>I(t,n,r,i,e.id),onViewCreated:t=>M(e.id,t)})]},e.id))})]})}),(0,H.jsx)(xz,{open:c,onOpenChange:l,defaultDate:e,onCreated:t=>{Kj.listByDate(e).then(i).catch(()=>{}),s(qA(t.id))}}),u&&f&&(0,H.jsx)(BG,{block:f,prepareRun:w,onClose:()=>{d(!1),h(null),_(null)},onCompleteWorkout:(e,t)=>I(e,t,m??void 0,void 0),autoStart:!0})]}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function AQ({identity:e}){let t=Sn();return(0,V.useEffect)(()=>{let n=!1;return Kj.resolve(e).then(e=>{!n&&e.journalDate&&t(qA(e.id),{replace:!0})}).catch(()=>{n||t(`/journal`,{replace:!0})}),()=>{n=!0}},[e,t]),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function jQ(e){let t=window.location.pathname,n=TR(t);return n.kind===`date`?(0,H.jsx)(kQ,{journalDate:n.journalDate,theme:e.theme,onViewCreated:e.onViewCreated}):n.kind===`note`?(0,H.jsx)(_n,{to:qA(n.noteId),replace:!0}):n.kind===`uuid-alias`?(0,H.jsx)(AQ,{identity:n.noteId}):n.kind===`slug-alias`?(0,H.jsx)(AQ,{identity:n.slug}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Journal route not found.`})}var MQ=()=>(0,H.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,H.jsx)(`div`,{className:`mt-0.5 flex-shrink-0 text-primary`,children:(0,H.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,"aria-hidden":`true`,children:[(0,H.jsx)(`circle`,{cx:`9`,cy:`9`,r:`8`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,H.jsx)(`path`,{d:`M9 5v4.5M9 11.5v1`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}),(0,H.jsxs)(`div`,{className:`flex-1 text-sm leading-relaxed text-muted-foreground`,children:[(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Ready to try it?`}),` `,`Press the`,` `,(0,H.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,H.jsx)(`div`,{className:`pointer-events-none absolute -bottom-4 right-8 text-primary/50`,"aria-hidden":`true`,children:(0,H.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 20 20`,fill:`none`,children:[(0,H.jsx)(`path`,{d:`M3 3 L17 3 L17 17`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,H.jsx)(`path`,{d:`M11 11 L17 17 L23 11`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]});function NQ({config:e,onAction:t}){return!e.headline||!e.subtitle||e.pillars.length===0?(0,H.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,H.jsx)(`code`,{children:`attention`}),` widget config.`]}):(0,H.jsxs)(`section`,{className:`p-8`,children:[(0,H.jsx)(`p`,{className:`mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:`Playground`}),(0,H.jsx)(`h1`,{className:`text-3xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-100 sm:text-4xl`,children:e.headline}),(0,H.jsx)(`p`,{className:`mt-4 max-w-3xl text-base leading-7 text-zinc-600 dark:text-zinc-300`,children:e.subtitle}),(0,H.jsx)(`div`,{className:`mt-7 grid gap-3 md:grid-cols-3`,children:e.pillars.map(e=>(0,H.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,H.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,H.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.label}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]},e.label))}),(0,H.jsx)(`div`,{className:`mt-7 flex flex-wrap gap-3`,children:e.actions.map(e=>(0,H.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,H.jsx)(h,{className:`size-4`,"aria-hidden":`true`})]},`${e.action}-${e.label}`))})]})}function PQ({config:e,isDarkMode:t,onRun:n}){let r=(0,V.useRef)(null),i=(0,V.useRef)(null),a=(0,V.useMemo)(()=>e.lines.map(e=>e.code).join(`
160
- `),[e.lines]);return(0,V.useEffect)(()=>{if(r.current)return i.current?.destroy(),i.current=new Er({state:ri.create({doc:a,extensions:[Qr(),hi(),ri.readOnly.of(!1),Er.theme({"&":{fontSize:`13px`,borderRadius:`12px`,border:`1px solid var(--cm-border)`},".cm-scroller":{fontFamily:`JetBrains Mono, ui-monospace, SFMono-Regular, monospace`,lineHeight:`1.6`,minHeight:`180px`},".cm-content":{padding:`14px 0`},".cm-gutters":{backgroundColor:`transparent`,borderRight:`1px solid var(--cm-border)`}}),Er.theme({"&":{"--cm-border":t?`rgba(82, 82, 91, 0.7)`:`rgba(212, 212, 216, 0.9)`}},{dark:t}),...t?[ni]:[]]}),parent:r.current}),()=>{i.current?.destroy(),i.current=null}},[t,a]),e.lines.length===0?(0,H.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,H.jsx)(`code`,{children:`code-example`}),` widget config.`]}):(0,H.jsxs)(`section`,{className:`p-5`,children:[(0,H.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-zinc-900 dark:text-zinc-100`,children:`Code example`}),(0,H.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,H.jsx)(Ht,{className:`size-3.5`,"aria-hidden":`true`}),e.cta]})]}),(0,H.jsx)(`div`,{ref:r}),(0,H.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,H.jsxs)(`li`,{className:`flex gap-2`,children:[(0,H.jsx)(`span`,{className:`mt-1 inline-block size-1.5 rounded-full bg-zinc-400`,"aria-hidden":`true`}),(0,H.jsxs)(`span`,{children:[(0,H.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 FQ({config:e,onOpenDocs:t}){return!e.category||!e.title||!e.docsPath?(0,H.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,H.jsx)(`code`,{children:`syntax-group`}),` widget config.`]}):(0,H.jsxs)(`article`,{className:`p-5`,children:[(0,H.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:e.category}),(0,H.jsxs)(`h3`,{className:`mt-2 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[(0,H.jsx)(`span`,{className:`mr-2`,"aria-hidden":`true`,children:e.icon}),e.title]}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]}),(0,H.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,H.jsx)(k,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,H.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,H.jsx)(`code`,{children:e.example})})]})}function IQ(e){return({config:t})=>(0,H.jsx)(NQ,{config:t,onAction:e})}function LQ(e,t){return({config:n})=>(0,H.jsx)(PQ,{config:n,isDarkMode:e,onRun:t})}function RQ(e){return({config:t})=>(0,H.jsx)(FQ,{config:t,onOpenDocs:e})}var zQ=[`visitedLanding`,`editedNote`,`ranWorkout`,`loggedEffort`,`openedReview`],BQ=`wodwiki.onboarding.v1`,VQ={visitedLanding:!1,editedNote:!1,ranWorkout:!1,loggedEffort:!1,openedReview:!1};function HQ(){if(typeof window>`u`||!window.localStorage)return{...VQ};try{let e=window.localStorage.getItem(BQ);if(!e)return{...VQ};let t=JSON.parse(e),n={...VQ};for(let e of zQ)n[e]=t[e]===!0;return n}catch{return{...VQ}}}function UQ(e){if(!(typeof window>`u`||!window.localStorage))try{window.localStorage.setItem(BQ,JSON.stringify(e))}catch{}}function WQ(){let[e,t]=(0,V.useState)(HQ);(0,V.useEffect)(()=>{let e=e=>{e.key===BQ&&t(HQ())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let n=(0,V.useCallback)(e=>{t(t=>{if(t[e])return t;let n={...t,[e]:!0};return UQ(n),n})},[]),r=zQ.length,i=zQ.reduce((t,n)=>t+ +!!e[n],0);return{progress:e,stepsComplete:i,totalSteps:r,isComplete:i===r,mark:n}}function GQ(){let{mark:e}=WQ();return{onEditNote:(0,V.useCallback)(()=>{e(`editedNote`)},[e]),onRunWorkout:(0,V.useCallback)(()=>{e(`ranWorkout`)},[e]),onLogEffort:(0,V.useCallback)(()=>{e(`loggedEffort`)},[e])}}var KQ=new ID;function qQ({theme:e,onViewCreated:t,onScrollToSection:n,onSearch:r}){let{id:i}=zn(),a=i??`playground`,o=az(`playground`,a),s=(0,V.useMemo)(()=>i?fy(i):`Playground`,[i]),c=Sn(),l=!i||i===`playground`,{content:u,loading:d,entryId:f,noteBlocks:p,sourceRevision:m,onIdentityChange:h,onSaved:g,error:_,onChange:v,onLineChange:y,onBlur:b,flush:x,committedSourceRevision:S,resetToOriginal:w}=BJ({category:`playground`,name:a,mdContent:gY.content,seedOnMount:l}),T=f??o,{onEditNote:E,onRunWorkout:D,onLogEffort:O}=GQ(),k=(0,V.useCallback)(e=>{E(),v(e)},[E,v]),[A,j]=(0,V.useState)([]),M=(0,V.useCallback)(()=>{X.getSessionsForNote(T).then(e=>j(e.filter(e=>e.completed))).catch(()=>{})},[T]);(0,V.useEffect)(()=>{M()},[M]);let N=(0,V.useRef)(!1),P=(0,V.useRef)(null),F=(0,V.useCallback)(e=>{if(P.current=e,t?.(e),N.current)return;N.current=!0;let n=Math.min(gY.cursorOffset,e.state.doc.length);e.dispatch({selection:gi.cursor(n)})},[t]),I=(0,V.useCallback)(async e=>{try{await x();let t=C(),n=await gF(T,e,t,`playground`);g({rawContent:n.note.rawContent,blocks:n.note.blocks,sourceRevision:n.note.sourceRevision}),VJ.set(t,{block:n.block,noteId:n.session.noteId,captured:n,origin:`playground`,returnTo:`/playground/${encodeURIComponent(a)}`}),D(),c(QA(t))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[T,a,c,D,x,g]),ee=(0,V.useCallback)(async e=>{try{O();let t=await OJ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content}),n=wJ(new Date);Z({title:`Added to journal`,description:t.journalDate===n?`Added to today's journal`:`Added to ${t.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(t.journalDate??n)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[s,a,c,O]),[te,ne]=(0,V.useState)(null),[re,ie]=(0,V.useState)(!1),ae=(0,V.useCallback)(async e=>{let t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`;try{await oH(T,t),Z({title:`Moved to journal`,description:`This playground now lives on ${t}.`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(t)),children:`Open`})}),c(qA(T))}catch{Z({title:`Error`,description:`Could not move to journal`,variant:`destructive`})}},[T,c]),oe=(0,V.useCallback)(async(e,t)=>{let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await OJ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content,date:t}),c(KA(n)),Z({title:`Scheduled`,description:`Added to journal for ${n}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(n)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[s,a,c]),[se,ce]=(0,V.useState)([]),L=WJ({content:u,scriptBlocks:se,onStartWorkout:I,results:A}),le=(0,V.useMemo)(()=>YJ({id:T,type:`playground`}),[T]),ue=tY({noteId:T,stamps:le.stamps}),[R,de]=(0,V.useState)(null);(0,V.useEffect)(()=>{let e=!1;return X.getNote(T).then(t=>{if(e||!t?.sourceId)return;let n=XJ(t.sourceId);n&&de({noteId:T,link:n})}).catch(()=>{}),()=>{e=!0}},[T]);let fe=(0,H.jsxs)(nR,{label:`Playground actions`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>ie(!0),title:`Move this playground to a journal date`,className:`inline-flex items-center gap-1 rounded-pill border border-border bg-card px-2.5 py-1 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,children:[(0,H.jsx)(Ut,{className:`size-3.5`,"aria-hidden":`true`}),`Move to journal`]}),(0,H.jsx)(_Y,{mode:`playground`,currentWorkout:{name:s,content:u},index:L,onReset:w})]}),pe=rY(`playground`,{onPlay:I,onShare:lY,onAddToToday:ee,onSchedule:ne}),me=(0,V.useCallback)(e=>{if(e===`scroll-to-workout`){let e=L.find(e=>e.type===`time`||e.type===`log`);e&&n?.(e.id)}else e===`open-search`&&r?.()},[L,n,r]),he=(0,V.useCallback)(e=>{let t={id:`code-example-block`,line:0,endLine:e.split(`
161
- `).length,content:e};I(t)},[I]),ge=(0,V.useCallback)(e=>{e.startsWith(`/`)?window.open(e,`_blank`):c(e)},[c]),_e=(0,V.useCallback)((e,t)=>{if(e===`route`&&t.route)c(t.route);else if(e===`start-workout`){let e=se[0];e&&I(e)}else e===`new-note`&&c(`/playground`)},[c,se,I]),ve=(0,V.useMemo)(()=>new Map([[`playground-run-tip`,MQ],[`attention`,IQ(me)],[`code-example`,LQ(e===`dark`,he)],[`syntax-group`,RQ(ge)]]),[me,he,ge,e]);return(0,V.useEffect)(()=>{document.title=`Wod.Wiki - ${s}`},[s]),d?(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(TF,{notePersistence:Nj,provider:KQ,children:(0,H.jsx)(fL,{title:s,actions:fe,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(nY,{data:ue,up:le.up,source:R?.noteId===T?R.link:null}),(0,H.jsx)(sK,{value:u,onChange:k,onCursorPositionChange:y,onBlur:b,noteId:T,noteBlocks:p,sourceRevision:m,onIdentityChange:e=>h({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:g,beforeRun:async()=>(await x(),S()),onSaveRequest:x,onCommitChange:x,commands:pe,enableInlineRuntime:!1,onViewCreated:F,theme:e,showLineNumbers:!1,onBlocksChange:ce,onButtonAction:_e,widgetComponents:ve}),_?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,_ instanceof Error?_.message:String(_),` Your draft is kept.`]}):null,(0,H.jsx)(qP,{noteId:T,blocks:p,sourceRevision:m,onRevert:async e=>{await x();let t=P.current?.state.field(ZC);if(!t)throw Error(`The current note editor is unavailable.`);let n=KP({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:S()},e);h({rawContent:n.rawContent,noteBlocks:n.blocks,sourceRevision:n.sourceRevision}),await x()}})]})})}),te&&(0,H.jsx)(lS,{open:!0,onClose:()=>ne(null),title:`Schedule workout`,children:(0,H.jsx)(LJ,{selectedDate:null,onDateSelect:e=>{oe(te,e),ne(null)}})}),re&&(0,H.jsx)(lS,{open:!0,onClose:()=>ie(!1),title:`Move playground to Journal`,description:`Choose a date. This keeps the workout's existing results and attachments.`,children:(0,H.jsx)(LJ,{selectedDate:null,onDateSelect:e=>{ie(!1),ae(e)}})})]})}function JQ({category:e,name:t,mdContent:n,theme:r,runMode:i,hidePlanningCommands:a,onViewCreated:o}){let s=i?i===`inline`:zz.has(e),c=!Bz.has(e),l=az(e,t),u=Sn(),{content:d,loading:f,entryId:p,noteBlocks:m,sourceRevision:h,onIdentityChange:g,onSaved:_,error:v,onChange:y,onLineChange:b,onBlur:x,flush:S,committedSourceRevision:w}=BJ({category:e,name:t,mdContent:n,seedOnMount:!c}),T=(0,V.useMemo)(()=>c?{label:`${e}-${t}`,path:ZA(e,t)}:null,[e,c,t]),[E,D]=(0,V.useState)(null),O=(0,V.useCallback)(async n=>{let r=C();if(s){try{await S();let e=await hF({noteId:p??l,rawContent:d,blocks:m,expectedSourceRevision:w(),metadata:{title:t},noteType:`playground`},n,r);_({rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision}),VJ.set(r,{block:e.block,noteId:e.session.noteId,captured:e}),u(QA(r))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}return}try{let i=await OJ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content}),a=Object.values(i.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The saved journal workout is unavailable.`);VJ.set(r,{block:{...n,id:a.id},noteId:i.id}),u(JA(i.journalDate??``,r))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[s,l,p,t,e,T,u,d,m,S,w,_]),k=(0,V.useCallback)(async(n,r)=>{let i=VP(r),a;try{a=(await OJ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content,date:r,wrapInWod:!0})).journalDate??``}catch{Z({variant:`destructive`,title:`Could not save workout`,description:`Failed to add "${t}" to ${i}. Please try again.`});return}u(KA(a));let o=KA(a);Z({title:`Added to ${i}`,description:`"${t}" was added to your journal.`,action:(0,H.jsx)(Yk,{altText:`View journal entry`,onClick:()=>u(o),children:`View Note`}),duration:7e3})},[t,e,T,u]),A=rY(`collection-readonly`,{onPlay:O,onShare:lY,onAddToToday:a?void 0:e=>k(e,new Date),onSchedule:a?void 0:D,onOpenInPlayground:e=>oY(e,u)}),[j,M]=(0,V.useState)([]),N=(0,V.useCallback)(()=>{u(qA(l))},[u,l]),P=WJ({content:d,scriptBlocks:j,onStartWorkout:O,onEditNote:c?N:void 0}),F=(0,V.useMemo)(()=>c?YJ({id:l,type:`feed`}):null,[c,l]),I=tY({noteId:l,stamps:F?.stamps??[]}),ee=(0,H.jsx)(nR,{children:(0,H.jsx)(_Y,{mode:`collection-readonly`,currentWorkout:{name:l,content:d},index:P})});return f?(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fL,{title:t,actions:ee,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(nY,{data:I,up:F?.up}),(0,H.jsx)(sK,{value:d,onChange:y,onCursorPositionChange:b,onBlur:x,noteId:l,noteBlocks:m,sourceRevision:h,onIdentityChange:e=>g({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:_,beforeRun:async()=>(await S(),w()),onSaveRequest:S,onCommitChange:S,readonly:!0,enableInlineRuntime:s,commands:A,onViewCreated:o,theme:r,showLineNumbers:!1,onBlocksChange:M}),v?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,v instanceof Error?v.message:String(v),` Your draft is kept.`]}):null]})}),E&&(0,H.jsx)(lS,{open:!0,onClose:()=>D(null),title:`Schedule ${t}`,children:(0,H.jsx)(LJ,{selectedDate:null,onDateSelect:e=>{e&&k(E,e),D(null)}})})]})}var YQ=xe(`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2`,{variants:{variant:{default:`border-transparent bg-primary text-primary-foreground hover:bg-primary/80`,secondary:`border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80`,destructive:`border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80`,outline:`text-foreground`}},defaultVariants:{variant:`default`}}),XQ=V.memo(({className:e,variant:t,...n})=>(0,H.jsx)(`div`,{className:U(YQ({variant:t}),e),...n})),ZQ=(0,V.forwardRef)(function({className:e,multiple:t,...n},r){return(0,H.jsxs)(`span`,{"data-slot":`control`,className:U(`group relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`has-data-[focus]:after:ring-2 has-data-[focus]:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:[(0,H.jsx)(te,{ref:r,multiple:t,...n,className:U(`relative block w-full appearance-none rounded-lg py-[calc(theme(spacing.2.5)-1px)]`,`sm:py-[calc(theme(spacing.1.5)-1px)]`,t?`px-[calc(theme(spacing.3.5)-1px)] sm:px-[calc(theme(spacing.3)-1px)]`:`pr-[calc(theme(spacing.10)-1px)] pl-[calc(theme(spacing.3.5)-1px)] sm:pr-[calc(theme(spacing.9)-1px)] sm:pl-[calc(theme(spacing.3)-1px)]`,`[&_optgroup]:font-semibold`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6 dark:[&>*]:text-white`,`border border-border/60 data-[hover]:border-border dark:border-white/10 dark:data-[hover]:border-white/20`,`bg-transparent dark:bg-white/5 dark:[&>*]:bg-muted`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 data-[disabled]:opacity-100 dark:data-[disabled]:border-white/15 dark:data-[disabled]:bg-white/2.5 dark:data-[hover]:data-[disabled]:border-white/15`,`dark:scheme-dark`,e)}),!t&&(0,H.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2`,children:(0,H.jsxs)(`svg`,{className:`size-5 stroke-muted-foreground group-has-data-[disabled]:stroke-muted-foreground/70 sm:size-4 forced-colors:stroke-[CanvasText]`,viewBox:`0 0 16 16`,"aria-hidden":`true`,fill:`none`,children:[(0,H.jsx)(`path`,{d:`M5.75 10.75L8 13L10.25 10.75`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,H.jsx)(`path`,{d:`M10.25 5.25L8 3L5.75 5.25`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]})}),QQ={effort:`efforts`,equipment:`equipment`},$Q=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`page`,`page_notes`,`note_tags`,`attachments`];async function e$(e){let t=e.kind===`effort`?dc(e.rawContent):void 0,n=e.kind===`equipment`?mc(e.rawContent):void 0,r=t?.effort??n?.equipment,i=[...t?.errors??n?.errors??[]],a=A_(e.rawContent),o=typeof a.id==`string`?a.id.trim():``;if(o||i.push("Frontmatter must declare a stable `id` (the clone flow patches it into the source)"),r&&r.slug!==e.slug&&i.push(`Document slug "${r.slug}" does not match "${e.slug}"`),r&&r.label.trim()!==e.title.trim()&&i.push(`Document label "${r.label}" does not match title "${e.title}"`),i.length>0)throw Error(i.join(`
162
- `));return X.withTransaction([...$Q],async i=>{let a=e.kind===`effort`?await i.getEffort(e.slug):await i.getEquipment(e.slug);if(a?.registrySource===`bundled`)throw Error(`"${e.slug}" is a bundled definition and cannot be saved over — clone it first`);if(a&&a.id!==o)throw Error(`Document id "${o}" does not match record id "${a.id}" — clone instead of re-keying`);let s=a?.ownerNoteId,c=e.noteId??s??`${e.kind}/${e.slug}`;if(s!==void 0&&c!==s)throw Error(`"${e.slug}" is owned by note ${s}; refusing to save against ${c}`);let l=new Date().toISOString();if(e.kind===`effort`){let n={...t.effort,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:QQ.effort,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEffort(n)}else{let t={...n.equipment,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:QQ.equipment,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEquipment(t)}return{id:c,sourceRevision:(await i.saveNoteSource({noteId:c,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r.label,sourceId:QQ[e.kind]},createdAt:Date.now()})).sourceRevision}})}async function t$(e,t){await X.withTransaction([...$Q],async n=>{let r=e===`effort`?await n.getEffort(t):await n.getEquipment(t);if(r?.registrySource!==`user`)throw Error(`"${t}" is not user-owned ${e}`);e===`effort`?await n.deleteEffort(t):await n.deleteEquipment(t);let i=r.ownerNoteId??`${e}/${t}`;await n.getNote(i)&&await n.deleteNote(i)})}function n$(e,t,n){let r=`effort-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=Wa(e,[`id`],r);return o=Wa(o,[`slug`],i),o=Wa(o,[`label`],a),o=Wa(o,[`registrySource`],`user`),o=Wa(o,[`derivation`,`parentSlug`],t),{raw:o,id:r,slug:i,label:a}}function r$(e){let{registry:t,isReady:n,refresh:r}=Vk(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(!0),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(!1),g=u?.registrySource===`user`,_=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`effort/${i.slug}`,c=await X.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??fc(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load effort.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,V.useCallback)(async t=>{if(!e&&!u)return;let{effort:n,errors:i}=dc(t,u??void 0);if(i.length>0)throw Z({title:`Invalid YAML`,description:i.join(`
171
+ `))}}let i=yQ(e,n,t);await Kj.create(i)},[]),_e=r??ge,ve=(0,V.useCallback)(async e=>{F(null);try{await aQ(e,a)}catch(e){F(e instanceof Error?e.message:`Could not start the workout.`)}},[a]),ye=(0,V.useCallback)(async e=>{F(null);try{let t=await Kj.resolve(e.id),{routeId:n}=await gH(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``,{title:e.title});a(WA(n.replace(/^playground\//,``)))}catch(e){F(e instanceof Error?e.message:`Could not create the playground entry.`)}},[a]),be=(0,V.useCallback)(e=>tm(e)?XF.runFind(e):XF.runQuery(e.raw),[]),[xe,Se]=(0,V.useState)(0);(0,V.useEffect)(()=>MV(()=>Se(e=>e+1)),[]),(0,V.useEffect)(()=>{let e=mb().result?.id??-1;return hb(()=>{let t=mb().result?.id??-1;t!==e&&(e=t,Se(e=>e+1))})},[]);let Ce=(0,V.useCallback)(async()=>{f(!0),g(null),m(null);try{let e=await Nk(`community`,{force:!0,onProgress:m});e===`imported`||e===`current`?(u(!0),Se(e=>e+1)):e===`busy`?g(`Another tab is already syncing — wait for it to finish, then try again.`):e===`disabled`&&g(`Seed import is disabled.`)}finally{f(!1)}},[]);(0,V.useEffect)(()=>{if(s===`preparing`)return;if(L.error){N(!1);return}let e=!1,t=setTimeout(()=>{N(!0),D(void 0),he.query(_,t=>{e||D(t)}).then(t=>{e||(T(t),k(xZ(_,L)),eN({pathname:o.pathname,query:_,entries:t}))}).catch(()=>{e||(T([]),eN({pathname:o.pathname,query:_,entries:[]}))}).finally(()=>{e||N(!1)})},MQ);return()=>{e=!0,clearTimeout(t)}},[_,he,L,o.pathname,s,xe]);let we=(0,V.useMemo)(()=>O?.length?O:b.groupBy?[b.groupBy]:[e.level===`effort`?`discipline`:`date`],[O,b.groupBy,e.level]),Te=O?.length?`query`:b.groupBy?`view`:`level`,Ee=(0,V.useMemo)(()=>new Set(L.error||!tm(L)?[]:zp(L.target,`find`)),[L]),De=L.error||rm(L)?0:L.filters.filter(e=>Ee.has(e.key)).length,Oe=(L.error||rm(L)?0:L.filters.length)-De,ke=e.shelfVisible&&!le,Ae=(0,V.useMemo)(()=>CZ(w,we,{shelfVisible:ke}),[w,we,ke]),je=ZZ(w),{visible:Me,growTo:Ne}=je,Pe=(0,V.useMemo)(()=>CZ(Me,we,{shelfVisible:ke}),[Me,we,ke]),Fe=(0,V.useMemo)(()=>new Map(Ae.map(e=>[e.id,e.entries.length])),[Ae]),{setL3Items:Ie,scrollToSection:Le,navState:Re,setStreamControls:ze}=hA();(0,V.useEffect)(()=>{if(Ae.length===0){Ie([]);return}let e=Ae.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return Ie(e),()=>Ie([])},[Ae,Ie]);let Be=(0,V.useMemo)(()=>{let t=Bp(L.error||!tm(L)?e.level===`effort`?`effort`:`note`:L.target,`find`);return AQ.filter(e=>t.includes(e.id))},[L,e.level]),Ve=(0,V.useCallback)(e=>{let t=tQ(_,e);t===_?C(e):v(t)},[_,v,C]),He=(0,V.useCallback)(e=>{let t=we.some(t=>t.toLowerCase()===e.toLowerCase()),n=xN(_,e,!t);v(n);let r=Y(n);!r.error&&tm(r)&&Ve(r.groupBy?.[0]??``)},[we,_,v,Ve]);(0,V.useEffect)(()=>(ze?.({query:_,onQueryChange:v,groupDims:we,onToggleGroupDim:He,availableGroupDims:Be,settings:b,onLayoutChange:x,onToggleField:S,level:e.level}),()=>ze?.(null)),[_,v,we,He,Be,ze,b,x,S,e.level]);let Ue=`activeL3Id`in Re&&typeof Re.activeL3Id==`string`?Re.activeL3Id:null,We=(0,V.useRef)(null);(0,V.useEffect)(()=>{let e=Ue;if(!e||We.current===e||document.getElementById(e))return;let t=Ae.find(t=>t.id===e);if(!t)return;We.current=e;let n=t.entries[t.entries.length-1],r=n?w.findIndex(e=>e.id===n.id):-1;Ne(r>=0?r+1:w.length)},[Ue,Ae,w,Ne]),(0,V.useEffect)(()=>{let e=We.current;!e||!document.getElementById(e)||(We.current=null,Le(e))},[Pe,Le]);let Ge=aL(104),Ke=L.error&&_!==e.defaultWql?L.error:null,qe=y??Ke,Je=(0,V.useMemo)(()=>{let e=[];if(!L.error&&L.advisories?.length&&e.push({id:`edit-query`,label:`Edit query`,apply:()=>yZ(_,be,v)}),!L.error&&L.window){let t=L.window,n=t.kind===`relative`?`last ${t.size}${t.unit}`:`from ${t.start}${t.end?` to ${t.end}`:``}`;e.push({id:`remove-window`,label:`Remove time window (${n})`,apply:()=>v($Z(_))})}let t=L.error?[]:L.filters.filter(e=>e.key!==`source`);return t.length>0&&e.push({id:`clear-filters`,label:t.length===1?`Clear filter`:`Clear filters (${t.length})`,apply:()=>v(eQ(_))}),e},[L,_,v,be]),Ye=(0,H.jsxs)(`div`,{className:`px-6 py-16 text-center text-muted-foreground flex flex-col items-center justify-center gap-3`,"data-testid":`stream-empty-state`,children:[(0,H.jsx)(`p`,{className:`text-sm font-medium`,children:e.emptyMessage??(L.window?`No entries found within the selected time window.`:`No entries match your search.`)}),Je.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2 mt-1`,children:Je.map(e=>(0,H.jsx)(W,{variant:`outline`,size:`sm`,onClick:e.apply,className:`text-xs`,children:e.label},e.id))})]}),Xe=!!L.error&&w.length>0;return s===`preparing`?(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`stream-preparing`,role:`status`,"aria-busy":`true`,children:[ie,ce,(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-4 p-6`,children:[(0,H.jsxs)(`div`,{className:`w-full max-w-2xl space-y-3`,"aria-hidden":`true`,children:[(0,H.jsx)(`div`,{className:`h-4 w-2/3 animate-pulse rounded bg-muted`}),(0,H.jsx)(`div`,{className:`h-4 w-1/2 animate-pulse rounded bg-muted`}),(0,H.jsx)(`div`,{className:`h-4 w-3/4 animate-pulse rounded bg-muted`})]}),(0,H.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:`Loading library…`})]})]}):(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`queriable-stream-view`,children:[ie,ce,(0,H.jsx)($I,{className:`max-lg:hidden`,actions:(0,H.jsxs)(nR,{primary:e.route===`/efforts`?(0,H.jsxs)(W,{size:`sm`,onClick:()=>a(cj(`new`,void 0,{mode:`create`})),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`efforts-catalog-create-btn`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New`})]}):te?(0,H.jsxs)(W,{size:`sm`,onClick:()=>oe(!0),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`notebooks-create-button`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New Notebook`})]}):void 0,label:`Stream actions`,children:[te&&(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>re(!0),"data-testid":`manage-catalogs-button`,className:`h-9 gap-1.5 px-2.5 text-xs`,children:[(0,H.jsx)(wt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Manage Notebooks`})]}),t]}),queryBar:(0,H.jsx)(bZ,{query:_,onQueryChange:v,scopeOptions:e.scopeOptions,execute:be,defaultQuery:e.defaultWql,route:e.route})}),(0,H.jsx)(`div`,{className:`px-4 pt-2 sm:px-6 lg:px-8`,"data-testid":`stream-query-status-row`,children:(0,H.jsx)(PQ,{error:qe,target:L.error?null:tm(L)?L.target:L.family,matched:w.length,total:Math.max(E?.selected??0,w.length),loading:M,applied:De,ignored:Oe,advisories:L.error?[]:L.advisories??[],groupDims:we,groupingSource:Te})}),e.scopeOptions.length===0&&(0,H.jsx)(`p`,{"data-testid":`route-wql-empty-options`,className:`px-4 pt-3 text-xs text-muted-foreground sm:px-6 lg:px-8`,children:`No source options are set for this route — pick a source by editing the query.`}),e.seedNotice&&c&&!l&&(0,H.jsx)(`div`,{className:`px-4 pt-3 sm:px-6 lg:px-8`,"data-testid":`seed-library-notice`,children:(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex flex-col sm:flex-row sm:items-center gap-3`,children:[(0,H.jsxs)(`div`,{className:`flex-1 space-y-1`,children:[(0,H.jsxs)(`p`,{className:`text-sm font-medium text-foreground flex items-center gap-2`,children:[(0,H.jsx)(ot,{className:`size-4 text-primary`}),`Only the core seed is imported`]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:`The content for this page comes from community libraries, which are not imported yet. Sync now to import the community library — or open Sync settings to add more sources (mirrors, your own libraries).`}),p&&(0,H.jsxs)(`div`,{className:`space-y-1.5 pt-1`,"data-testid":`seed-library-notice-progress`,children:[(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-xs text-muted-foreground`,children:NQ(p)}),p.phase!==`checking`&&p.phase!==`finished`?(0,H.jsx)(vZ,{value:p.completedChunks,max:p.totalChunks,label:`Community library import progress`,className:`max-w-sm`}):d?(0,H.jsx)(`progress`,{"aria-label":`Checking the community library`,className:`h-2 max-w-sm w-full`}):null]}),(h??(p?.phase===`finished`?p.error:null))&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`seed-library-notice-error`,children:h??(p?.phase===`finished`?p.error:null)})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,H.jsxs)(W,{size:`sm`,onClick:()=>void Ce(),disabled:d,"data-testid":`seed-library-notice-sync`,className:`gap-2`,children:[(0,H.jsx)(pn,{className:`size-3.5 ${d?`animate-spin`:``}`}),(0,H.jsx)(`span`,{children:d?`Syncing…`:`Sync now`})]}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>a(Q.settingsSync),"data-testid":`seed-library-notice-settings`,className:`gap-2`,children:[(0,H.jsx)(wt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Sync settings`})]})]})]})}),I&&ee&&(0,aS.createPortal)((0,H.jsx)(bZ,{query:_,onQueryChange:v,scopeOptions:e.scopeOptions,execute:be,defaultQuery:e.defaultWql,route:e.route,compact:!0}),ee),qe&&(0,H.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-query-error`,children:[(0,H.jsx)(Ze,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,H.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,H.jsx)(`p`,{className:`font-bold`,children:`Query error`}),(0,H.jsx)(`p`,{className:`mt-1 font-mono text-[11px] opacity-90`,children:qe})]})]}),P&&(0,H.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-action-error`,children:[(0,H.jsx)(Ze,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,H.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,H.jsx)(`p`,{className:`font-bold`,children:`Action failed`}),(0,H.jsx)(`p`,{className:`mt-1 text-[11px] opacity-90`,children:P})]}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>F(null),className:`text-[11px] font-bold uppercase tracking-wider hover:opacity-80`,"data-testid":`stream-action-error-dismiss`,children:`Dismiss`})]}),de&&(0,H.jsx)(`div`,{className:`border-b border-border/60 bg-card/20 px-6 py-4`,"data-testid":`collection-readme-note`,children:pe.map((e,t)=>e.kind===`markdown`?(0,H.jsx)(Sq,{prose:e.text},t):(0,H.jsx)(OQ,{query:e.query,heading:e.heading,onAddToToday:_e,onRunStart:ve},t))}),me?null:b.layout===`rows`?(0,H.jsx)(`div`,{className:Xe?`flex-1 opacity-50 transition-opacity`:`flex-1`,children:(0,H.jsx)(fQ,{entries:w,level:e.level,visibleFieldIds:b.visibleFields,stickyHeaderTop:Ge,emptyMessage:e.emptyMessage??`No matching records found.`})}):b.layout===`feed`?Pe.length>0?(0,H.jsx)(vQ,{groups:Pe,batch:je,stickyOffset:Ge,onRunEntry:ve,onSendToPlayground:ye}):M&&w.length===0?(0,H.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):w.length===0&&!M?Ye:null:(0,H.jsx)(`div`,{className:Xe?`flex-1 divide-y divide-border/60 opacity-50 transition-opacity`:`flex-1 divide-y divide-border/60`,children:Pe.length>0?(0,H.jsxs)(`div`,{className:`divide-y divide-border/40`,"data-testid":`stream-dated-content`,children:[Pe.map(e=>{let t=Fe.get(e.id)??e.entries.length;return e.key===`shelf`?(0,H.jsxs)(`div`,{id:e.id,className:`border-b border-border/60`,"data-testid":`stream-shelf`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>j(e=>!e),className:`w-full flex items-center justify-between px-6 py-2.5 bg-muted/20 hover:bg-muted/40 transition-colors text-left`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[A?(0,H.jsx)(un,{className:`size-3.5 text-muted-foreground`}):(0,H.jsx)(Vn,{className:`size-3.5 text-muted-foreground`}),(0,H.jsx)(Rss,{className:`size-3.5 text-amber-500`}),(0,H.jsx)(`span`,{className:`text-xs font-bold text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 bg-muted px-1.5 py-0.5 rounded-full`,children:t})]})}),A&&(0,H.jsx)(`div`,{className:`divide-y divide-border/40`,children:e.entries.map(e=>(0,H.jsx)(lQ,{entry:e,visibleFieldIds:b.visibleFields,onAddToToday:_e,onRunStart:ve},e.id))})]},e.id):(0,H.jsxs)(`div`,{id:e.id,className:`group/date`,"data-testid":`date-group-${e.key}`,children:[(0,H.jsx)(oL,{top:Ge,icon:(0,H.jsx)(qt,{className:`size-3.5 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,H.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${t} ${t===1?`entry`:`entries`}`}),(0,H.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(t=>(0,H.jsx)(lQ,{entry:t,visibleFieldIds:b.visibleFields,tone:e.isToday?`primary`:`secondary`,onAddToToday:_e,onRunStart:ve},t.id))})]},e.id)}),(0,H.jsx)(jQ,{batch:je})]}):M&&w.length===0?(0,H.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):w.length===0&&!M?Ye:null})]})}function IQ({pageRoute:e,quests:t,challengeSectionMap:n,onScrollToSection:r}){let{quests:i,stepsComplete:a,totalSteps:o,isComplete:s}=OH(e,t),[c,l]=(0,V.useState)(!1),u=(0,V.useRef)(null),d=(0,V.useRef)(null),f=(0,V.useRef)(null);if(o===0)return null;let p=e=>{let t=n.get(e);t&&r?.(t),l(!1)};(0,V.useEffect)(()=>{if(!c)return;let e=e=>{e.key===`Escape`&&(l(!1),u.current?.focus())},t=e=>{let t=e.relatedTarget,n=u.current?.parentElement;n&&t&&!n.contains(t)&&l(!1)},n=e=>{let t=u.current?.parentElement;t&&!t.contains(e.target)&&l(!1)};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,n),document.addEventListener(`touchstart`,n),d.current?.addEventListener(`focusout`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,n),document.removeEventListener(`touchstart`,n),d.current?.removeEventListener(`focusout`,t)}},[c]),(0,V.useEffect)(()=>()=>{f.current&&=(window.clearTimeout(f.current),null)},[]);let m=()=>{f.current&&=(window.clearTimeout(f.current),null)},h=()=>{m(),f.current=window.setTimeout(()=>l(!1),150)};return(0,H.jsxs)(`div`,{className:`relative py-1.5 shrink-0`,onPointerEnter:e=>{e.pointerType===`mouse`&&(m(),l(!0))},onPointerLeave:e=>{e.pointerType===`mouse`&&h()},children:[(0,H.jsxs)(`button`,{ref:u,type:`button`,"aria-haspopup":`menu`,"aria-expanded":c,"aria-label":`${a} of ${o} challenges complete`,title:`${a} of ${o} challenges complete`,onClick:()=>l(!0),className:`flex items-center gap-1.5 cursor-pointer focus:outline-none select-none text-left rounded-full border border-border/70 bg-background px-3 py-1 hover:bg-muted/40 hover:border-border transition-colors shadow-sm`,children:[s?(0,H.jsx)(Zn,{className:`size-4 text-emerald-500`}):(0,H.jsx)(vn,{className:`size-4 text-muted-foreground`}),(0,H.jsxs)(`span`,{className:U(`text-[10px] font-black uppercase tracking-wider`,s?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`),children:[a,`/`,o]})]}),c&&(0,H.jsxs)(`div`,{ref:d,role:`menu`,"aria-orientation":`vertical`,className:`absolute left-0 top-full mt-1.5 w-64 rounded-xl border border-border bg-popover text-popover-foreground shadow-2xl p-3 z-50 origin-top-left before:content-[''] before:absolute before:-top-1.5 before:left-0 before:right-0 before:h-1.5 before:bg-transparent`,children:[(0,H.jsxs)(`div`,{className:`mb-2.5 pb-2 border-b border-border/60 flex items-center justify-between gap-2`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h5`,{className:`text-[10px] font-black uppercase tracking-widest text-foreground`,children:`Syntax Challenges`}),(0,H.jsx)(`p`,{className:`text-[9px] text-muted-foreground mt-0.5`,children:`Click a challenge to jump to its section.`})]}),(0,H.jsxs)(`span`,{className:`text-[9px] font-black uppercase tracking-wider text-muted-foreground tabular-nums`,children:[a,`/`,o]})]}),(0,H.jsx)(`div`,{className:`flex flex-col gap-1`,children:i.map(e=>{let t=n.get(e.id);return(0,H.jsx)(zq,{quest:e,onClick:t?()=>p(e.id):void 0,disabled:!t,compact:!0,className:`border-0 bg-transparent hover:bg-muted/40`},e.id)})})]})]})}function LQ(e){return(0,H.jsx)(RQ,{...e},e.entry.id)}function RQ({entry:e,onChange:t,registerRun:n,...r}){let[i,a]=(0,V.useState)({blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}),[o,s]=(0,V.useState)(null),c=(0,V.useRef)(i.sourceRevision),l=(0,V.useRef)({rawContent:e.rawContent,...i}),u=(0,V.useCallback)(e=>{c.current=e.sourceRevision;let t=l.current,n=t.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));a(t=>({blocks:n?e.blocks:t.blocks,sourceRevision:e.sourceRevision}))},[]),d=(0,V.useCallback)(async t=>{let n=await Nj.saveNote({noteId:e.id,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:c.current}),r={rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0};return u(r),r},[e.id,u]),f=YJ({onSave:async e=>{await d(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])}),p=(0,V.useCallback)(e=>{let t=l.current.rawContent!==e.rawContent||JSON.stringify(Object.values(l.current.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));l.current=e,t&&f.onChange(e)},[f.onChange]);return(0,V.useEffect)(()=>(n?.(async(t,n)=>{await f.flush();let r=l.current,i=await hF({noteId:e.id,rawContent:r.rawContent,blocks:r.blocks,expectedSourceRevision:c.current},t,n);return u({rawContent:i.note.rawContent,blocks:i.note.blocks,sourceRevision:i.note.sourceRevision}),i}),()=>n?.(null)),[e.id,n,f.flush,u]),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vK,{...r,noteId:e.id,value:o??e.rawContent,noteBlocks:i.blocks,sourceRevision:i.sourceRevision,onIdentityChange:p,onSaved:u,beforeRun:async()=>(await f.flush(),c.current),onSaveRequest:f.flush,onChange:e=>{s(null),t(e)},onBlur:f.onBlur,onCursorPositionChange:f.onLineChange,onCommitChange:f.flush}),f.error?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,f.error instanceof Error?f.error.message:String(f.error),` Your draft is kept.`]}):null,(0,H.jsx)(qP,{noteId:e.id,blocks:i.blocks,sourceRevision:i.sourceRevision,onRevert:async e=>{await f.flush();let n=KP({...l.current,sourceRevision:c.current},e),r=await d(n);l.current=r,s(n.rawContent),t(n.rawContent)}})]})}var zQ=new ID;function BQ({journalDate:e,theme:t,onViewCreated:n}){let[r,i]=(0,V.useState)(null),[a,o]=Ct(),s=Sn(),[c,l]=(0,V.useState)(!1),[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(null),[m,h]=(0,V.useState)(null),[g,_]=(0,V.useState)(null),v=(0,V.useRef)(null),y=(0,V.useRef)(null),b=(0,V.useRef)(new Map),[x,S]=(0,V.useState)(null),w=(0,V.useCallback)(async()=>{let e=v.current;if(!e||!m)throw Error(`The pending workout is unavailable.`);return e.captured?(y.current=e.captured,e.captured.block):(y.current||=e.snapshot?await hF(e.snapshot,e.block,m,e.origin):await gF(e.noteId,e.block,m,e.origin),y.current.block)},[m]),[T,E]=(0,V.useState)({}),D=(0,V.useCallback)((e,t)=>{E(n=>n[e]===t?n:{...n,[e]:t})},[]),O=(0,V.useRef)(new Map),k=(0,V.useRef)(null),[A,j]=(0,V.useState)(null),M=(0,V.useCallback)((e,t)=>{O.current.set(e,t),k.current||(k.current=t,j(t),n?.(t))},[n]),N=a.get(`note`);(0,V.useEffect)(()=>{if(!N||!r)return;let e=document.getElementById(`note-${N}`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},[N,r]);let P=a.toString();(0,V.useEffect)(()=>{let e=new URLSearchParams(P).get(`autoStart`);if(!e)return;let t=QJ.get(e);t&&(QJ.delete(e),v.current=t,y.current=null,p(t.block),h(e),_(t.noteId),d(!0)),o(e=>(e.delete(`autoStart`),e),{replace:!0})},[P,o]);let F=(0,V.useCallback)((e,t)=>{i(n=>n?.map(n=>n.id===e?{...n,rawContent:t}:n)??n)},[]),I=(0,V.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=y.current;if(!a)return Promise.reject(Error(`The saved run pin is unavailable.`));let o=a.session.id,s=O.current.get(a.session.noteId);if(s&&!s.state.doc.toString().includes(GT(o))){let e=KT(s.state,a.session.blockId,o);e&&s.dispatch({changes:e})}return FV.record({blockId:a.session.blockId,noteId:a.session.noteId,resultId:o,data:t,createdAt:t.endTime})},[]);(0,V.useEffect)(()=>{let t=!1;return Kj.listByDate(e).then(e=>{t||i(e)}).catch(()=>{t||i([])}),()=>{t=!0}},[e]);let ee=/^\d{4}-\d{2}-\d{2}$/.test(e),te=(0,V.useMemo)(()=>{if(!ee)return null;let[t,n,r]=e.split(`-`).map(Number);return{prev:Bj(new Date(t,n-1,r-1)),next:Bj(new Date(t,n-1,r+1))}},[e,ee]),{setL3Items:ne}=hA(),[re,ie]=(0,V.useState)({}),ae=r?.map(e=>e.id).join(`|`)??``,oe=(0,V.useMemo)(()=>ae?ae.split(`|`):[],[ae]);(0,V.useEffect)(()=>{if(oe.length===0)return;let e=!1;for(let t of oe)X.getSessionsForNote(t).then(n=>{e||ie(e=>({...e,[t]:n}))}).catch(()=>{});return()=>{e=!0}},[oe]),(0,V.useEffect)(()=>MV(e=>{X.getSessionsForNote(e.noteId).then(t=>{ie(n=>({...n,[e.noteId]:t}))}).catch(()=>{})}),[]);let se=r!==null&&r.length===1?r[0]:null,ce=se?re[se.id]:void 0,L=(0,V.useCallback)(async(t,n)=>{try{let r=b.current.get(t);if(!r)throw Error(`The saved note editor is unavailable.`);let i=C(),a=await r(n,i);QJ.set(i,{noteId:t,block:a.block,captured:a,returnTo:GA(e)}),s(QA(i))}catch(e){S(e instanceof Error?e.message:String(e))}},[e,s]),le=(0,V.useCallback)(e=>{se&&L(se.id,e)},[se,L]);tY({content:se?.rawContent??``,scriptBlocks:se?T[se.id]??[]:[],onStartWorkout:le,results:ce});let ue=(0,V.useCallback)(e=>t=>{L(e,t)},[L]),R=(0,V.useMemo)(()=>{if(!r||r.length<=1)return[];let e=[];for(let t of r){let n=t.title||`Untitled note`,r=eY(Wz(t.rawContent),T[t.id]??[],ue(t.id),re[t.id]);for(let i of r)e.push(...Gz([{...i,id:`note-${t.id}:${i.id}`,label:`${n} · ${i.label}`}]))}return e},[r,T,re,ue]),de=(0,V.useRef)(!1);return(0,V.useEffect)(()=>{if(R.length!==0)return de.current=!0,ne(R),()=>{de.current&&(de.current=!1,ne([]))}},[R,ne]),r?N?(0,H.jsx)(_n,{to:qA(N),replace:!0}):(0,H.jsxs)(TF,{notePersistence:Nj,provider:zQ,children:[(0,H.jsx)(fL,{title:e,subtitle:`${r.length} ${r.length===1?`note`:`notes`}`,actions:(0,H.jsx)(nR,{primary:(0,H.jsxs)(W,{type:`button`,onClick:()=>l(!0),children:[(0,H.jsx)(Kt,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`New note`]})}),editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-8 px-4 py-6 sm:px-6`,children:[x&&(0,H.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,x,` Your draft is kept.`]}),(0,H.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,H.jsx)(`button`,{type:`button`,onClick:()=>Uz()?s(-1):s(`/journal`),className:`rounded-pill border border-border px-2 py-0.5 hover:bg-accent hover:text-foreground transition-colors`,children:`‹ Journal`}),te&&(0,H.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,H.jsxs)(Wn,{to:GA(te.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:[`‹ `,te.prev]}),(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:e}),(0,H.jsxs)(Wn,{to:GA(te.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:[te.next,` ›`]})]})]}),r.length>1&&(0,H.jsx)(`nav`,{"aria-label":`Notes on this date`,className:`flex flex-wrap gap-2`,children:r.map(e=>(0,H.jsx)(Wn,{to:qA(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,H.jsxs)(`div`,{className:`flex flex-col items-start gap-3 rounded-lg border border-dashed border-border p-6`,children:[(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Notes on this date yet.`}),(0,H.jsxs)(W,{type:`button`,size:`lg`,onClick:()=>l(!0),children:[(0,H.jsx)(Kt,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Create a note`]})]}):r.length===1?(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,H.jsx)(Wn,{to:qA(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,H.jsx)(LQ,{entry:r[0],registerRun:e=>{e?b.current.set(r[0].id,e):b.current.delete(r[0].id)},onChange:e=>F(r[0].id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>D(r[0].id,e),onCompleteWorkout:(e,t,n,i)=>I(e,t,n,i,r[0].id),onViewCreated:e=>M(r[0].id,e)},r[0].id)]}):(0,H.jsx)(`div`,{className:`space-y-6`,children:r.map((e,n)=>(0,H.jsxs)(`div`,{id:`note-${e.id}`,className:`rounded-lg border border-border/60 p-4 space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,H.jsx)(Wn,{to:qA(e.id),className:`text-sm font-semibold hover:underline text-foreground`,children:e.title||`Note ${n+1}`})}),(0,H.jsx)(LQ,{entry:e,registerRun:t=>{t?b.current.set(e.id,t):b.current.delete(e.id)},onChange:t=>F(e.id,t),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:t=>D(e.id,t),onCompleteWorkout:(t,n,r,i)=>I(t,n,r,i,e.id),onViewCreated:t=>M(e.id,t)})]},e.id))})]})}),(0,H.jsx)(xz,{open:c,onOpenChange:l,defaultDate:e,onCreated:t=>{Kj.listByDate(e).then(i).catch(()=>{}),s(qA(t.id))}}),u&&f&&(0,H.jsx)(ZG,{block:f,prepareRun:w,onClose:()=>{d(!1),h(null),_(null)},onCompleteWorkout:(e,t)=>I(e,t,m??void 0,void 0),autoStart:!0})]}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function VQ({identity:e}){let t=Sn();return(0,V.useEffect)(()=>{let n=!1;return Kj.resolve(e).then(e=>{!n&&e.journalDate&&t(qA(e.id),{replace:!0})}).catch(()=>{n||t(`/journal`,{replace:!0})}),()=>{n=!0}},[e,t]),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function HQ(e){let t=window.location.pathname,n=TR(t);return n.kind===`date`?(0,H.jsx)(BQ,{journalDate:n.journalDate,theme:e.theme,onViewCreated:e.onViewCreated}):n.kind===`note`?(0,H.jsx)(_n,{to:qA(n.noteId),replace:!0}):n.kind===`uuid-alias`?(0,H.jsx)(VQ,{identity:n.noteId}):n.kind===`slug-alias`?(0,H.jsx)(VQ,{identity:n.slug}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Journal route not found.`})}var UQ=()=>(0,H.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,H.jsx)(`div`,{className:`mt-0.5 flex-shrink-0 text-primary`,children:(0,H.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,"aria-hidden":`true`,children:[(0,H.jsx)(`circle`,{cx:`9`,cy:`9`,r:`8`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,H.jsx)(`path`,{d:`M9 5v4.5M9 11.5v1`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}),(0,H.jsxs)(`div`,{className:`flex-1 text-sm leading-relaxed text-muted-foreground`,children:[(0,H.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Ready to try it?`}),` `,`Press the`,` `,(0,H.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,H.jsx)(`div`,{className:`pointer-events-none absolute -bottom-4 right-8 text-primary/50`,"aria-hidden":`true`,children:(0,H.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 20 20`,fill:`none`,children:[(0,H.jsx)(`path`,{d:`M3 3 L17 3 L17 17`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,H.jsx)(`path`,{d:`M11 11 L17 17 L23 11`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]});function WQ({config:e,onAction:t}){return!e.headline||!e.subtitle||e.pillars.length===0?(0,H.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,H.jsx)(`code`,{children:`attention`}),` widget config.`]}):(0,H.jsxs)(`section`,{className:`p-8`,children:[(0,H.jsx)(`p`,{className:`mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:`Playground`}),(0,H.jsx)(`h1`,{className:`text-3xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-100 sm:text-4xl`,children:e.headline}),(0,H.jsx)(`p`,{className:`mt-4 max-w-3xl text-base leading-7 text-zinc-600 dark:text-zinc-300`,children:e.subtitle}),(0,H.jsx)(`div`,{className:`mt-7 grid gap-3 md:grid-cols-3`,children:e.pillars.map(e=>(0,H.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,H.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,H.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.label}),(0,H.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]},e.label))}),(0,H.jsx)(`div`,{className:`mt-7 flex flex-wrap gap-3`,children:e.actions.map(e=>(0,H.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,H.jsx)(h,{className:`size-4`,"aria-hidden":`true`})]},`${e.action}-${e.label}`))})]})}function GQ({config:e,isDarkMode:t,onRun:n}){let r=(0,V.useRef)(null),i=(0,V.useRef)(null),a=(0,V.useMemo)(()=>e.lines.map(e=>e.code).join(`
172
+ `),[e.lines]);return(0,V.useEffect)(()=>{if(r.current)return i.current?.destroy(),i.current=new Er({state:ri.create({doc:a,extensions:[Qr(),hi(),ri.readOnly.of(!1),Er.theme({"&":{fontSize:`13px`,borderRadius:`12px`,border:`1px solid var(--cm-border)`},".cm-scroller":{fontFamily:`JetBrains Mono, ui-monospace, SFMono-Regular, monospace`,lineHeight:`1.6`,minHeight:`180px`},".cm-content":{padding:`14px 0`},".cm-gutters":{backgroundColor:`transparent`,borderRight:`1px solid var(--cm-border)`}}),Er.theme({"&":{"--cm-border":t?`rgba(82, 82, 91, 0.7)`:`rgba(212, 212, 216, 0.9)`}},{dark:t}),...t?[ni]:[]]}),parent:r.current}),()=>{i.current?.destroy(),i.current=null}},[t,a]),e.lines.length===0?(0,H.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,H.jsx)(`code`,{children:`code-example`}),` widget config.`]}):(0,H.jsxs)(`section`,{className:`p-5`,children:[(0,H.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-zinc-900 dark:text-zinc-100`,children:`Code example`}),(0,H.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,H.jsx)(Ht,{className:`size-3.5`,"aria-hidden":`true`}),e.cta]})]}),(0,H.jsx)(`div`,{ref:r}),(0,H.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,H.jsxs)(`li`,{className:`flex gap-2`,children:[(0,H.jsx)(`span`,{className:`mt-1 inline-block size-1.5 rounded-full bg-zinc-400`,"aria-hidden":`true`}),(0,H.jsxs)(`span`,{children:[(0,H.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 KQ({config:e,onOpenDocs:t}){return!e.category||!e.title||!e.docsPath?(0,H.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,H.jsx)(`code`,{children:`syntax-group`}),` widget config.`]}):(0,H.jsxs)(`article`,{className:`p-5`,children:[(0,H.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:e.category}),(0,H.jsxs)(`h3`,{className:`mt-2 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[(0,H.jsx)(`span`,{className:`mr-2`,"aria-hidden":`true`,children:e.icon}),e.title]}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]}),(0,H.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,H.jsx)(k,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,H.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,H.jsx)(`code`,{children:e.example})})]})}function qQ(e){return({config:t})=>(0,H.jsx)(WQ,{config:t,onAction:e})}function JQ(e,t){return({config:n})=>(0,H.jsx)(GQ,{config:n,isDarkMode:e,onRun:t})}function YQ(e){return({config:t})=>(0,H.jsx)(KQ,{config:t,onOpenDocs:e})}var XQ=[`visitedLanding`,`editedNote`,`ranWorkout`,`loggedEffort`,`openedReview`],ZQ=`wodwiki.onboarding.v1`,QQ={visitedLanding:!1,editedNote:!1,ranWorkout:!1,loggedEffort:!1,openedReview:!1};function $Q(){if(typeof window>`u`||!window.localStorage)return{...QQ};try{let e=window.localStorage.getItem(ZQ);if(!e)return{...QQ};let t=JSON.parse(e),n={...QQ};for(let e of XQ)n[e]=t[e]===!0;return n}catch{return{...QQ}}}function e$(e){if(!(typeof window>`u`||!window.localStorage))try{window.localStorage.setItem(ZQ,JSON.stringify(e))}catch{}}function t$(){let[e,t]=(0,V.useState)($Q);(0,V.useEffect)(()=>{let e=e=>{e.key===ZQ&&t($Q())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let n=(0,V.useCallback)(e=>{t(t=>{if(t[e])return t;let n={...t,[e]:!0};return e$(n),n})},[]),r=XQ.length,i=XQ.reduce((t,n)=>t+ +!!e[n],0);return{progress:e,stepsComplete:i,totalSteps:r,isComplete:i===r,mark:n}}function n$(){let{mark:e}=t$();return{onEditNote:(0,V.useCallback)(()=>{e(`editedNote`)},[e]),onRunWorkout:(0,V.useCallback)(()=>{e(`ranWorkout`)},[e]),onLogEffort:(0,V.useCallback)(()=>{e(`loggedEffort`)},[e])}}var r$=new ID;function i$({theme:e,onViewCreated:t,onScrollToSection:n,onSearch:r}){let{id:i}=zn(),a=i??`playground`,o=az(`playground`,a),s=(0,V.useMemo)(()=>i?fy(i):`Playground`,[i]),c=Sn(),l=!i||i===`playground`,{content:u,loading:d,entryId:f,noteBlocks:p,sourceRevision:m,onIdentityChange:h,onSaved:g,error:_,onChange:v,onLineChange:y,onBlur:b,flush:x,committedSourceRevision:S,resetToOriginal:w}=ZJ({category:`playground`,name:a,mdContent:DY.content,seedOnMount:l}),T=f??o,{onEditNote:E,onRunWorkout:D,onLogEffort:O}=n$(),k=(0,V.useCallback)(e=>{E(),v(e)},[E,v]),[A,j]=(0,V.useState)([]),M=(0,V.useCallback)(()=>{X.getSessionsForNote(T).then(e=>j(e.filter(e=>e.completed))).catch(()=>{})},[T]);(0,V.useEffect)(()=>{M()},[M]);let N=(0,V.useRef)(!1),P=(0,V.useRef)(null),F=(0,V.useCallback)(e=>{if(P.current=e,t?.(e),N.current)return;N.current=!0;let n=Math.min(DY.cursorOffset,e.state.doc.length);e.dispatch({selection:gi.cursor(n)})},[t]),I=(0,V.useCallback)(async e=>{try{await x();let t=C(),n=await gF(T,e,t,`playground`);g({rawContent:n.note.rawContent,blocks:n.note.blocks,sourceRevision:n.note.sourceRevision}),QJ.set(t,{block:n.block,noteId:n.session.noteId,captured:n,origin:`playground`,returnTo:`/playground/${encodeURIComponent(a)}`}),D(),c(QA(t))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[T,a,c,D,x,g]),ee=(0,V.useCallback)(async e=>{try{O();let t=await zJ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content}),n=FJ(new Date);Z({title:`Added to journal`,description:t.journalDate===n?`Added to today's journal`:`Added to ${t.journalDate}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(t.journalDate??n)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[s,a,c,O]),[te,ne]=(0,V.useState)(null),[re,ie]=(0,V.useState)(!1),ae=(0,V.useCallback)(async e=>{let t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`;try{await _H(T,t),Z({title:`Moved to journal`,description:`This playground now lives on ${t}.`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(t)),children:`Open`})}),c(qA(T))}catch{Z({title:`Error`,description:`Could not move to journal`,variant:`destructive`})}},[T,c]),oe=(0,V.useCallback)(async(e,t)=>{let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await zJ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content,date:t}),c(KA(n)),Z({title:`Scheduled`,description:`Added to journal for ${n}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>c(KA(n)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[s,a,c]),[se,ce]=(0,V.useState)([]),L=tY({content:u,scriptBlocks:se,onStartWorkout:I,results:A}),le=(0,V.useMemo)(()=>oY({id:T,type:`playground`}),[T]),ue=fY({noteId:T,stamps:le.stamps}),[R,de]=(0,V.useState)(null);(0,V.useEffect)(()=>{let e=!1;return X.getNote(T).then(t=>{if(e||!t?.sourceId)return;let n=sY(t.sourceId);n&&de({noteId:T,link:n})}).catch(()=>{}),()=>{e=!0}},[T]);let fe=(0,H.jsxs)(nR,{label:`Playground actions`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>ie(!0),title:`Move this playground to a journal date`,className:`inline-flex items-center gap-1 rounded-pill border border-border bg-card px-2.5 py-1 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,children:[(0,H.jsx)(Ut,{className:`size-3.5`,"aria-hidden":`true`}),`Move to journal`]}),(0,H.jsx)(OY,{mode:`playground`,currentWorkout:{name:s,content:u},index:L,onReset:w})]}),pe=mY(`playground`,{onPlay:I,onShare:bY,onAddToToday:ee,onSchedule:ne}),me=(0,V.useCallback)(e=>{if(e===`scroll-to-workout`){let e=L.find(e=>e.type===`time`||e.type===`log`);e&&n?.(e.id)}else e===`open-search`&&r?.()},[L,n,r]),he=(0,V.useCallback)(e=>{let t={id:`code-example-block`,line:0,endLine:e.split(`
173
+ `).length,content:e};I(t)},[I]),ge=(0,V.useCallback)(e=>{e.startsWith(`/`)?window.open(e,`_blank`):c(e)},[c]),_e=(0,V.useCallback)((e,t)=>{if(e===`route`&&t.route)c(t.route);else if(e===`start-workout`){let e=se[0];e&&I(e)}else e===`new-note`&&c(`/playground`)},[c,se,I]),ve=(0,V.useMemo)(()=>new Map([[`playground-run-tip`,UQ],[`attention`,qQ(me)],[`code-example`,JQ(e===`dark`,he)],[`syntax-group`,YQ(ge)]]),[me,he,ge,e]);return(0,V.useEffect)(()=>{document.title=`Wod.Wiki - ${s}`},[s]),d?(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(TF,{notePersistence:Nj,provider:r$,children:(0,H.jsx)(fL,{title:s,actions:fe,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(pY,{data:ue,up:le.up,source:R?.noteId===T?R.link:null}),(0,H.jsx)(vK,{value:u,onChange:k,onCursorPositionChange:y,onBlur:b,noteId:T,noteBlocks:p,sourceRevision:m,onIdentityChange:e=>h({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:g,beforeRun:async()=>(await x(),S()),onSaveRequest:x,onCommitChange:x,commands:pe,enableInlineRuntime:!1,onViewCreated:F,theme:e,showLineNumbers:!1,onBlocksChange:ce,onButtonAction:_e,widgetComponents:ve}),_?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,_ instanceof Error?_.message:String(_),` Your draft is kept.`]}):null,(0,H.jsx)(qP,{noteId:T,blocks:p,sourceRevision:m,onRevert:async e=>{await x();let t=P.current?.state.field(ZC);if(!t)throw Error(`The current note editor is unavailable.`);let n=KP({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:S()},e);h({rawContent:n.rawContent,noteBlocks:n.blocks,sourceRevision:n.sourceRevision}),await x()}})]})})}),te&&(0,H.jsx)(lS,{open:!0,onClose:()=>ne(null),title:`Schedule workout`,children:(0,H.jsx)(JJ,{selectedDate:null,onDateSelect:e=>{oe(te,e),ne(null)}})}),re&&(0,H.jsx)(lS,{open:!0,onClose:()=>ie(!1),title:`Move playground to Journal`,description:`Choose a date. This keeps the workout's existing results and attachments.`,children:(0,H.jsx)(JJ,{selectedDate:null,onDateSelect:e=>{ie(!1),ae(e)}})})]})}function a$({category:e,name:t,mdContent:n,theme:r,runMode:i,hidePlanningCommands:a,onViewCreated:o}){let s=i?i===`inline`:zz.has(e),c=!Bz.has(e),l=az(e,t),u=Sn(),{content:d,loading:f,entryId:p,noteBlocks:m,sourceRevision:h,onIdentityChange:g,onSaved:_,error:v,onChange:y,onLineChange:b,onBlur:x,flush:S,committedSourceRevision:w}=ZJ({category:e,name:t,mdContent:n,seedOnMount:!c}),T=(0,V.useMemo)(()=>c?{label:`${e}-${t}`,path:ZA(e,t)}:null,[e,c,t]),[E,D]=(0,V.useState)(null),O=(0,V.useCallback)(async n=>{let r=C();if(s){try{await S();let e=await hF({noteId:p??l,rawContent:d,blocks:m,expectedSourceRevision:w(),metadata:{title:t},noteType:`playground`},n,r);_({rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision}),QJ.set(r,{block:e.block,noteId:e.session.noteId,captured:e}),u(QA(r))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}return}try{let i=await zJ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content}),a=Object.values(i.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The saved journal workout is unavailable.`);QJ.set(r,{block:{...n,id:a.id},noteId:i.id}),u(JA(i.journalDate??``,r))}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[s,l,p,t,e,T,u,d,m,S,w,_]),k=(0,V.useCallback)(async(n,r)=>{let i=VP(r),a;try{a=(await zJ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content,date:r,wrapInWod:!0})).journalDate??``}catch{Z({variant:`destructive`,title:`Could not save workout`,description:`Failed to add "${t}" to ${i}. Please try again.`});return}u(KA(a));let o=KA(a);Z({title:`Added to ${i}`,description:`"${t}" was added to your journal.`,action:(0,H.jsx)(Yk,{altText:`View journal entry`,onClick:()=>u(o),children:`View Note`}),duration:7e3})},[t,e,T,u]),A=mY(`collection-readonly`,{onPlay:O,onShare:bY,onAddToToday:a?void 0:e=>k(e,new Date),onSchedule:a?void 0:D,onOpenInPlayground:e=>_Y(e,u)}),[j,M]=(0,V.useState)([]),N=(0,V.useCallback)(()=>{u(qA(l))},[u,l]),P=tY({content:d,scriptBlocks:j,onStartWorkout:O,onEditNote:c?N:void 0}),F=(0,V.useMemo)(()=>c?oY({id:l,type:`feed`}):null,[c,l]),I=fY({noteId:l,stamps:F?.stamps??[]}),ee=(0,H.jsx)(nR,{children:(0,H.jsx)(OY,{mode:`collection-readonly`,currentWorkout:{name:l,content:d},index:P})});return f?(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fL,{title:t,actions:ee,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,H.jsx)(pY,{data:I,up:F?.up}),(0,H.jsx)(vK,{value:d,onChange:y,onCursorPositionChange:b,onBlur:x,noteId:l,noteBlocks:m,sourceRevision:h,onIdentityChange:e=>g({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:_,beforeRun:async()=>(await S(),w()),onSaveRequest:S,onCommitChange:S,readonly:!0,enableInlineRuntime:s,commands:A,onViewCreated:o,theme:r,showLineNumbers:!1,onBlocksChange:M}),v?(0,H.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,v instanceof Error?v.message:String(v),` Your draft is kept.`]}):null]})}),E&&(0,H.jsx)(lS,{open:!0,onClose:()=>D(null),title:`Schedule ${t}`,children:(0,H.jsx)(JJ,{selectedDate:null,onDateSelect:e=>{e&&k(E,e),D(null)}})})]})}var o$=xe(`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2`,{variants:{variant:{default:`border-transparent bg-primary text-primary-foreground hover:bg-primary/80`,secondary:`border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80`,destructive:`border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80`,outline:`text-foreground`}},defaultVariants:{variant:`default`}}),s$=V.memo(({className:e,variant:t,...n})=>(0,H.jsx)(`div`,{className:U(o$({variant:t}),e),...n})),c$=(0,V.forwardRef)(function({className:e,multiple:t,...n},r){return(0,H.jsxs)(`span`,{"data-slot":`control`,className:U(`group relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`has-data-[focus]:after:ring-2 has-data-[focus]:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:[(0,H.jsx)(te,{ref:r,multiple:t,...n,className:U(`relative block w-full appearance-none rounded-lg py-[calc(theme(spacing.2.5)-1px)]`,`sm:py-[calc(theme(spacing.1.5)-1px)]`,t?`px-[calc(theme(spacing.3.5)-1px)] sm:px-[calc(theme(spacing.3)-1px)]`:`pr-[calc(theme(spacing.10)-1px)] pl-[calc(theme(spacing.3.5)-1px)] sm:pr-[calc(theme(spacing.9)-1px)] sm:pl-[calc(theme(spacing.3)-1px)]`,`[&_optgroup]:font-semibold`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6 dark:[&>*]:text-white`,`border border-border/60 data-[hover]:border-border dark:border-white/10 dark:data-[hover]:border-white/20`,`bg-transparent dark:bg-white/5 dark:[&>*]:bg-muted`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 data-[disabled]:opacity-100 dark:data-[disabled]:border-white/15 dark:data-[disabled]:bg-white/2.5 dark:data-[hover]:data-[disabled]:border-white/15`,`dark:scheme-dark`,e)}),!t&&(0,H.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2`,children:(0,H.jsxs)(`svg`,{className:`size-5 stroke-muted-foreground group-has-data-[disabled]:stroke-muted-foreground/70 sm:size-4 forced-colors:stroke-[CanvasText]`,viewBox:`0 0 16 16`,"aria-hidden":`true`,fill:`none`,children:[(0,H.jsx)(`path`,{d:`M5.75 10.75L8 13L10.25 10.75`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,H.jsx)(`path`,{d:`M10.25 5.25L8 3L5.75 5.25`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]})}),l$={effort:`efforts`,equipment:`equipment`},u$=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`page`,`page_notes`,`note_tags`,`attachments`];async function d$(e){let t=e.kind===`effort`?dc(e.rawContent):void 0,n=e.kind===`equipment`?mc(e.rawContent):void 0,r=t?.effort??n?.equipment,i=[...t?.errors??n?.errors??[]],a=A_(e.rawContent),o=typeof a.id==`string`?a.id.trim():``;if(o||i.push("Frontmatter must declare a stable `id` (the clone flow patches it into the source)"),r&&r.slug!==e.slug&&i.push(`Document slug "${r.slug}" does not match "${e.slug}"`),r&&r.label.trim()!==e.title.trim()&&i.push(`Document label "${r.label}" does not match title "${e.title}"`),i.length>0)throw Error(i.join(`
174
+ `));return X.withTransaction([...u$],async i=>{let a=e.kind===`effort`?await i.getEffort(e.slug):await i.getEquipment(e.slug);if(a?.registrySource===`bundled`)throw Error(`"${e.slug}" is a bundled definition and cannot be saved over — clone it first`);if(a&&a.id!==o)throw Error(`Document id "${o}" does not match record id "${a.id}" — clone instead of re-keying`);let s=a?.ownerNoteId,c=e.noteId??s??`${e.kind}/${e.slug}`;if(s!==void 0&&c!==s)throw Error(`"${e.slug}" is owned by note ${s}; refusing to save against ${c}`);let l=new Date().toISOString();if(e.kind===`effort`){let n={...t.effort,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:l$.effort,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEffort(n)}else{let t={...n.equipment,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:l$.equipment,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEquipment(t)}return{id:c,sourceRevision:(await i.saveNoteSource({noteId:c,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r.label,sourceId:l$[e.kind]},createdAt:Date.now()})).sourceRevision}})}async function f$(e,t){await X.withTransaction([...u$],async n=>{let r=e===`effort`?await n.getEffort(t):await n.getEquipment(t);if(r?.registrySource!==`user`)throw Error(`"${t}" is not user-owned ${e}`);e===`effort`?await n.deleteEffort(t):await n.deleteEquipment(t);let i=r.ownerNoteId??`${e}/${t}`;await n.getNote(i)&&await n.deleteNote(i)})}function p$(e,t,n){let r=`effort-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=Wa(e,[`id`],r);return o=Wa(o,[`slug`],i),o=Wa(o,[`label`],a),o=Wa(o,[`registrySource`],`user`),o=Wa(o,[`derivation`,`parentSlug`],t),{raw:o,id:r,slug:i,label:a}}function m$(e){let{registry:t,isReady:n,refresh:r}=Vk(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(!0),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(!1),g=u?.registrySource===`user`,_=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`effort/${i.slug}`,c=await X.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??fc(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load effort.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,V.useCallback)(async t=>{if(!e&&!u)return;let{effort:n,errors:i}=dc(t,u??void 0);if(i.length>0)throw Z({title:`Invalid YAML`,description:i.join(`
163
175
  `),variant:`destructive`}),Error(i.join(`
164
- `));let a=t,o=n.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(o!==n.slug&&(n.slug=o,a=Wa(a,[`slug`],o)),n.label.trim()!==n.label&&(n.label=n.label.trim(),a=Wa(a,[`label`],n.label)),n.updatedAt=new Date().toISOString(),n.registrySource===`bundled`){let e=n$(a,n.slug,n.label);a=e.raw,n.id=e.id,n.slug=e.slug,n.label=e.label,n.registrySource=`user`,n.derivation={parentSlug:u?.slug,coefficients:{},hardOverrides:{}}}try{let e=n.ownerNoteId??_.current?.id??`effort/${n.slug}`,t=_.current?.id===e?_.current.revision:0,i=await e$({kind:`effort`,slug:n.slug,rawContent:a,title:n.label,expectedSourceRevision:t});_.current={id:i.id,revision:i.sourceRevision},await r(),d(n)}catch(e){throw Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`}),e}},[e,u,r]),{onChange:y,onLineChange:b,onBlur:x,flush:S}=RJ({onSave:v});return{document:i,setDocument:(0,V.useCallback)(e=>{a(e),y(e)},[y]),isLoading:o,effort:u,isEditable:g,notFound:f,flush:S,save:(0,V.useCallback)(e=>v(e??i),[v,i]),remove:(0,V.useCallback)(async()=>{let t=u?.slug??e;if(t)try{await t$(`effort`,t),_.current=null,d(null),await r()}catch(e){throw Z({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete effort.`,variant:`destructive`}),e}},[u,e,r]),cloneForEdit:(0,V.useCallback)(async()=>{if(!u||u.registrySource!==`bundled`)return null;let e=n$(i||fc(u),u.slug,u.label),t={...u,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,derivation:{parentSlug:u.slug,coefficients:{},hardOverrides:{}},ownerNoteId:`effort/${e.slug}`,sourceId:`efforts`,sourcePath:`effort/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};d(t),a(e.raw);try{let t=await e$({kind:`effort`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});_.current={id:t.id,revision:t.sourceRevision},await r()}catch(e){throw Z({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[u,i,r]),error:c,isAliasMatch:m}}function i$({resolved:e,effort:t}){return(0,H.jsxs)(`div`,{className:`my-6 p-4 border rounded-lg bg-muted/30 space-y-4`,children:[(0,H.jsxs)(`h3`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,H.jsx)(Ye,{className:`size-4`}),`Effective Resolution`]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Effective MET`}),(0,H.jsx)(`p`,{className:`text-xl font-bold`,children:e.met.toFixed(1)}),Math.abs(e.met-(t.baseAttributes.met||0))>.01&&(0,H.jsxs)(`span`,{className:`text-xs text-amber-600 dark:text-amber-400`,children:[`(base: `,t.baseAttributes.met.toFixed(1),`)`]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Discipline Factor`}),(0,H.jsxs)(`p`,{className:`text-xl font-bold`,children:[e.disciplineFactor.toFixed(2),`×`]})]})]}),Object.keys(e.modifiers).length>0&&(0,H.jsxs)(`div`,{className:`border-t pt-3`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-2`,children:`Applied Modifiers`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Object.entries(e.modifiers).map(([e,t])=>(0,H.jsxs)(XQ,{variant:`outline`,children:[e,`: `,t]},e))})]}),e.definition.derivation?.parentSlug&&(0,H.jsxs)(`div`,{className:`border-t pt-3 text-sm`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-1`,children:`Parent`}),(0,H.jsx)(`span`,{className:`font-mono text-primary`,children:e.definition.derivation.parentSlug})]})]})}function a$(){let{slug:e}=zn(),[t]=Ct(),n=Sn(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{registry:a,isReady:o,refresh:s}=Vk(),{document:c,setDocument:l,isLoading:u,effort:d,isEditable:f,notFound:p,cloneForEdit:m,error:h,onLineChange:g,onBlur:_,flush:v}=r$(e),[y,b]=(0,V.useState)([]),[x]=(0,V.useState)([]),[S,w]=(0,V.useState)(null),[T,E]=(0,V.useState)(!1),D=lj(t).mode===`create`,[O,k]=(0,V.useState)(()=>{let t=e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``,n=t?zE(t):``;return fc({id:`effort-user-${crypto.randomUUID()}`,slug:t,label:n,aliases:t?[t.replace(/[-_]+/g,` `)]:[],baseAttributes:{met:5},registrySource:`user`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()})}),[A,j]=(0,V.useState)(!1),[N,P]=(0,V.useState)(``),F=(0,V.useMemo)(()=>a?[...a.list()].sort((e,t)=>e.label.localeCompare(t.label)):[],[a]),I=(0,V.useCallback)(async()=>{if(!(!e||!N||!a))try{await Tc(a,N,e),await s(),Z({title:`Alias Linked`,description:`Linked "${e}" as an alias to ${N}.`}),n(cj(N))}catch(e){Z({title:`Failed to link alias`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,N,a,s,n]),ee=(0,V.useCallback)(async()=>{let{effort:e,errors:t}=dc(O);if(t.length>0){Z({title:`Invalid YAML`,description:t.join(`
165
- `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Z({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Z({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await e$({kind:`effort`,slug:r,rawContent:O,title:e.label.trim()||zE(r),expectedSourceRevision:0}),await s(),n(cj(r),{replace:!0})}catch(e){Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`})}},[O,s,n]),te=(0,V.useMemo)(()=>new bc(a),[a]),ne=(0,V.useMemo)(()=>!d||!o?null:te.resolveEffort(d.slug),[d,o,te]),re=(0,V.useCallback)(async t=>{try{let r=await OJ({workoutName:d?.label??e??`Effort`,category:`effort`,sourceNotePath:cj(e??``),wodContent:t.content}),i=Object.values(r.blocks??{}).find(e=>e.kind===`wod`);if(!i)throw Error(`The saved journal workout is unavailable.`);let a=C();VJ.set(a,{block:{...t,id:i.id},noteId:r.id}),n(`/run/${a}`)}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,d?.label,n]),ie=(0,V.useCallback)(async(e,t)=>{if(!d)return;let r=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await OJ({workoutName:d.label,category:`effort`,sourceNoteLabel:d.label,sourceNotePath:cj(d.slug),wodContent:e.content,date:t}),n(KA(r)),Z({title:`Scheduled`,description:`Added to journal for ${r}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>n(KA(r)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[d,n]);WJ({content:c,scriptBlocks:y,onStartWorkout:re,results:x});let ae=d?.ownerNoteId??`effort/${e}`,oe=(0,V.useMemo)(()=>e?YJ({id:ae,type:`collection`}):null,[e,ae]),se=tY({noteId:ae,stamps:oe?.stamps??[],effortSlug:e}),ce=rY(`collection-readonly`,{onPlay:re,onShare:lY,onSchedule:w});(0,V.useEffect)(()=>{d&&(window.document.title=`Wod.Wiki - ${d.label}`)},[d]);let L=(0,V.useCallback)(async()=>{if(d)try{let e=await m();e&&(n(cj(e.slug)),Z({title:`Cloned`,description:`Created a custom copy of "${d.label}". You can now edit it.`}))}catch(e){Z({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[m,d,n]);if(!o)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(D){let t=(0,H.jsx)(nR,{primary:(0,H.jsx)(W,{onClick:ee,"data-testid":`effort-create-btn`,children:`Create Effort`}),children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Cancel`})});return(0,H.jsx)(`div`,{"data-testid":sB.EFFORT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:e&&e!==`new`?`New effort: ${e}`:`Create Custom Effort`,actions:t,editor:(0,H.jsx)(`div`,{className:`relative`,"data-testid":`effort-create-editor`,children:(0,H.jsx)(sK,{value:O,onChange:k,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:ce,onBlocksChange:b})})})})}if(u)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(h)return(0,H.jsxs)(`div`,{"data-testid":`effort-load-error`,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Effort could not be loaded`}),(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:h})]}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Back to Catalog`})]});if(p||!d)return(0,H.jsxs)(`div`,{"data-testid":sB.EFFORT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Effort “`,e,`” not found`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This movement has not been populated in the effort catalog yet. You can create a new definition page for it or link it as an alias to an existing effort.`})]}),A?(0,H.jsxs)(`div`,{className:`w-full space-y-4 p-4 border rounded-lg bg-card text-left`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,children:[`Select target effort for “`,e,`”:`]}),(0,H.jsx)(ZQ,{value:N,onChange:e=>P(e.target.value),"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_SELECT,children:F.map(e=>(0,H.jsxs)(`option`,{value:e.slug,children:[e.label,` (`,e.slug,`)`]},e.slug))})]}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>j(!1),children:`Cancel`}),(0,H.jsx)(W,{size:`sm`,onClick:I,disabled:!N,"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_CONFIRM,children:`Confirm Link`})]})]}):(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,H.jsx)(W,{onClick:()=>n(cj(e,void 0,{mode:`create`})),"data-testid":sB.EFFORT_NOT_FOUND_CREATE_BTN,children:`Create Effort Page`}),(0,H.jsx)(W,{variant:`secondary`,onClick:()=>{j(!0),F.length>0&&!N&&P(F[0].slug)},"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_BTN,children:`Link as Alias`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Back to Catalog`})]})]});let le=(0,H.jsxs)(nR,{primary:f?void 0:(0,H.jsxs)(W,{variant:`outline`,onClick:L,"data-testid":sB.EFFORT_DETAIL_CLONE_BTN,children:[(0,H.jsx)(Se,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,H.jsx)(W,{variant:`ghost`,size:`icon`,onClick:()=>Uz()?n(-1):n(rj()),"aria-label":`Back to catalog`,title:Uz()?`Back`:`Back to catalog`,children:(0,H.jsx)(M,{className:`size-4`})}),(0,H.jsx)(XQ,{"data-testid":sB.EFFORT_DETAIL_SOURCE,variant:d.registrySource===`bundled`?`secondary`:`default`,children:d.registrySource===`bundled`?`Bundled`:`Custom`}),ne&&(0,H.jsxs)(W,{variant:T?`default`:`outline`,onClick:()=>E(e=>!e),children:[(0,H.jsx)(Ye,{className:`size-4 mr-1.5`}),T?`Hide Resolved`:`Show Resolved`]})]}),ue=ae;return(0,H.jsxs)(`div`,{"data-testid":sB.EFFORT_DETAIL_ROOT,className:`contents`,children:[(0,H.jsx)(fL,{title:d.label,titleTestId:sB.EFFORT_DETAIL_LABEL,actions:le,editor:(0,H.jsxs)(`div`,{className:`relative`,"data-testid":sB.EFFORT_DETAIL_NOTEBOOK_EDITOR,children:[T&&ne&&(0,H.jsx)(`div`,{className:`px-6 lg:px-10 pt-4`,children:(0,H.jsx)(i$,{resolved:ne,effort:d})}),(0,H.jsx)(sK,{noteId:ue,value:c,onChange:l,onCursorPositionChange:g,onBlur:_,onSaveRequest:v,onCommitChange:v,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:ce,onBlocksChange:b}),(0,H.jsx)(nY,{data:se,up:oe?.up,relatedLabel:`Used in`})]})}),S&&(0,H.jsx)(lS,{open:!0,onClose:()=>w(null),title:`Schedule workout`,children:(0,H.jsx)(LJ,{selectedDate:null,onDateSelect:e=>{ie(S,e),w(null)}})})]})}function o$(e,t){let n=t??e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return hc({id:`equipment-user-${crypto.randomUUID()}`,slug:e,label:n||e,aliases:[],registrySource:`user`})}function s$(e,t,n){let r=`equipment-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=Wa(e,[`id`],r);return o=Wa(o,[`slug`],i),o=Wa(o,[`label`],a),o=Wa(o,[`registrySource`],`user`),{raw:o,id:r,slug:i,label:a}}function c$(e){let{registry:t,isReady:n,refresh:r}=Wk(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(!0),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(!1),g=u?.registrySource===`user`,_=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`equipment/${i.slug}`,c=await X.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??hc(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load equipment.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,V.useCallback)(async e=>{let{equipment:t,errors:n}=mc(e,u??void 0);if(n.length>0)throw Z({title:`Invalid YAML`,description:n.join(`
176
+ `));let a=t,o=n.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(o!==n.slug&&(n.slug=o,a=Wa(a,[`slug`],o)),n.label.trim()!==n.label&&(n.label=n.label.trim(),a=Wa(a,[`label`],n.label)),n.updatedAt=new Date().toISOString(),n.registrySource===`bundled`){let e=p$(a,n.slug,n.label);a=e.raw,n.id=e.id,n.slug=e.slug,n.label=e.label,n.registrySource=`user`,n.derivation={parentSlug:u?.slug,coefficients:{},hardOverrides:{}}}try{let e=n.ownerNoteId??_.current?.id??`effort/${n.slug}`,t=_.current?.id===e?_.current.revision:0,i=await d$({kind:`effort`,slug:n.slug,rawContent:a,title:n.label,expectedSourceRevision:t});_.current={id:i.id,revision:i.sourceRevision},await r(),d(n)}catch(e){throw Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`}),e}},[e,u,r]),{onChange:y,onLineChange:b,onBlur:x,flush:S}=YJ({onSave:v});return{document:i,setDocument:(0,V.useCallback)(e=>{a(e),y(e)},[y]),isLoading:o,effort:u,isEditable:g,notFound:f,flush:S,save:(0,V.useCallback)(e=>v(e??i),[v,i]),remove:(0,V.useCallback)(async()=>{let t=u?.slug??e;if(t)try{await f$(`effort`,t),_.current=null,d(null),await r()}catch(e){throw Z({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete effort.`,variant:`destructive`}),e}},[u,e,r]),cloneForEdit:(0,V.useCallback)(async()=>{if(!u||u.registrySource!==`bundled`)return null;let e=p$(i||fc(u),u.slug,u.label),t={...u,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,derivation:{parentSlug:u.slug,coefficients:{},hardOverrides:{}},ownerNoteId:`effort/${e.slug}`,sourceId:`efforts`,sourcePath:`effort/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};d(t),a(e.raw);try{let t=await d$({kind:`effort`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});_.current={id:t.id,revision:t.sourceRevision},await r()}catch(e){throw Z({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[u,i,r]),error:c,isAliasMatch:m}}function h$({resolved:e,effort:t}){return(0,H.jsxs)(`div`,{className:`my-6 p-4 border rounded-lg bg-muted/30 space-y-4`,children:[(0,H.jsxs)(`h3`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,H.jsx)(Ye,{className:`size-4`}),`Effective Resolution`]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Effective MET`}),(0,H.jsx)(`p`,{className:`text-xl font-bold`,children:e.met.toFixed(1)}),Math.abs(e.met-(t.baseAttributes.met||0))>.01&&(0,H.jsxs)(`span`,{className:`text-xs text-amber-600 dark:text-amber-400`,children:[`(base: `,t.baseAttributes.met.toFixed(1),`)`]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Discipline Factor`}),(0,H.jsxs)(`p`,{className:`text-xl font-bold`,children:[e.disciplineFactor.toFixed(2),`×`]})]})]}),Object.keys(e.modifiers).length>0&&(0,H.jsxs)(`div`,{className:`border-t pt-3`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-2`,children:`Applied Modifiers`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Object.entries(e.modifiers).map(([e,t])=>(0,H.jsxs)(s$,{variant:`outline`,children:[e,`: `,t]},e))})]}),e.definition.derivation?.parentSlug&&(0,H.jsxs)(`div`,{className:`border-t pt-3 text-sm`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-1`,children:`Parent`}),(0,H.jsx)(`span`,{className:`font-mono text-primary`,children:e.definition.derivation.parentSlug})]})]})}function g$(){let{slug:e}=zn(),[t]=Ct(),n=Sn(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{registry:a,isReady:o,refresh:s}=Vk(),{document:c,setDocument:l,isLoading:u,effort:d,isEditable:f,notFound:p,cloneForEdit:m,error:h,onLineChange:g,onBlur:_,flush:v}=m$(e),[y,b]=(0,V.useState)([]),[x]=(0,V.useState)([]),[S,w]=(0,V.useState)(null),[T,E]=(0,V.useState)(!1),D=lj(t).mode===`create`,[O,k]=(0,V.useState)(()=>{let t=e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``,n=t?zE(t):``;return fc({id:`effort-user-${crypto.randomUUID()}`,slug:t,label:n,aliases:t?[t.replace(/[-_]+/g,` `)]:[],baseAttributes:{met:5},registrySource:`user`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()})}),[A,j]=(0,V.useState)(!1),[N,P]=(0,V.useState)(``),F=(0,V.useMemo)(()=>a?[...a.list()].sort((e,t)=>e.label.localeCompare(t.label)):[],[a]),I=(0,V.useCallback)(async()=>{if(!(!e||!N||!a))try{await Tc(a,N,e),await s(),Z({title:`Alias Linked`,description:`Linked "${e}" as an alias to ${N}.`}),n(cj(N))}catch(e){Z({title:`Failed to link alias`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,N,a,s,n]),ee=(0,V.useCallback)(async()=>{let{effort:e,errors:t}=dc(O);if(t.length>0){Z({title:`Invalid YAML`,description:t.join(`
177
+ `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Z({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Z({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await d$({kind:`effort`,slug:r,rawContent:O,title:e.label.trim()||zE(r),expectedSourceRevision:0}),await s(),n(cj(r),{replace:!0})}catch(e){Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`})}},[O,s,n]),te=(0,V.useMemo)(()=>new bc(a),[a]),ne=(0,V.useMemo)(()=>!d||!o?null:te.resolveEffort(d.slug),[d,o,te]),re=(0,V.useCallback)(async t=>{try{let r=await zJ({workoutName:d?.label??e??`Effort`,category:`effort`,sourceNotePath:cj(e??``),wodContent:t.content}),i=Object.values(r.blocks??{}).find(e=>e.kind===`wod`);if(!i)throw Error(`The saved journal workout is unavailable.`);let a=C();QJ.set(a,{block:{...t,id:i.id},noteId:r.id}),n(`/run/${a}`)}catch(e){Z({title:`Workout not started`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,d?.label,n]),ie=(0,V.useCallback)(async(e,t)=>{if(!d)return;let r=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await zJ({workoutName:d.label,category:`effort`,sourceNoteLabel:d.label,sourceNotePath:cj(d.slug),wodContent:e.content,date:t}),n(KA(r)),Z({title:`Scheduled`,description:`Added to journal for ${r}`,action:(0,H.jsx)(Yk,{altText:`Open journal`,onClick:()=>n(KA(r)),children:`Open`})})}catch{Z({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[d,n]);tY({content:c,scriptBlocks:y,onStartWorkout:re,results:x});let ae=d?.ownerNoteId??`effort/${e}`,oe=(0,V.useMemo)(()=>e?oY({id:ae,type:`collection`}):null,[e,ae]),se=fY({noteId:ae,stamps:oe?.stamps??[],effortSlug:e}),ce=mY(`collection-readonly`,{onPlay:re,onShare:bY,onSchedule:w});(0,V.useEffect)(()=>{d&&(window.document.title=`Wod.Wiki - ${d.label}`)},[d]);let L=(0,V.useCallback)(async()=>{if(d)try{let e=await m();e&&(n(cj(e.slug)),Z({title:`Cloned`,description:`Created a custom copy of "${d.label}". You can now edit it.`}))}catch(e){Z({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[m,d,n]);if(!o)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(D){let t=(0,H.jsx)(nR,{primary:(0,H.jsx)(W,{onClick:ee,"data-testid":`effort-create-btn`,children:`Create Effort`}),children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Cancel`})});return(0,H.jsx)(`div`,{"data-testid":sB.EFFORT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:e&&e!==`new`?`New effort: ${e}`:`Create Custom Effort`,actions:t,editor:(0,H.jsx)(`div`,{className:`relative`,"data-testid":`effort-create-editor`,children:(0,H.jsx)(vK,{value:O,onChange:k,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:ce,onBlocksChange:b})})})})}if(u)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(h)return(0,H.jsxs)(`div`,{"data-testid":`effort-load-error`,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Effort could not be loaded`}),(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:h})]}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Back to Catalog`})]});if(p||!d)return(0,H.jsxs)(`div`,{"data-testid":sB.EFFORT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Effort “`,e,`” not found`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This movement has not been populated in the effort catalog yet. You can create a new definition page for it or link it as an alias to an existing effort.`})]}),A?(0,H.jsxs)(`div`,{className:`w-full space-y-4 p-4 border rounded-lg bg-card text-left`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,children:[`Select target effort for “`,e,`”:`]}),(0,H.jsx)(c$,{value:N,onChange:e=>P(e.target.value),"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_SELECT,children:F.map(e=>(0,H.jsxs)(`option`,{value:e.slug,children:[e.label,` (`,e.slug,`)`]},e.slug))})]}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>j(!1),children:`Cancel`}),(0,H.jsx)(W,{size:`sm`,onClick:I,disabled:!N,"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_CONFIRM,children:`Confirm Link`})]})]}):(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,H.jsx)(W,{onClick:()=>n(cj(e,void 0,{mode:`create`})),"data-testid":sB.EFFORT_NOT_FOUND_CREATE_BTN,children:`Create Effort Page`}),(0,H.jsx)(W,{variant:`secondary`,onClick:()=>{j(!0),F.length>0&&!N&&P(F[0].slug)},"data-testid":sB.EFFORT_NOT_FOUND_ALIAS_BTN,children:`Link as Alias`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(rj()),children:`Back to Catalog`})]})]});let le=(0,H.jsxs)(nR,{primary:f?void 0:(0,H.jsxs)(W,{variant:`outline`,onClick:L,"data-testid":sB.EFFORT_DETAIL_CLONE_BTN,children:[(0,H.jsx)(Se,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,H.jsx)(W,{variant:`ghost`,size:`icon`,onClick:()=>Uz()?n(-1):n(rj()),"aria-label":`Back to catalog`,title:Uz()?`Back`:`Back to catalog`,children:(0,H.jsx)(M,{className:`size-4`})}),(0,H.jsx)(s$,{"data-testid":sB.EFFORT_DETAIL_SOURCE,variant:d.registrySource===`bundled`?`secondary`:`default`,children:d.registrySource===`bundled`?`Bundled`:`Custom`}),ne&&(0,H.jsxs)(W,{variant:T?`default`:`outline`,onClick:()=>E(e=>!e),children:[(0,H.jsx)(Ye,{className:`size-4 mr-1.5`}),T?`Hide Resolved`:`Show Resolved`]})]}),ue=ae;return(0,H.jsxs)(`div`,{"data-testid":sB.EFFORT_DETAIL_ROOT,className:`contents`,children:[(0,H.jsx)(fL,{title:d.label,titleTestId:sB.EFFORT_DETAIL_LABEL,actions:le,editor:(0,H.jsxs)(`div`,{className:`relative`,"data-testid":sB.EFFORT_DETAIL_NOTEBOOK_EDITOR,children:[T&&ne&&(0,H.jsx)(`div`,{className:`px-6 lg:px-10 pt-4`,children:(0,H.jsx)(h$,{resolved:ne,effort:d})}),(0,H.jsx)(vK,{noteId:ue,value:c,onChange:l,onCursorPositionChange:g,onBlur:_,onSaveRequest:v,onCommitChange:v,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:ce,onBlocksChange:b}),(0,H.jsx)(pY,{data:se,up:oe?.up,relatedLabel:`Used in`})]})}),S&&(0,H.jsx)(lS,{open:!0,onClose:()=>w(null),title:`Schedule workout`,children:(0,H.jsx)(JJ,{selectedDate:null,onDateSelect:e=>{ie(S,e),w(null)}})})]})}function _$(e,t){let n=t??e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return hc({id:`equipment-user-${crypto.randomUUID()}`,slug:e,label:n||e,aliases:[],registrySource:`user`})}function v$(e,t,n){let r=`equipment-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=Wa(e,[`id`],r);return o=Wa(o,[`slug`],i),o=Wa(o,[`label`],a),o=Wa(o,[`registrySource`],`user`),{raw:o,id:r,slug:i,label:a}}function y$(e){let{registry:t,isReady:n,refresh:r}=Wk(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(!0),[c,l]=(0,V.useState)(null),[u,d]=(0,V.useState)(null),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(!1),g=u?.registrySource===`user`,_=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`equipment/${i.slug}`,c=await X.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??hc(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load equipment.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,V.useCallback)(async e=>{let{equipment:t,errors:n}=mc(e,u??void 0);if(n.length>0)throw Z({title:`Invalid YAML`,description:n.join(`
166
178
  `),variant:`destructive`}),Error(n.join(`
167
- `));let i=e,a=t.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(a!==t.slug&&(t.slug=a,i=Wa(i,[`slug`],a)),t.label.trim()!==t.label&&(t.label=t.label.trim(),i=Wa(i,[`label`],t.label)),t.updatedAt=new Date().toISOString(),t.registrySource===`bundled`){let e=s$(i,t.slug,t.label);i=e.raw,t.id=e.id,t.slug=e.slug,t.label=e.label,t.registrySource=`user`}try{let e=t.ownerNoteId??_.current?.id??`equipment/${t.slug}`,n=_.current?.id===e?_.current.revision:0,a=await e$({kind:`equipment`,slug:t.slug,rawContent:i,title:t.label,expectedSourceRevision:n,noteId:e});_.current={id:a.id,revision:a.sourceRevision},await r(),d(t)}catch(e){throw Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`}),e}},[u,r]),{onChange:y,onLineChange:b,onBlur:x,flush:S}=RJ({onSave:v});return{document:i,setDocument:(0,V.useCallback)(e=>{a(e),y(e)},[y]),isLoading:o,equipment:u,isEditable:g,notFound:f,flush:S,save:(0,V.useCallback)(e=>v(e??i),[v,i]),remove:(0,V.useCallback)(async()=>{let e=u?.slug;if(e)try{await t$(`equipment`,e),_.current=null,d(null),await r()}catch(e){throw Z({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete equipment.`,variant:`destructive`}),e}},[u,r]),cloneForEdit:(0,V.useCallback)(async()=>{if(!u||u.registrySource!==`bundled`)return null;let e=s$(i||hc(u),u.slug,u.label),t={...u,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,ownerNoteId:`equipment/${e.slug}`,sourceId:`equipment`,sourcePath:`equipment/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};d(t),a(e.raw);try{let t=await e$({kind:`equipment`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});_.current={id:t.id,revision:t.sourceRevision},await r()}catch(e){throw Z({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[u,i,r]),error:c,isAliasMatch:m}}function l$(e){let{isReady:t,registry:n}=Wk(),{isReady:r,registry:i}=Vk(),[a,o]=(0,V.useState)({efforts:[],usedBy:[]});return(0,V.useEffect)(()=>{if(!t||!r||!e){o({efforts:[],usedBy:[]});return}let n=!1;async function a(){let t=i.list().filter(t=>t.equipment?.includes(e)??!1),r=await X.getEquipmentUsage(e);n||o({efforts:t,usedBy:r})}return a(),()=>{n=!0}},[e,t,r,n,i]),a}function u$(){let{slug:e}=zn(),[t]=Ct(),n=Sn(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{isReady:a,refresh:o}=Wk(),{document:s,setDocument:c,isLoading:l,equipment:u,isEditable:d,notFound:f,cloneForEdit:p,error:m,onLineChange:h,onBlur:g,flush:_}=c$(e),[v,y]=(0,V.useState)([]),b=t.get(`mode`)===`create`,[x,S]=(0,V.useState)(()=>o$(e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``)),C=(0,V.useCallback)(async()=>{let{equipment:e,errors:t}=mc(x);if(t.length>0){Z({title:`Invalid YAML`,description:t.join(`
168
- `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Z({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Z({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await e$({kind:`equipment`,slug:r,rawContent:x,title:e.label.trim()||zE(r),expectedSourceRevision:0}),await o(),n(ij(r),{replace:!0})}catch(e){Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`})}},[x,o,n]);WJ({content:b?x:s,scriptBlocks:v});let w=u?.ownerNoteId??(e?`equipment/${e}`:``),T=(0,V.useMemo)(()=>w?YJ({id:w,type:`collection`}):null,[w]),E=tY({noteId:w,stamps:T?.stamps??[]}),D=l$(u?.slug),O=(0,V.useMemo)(()=>({efforts:D.efforts.map(e=>({id:e.slug,title:e.label,to:cj(e.slug)})),related:D.usedBy.map(e=>({id:e.noteId,title:e.title,to:KJ(e.noteId)})),backlinks:E.backlinks}),[D,E.backlinks]);(0,V.useEffect)(()=>{u&&(window.document.title=`Wod.Wiki - ${u.label}`)},[u]);let k=(0,V.useCallback)(async()=>{if(u)try{let e=await p();e&&(n(ij(e.slug)),Z({title:`Cloned`,description:`Created a custom copy of "${u.label}". You can now edit it.`}))}catch(e){Z({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[p,u,n]);if(!a||l)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(b){let t=(0,H.jsx)(nR,{primary:(0,H.jsx)(W,{onClick:C,"data-testid":sB.EQUIPMENT_CREATE_BTN,children:`Create Equipment`}),children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Cancel`})});return(0,H.jsx)(`div`,{"data-testid":sB.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:e&&e!==`new`?`New equipment: ${e}`:`New equipment`,actions:t,editor:(0,H.jsx)(`div`,{className:`relative`,"data-testid":`equipment-create-editor`,children:(0,H.jsx)(sK,{value:x,onChange:S,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y})})})})}if(m)return(0,H.jsxs)(`div`,{"data-testid":sB.EQUIPMENT_LOAD_ERROR,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Equipment could not be loaded`}),(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:m})]}),(0,H.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Back to Equipment`})})]});if(f||!u)return(0,H.jsxs)(`div`,{"data-testid":sB.EQUIPMENT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Equipment “`,e,`” not found`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No equipment definition exists for this slug yet. You can create a new definition page for it.`})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,H.jsx)(W,{onClick:()=>n(`${ij(e??`new`)}?mode=create`),"data-testid":sB.EQUIPMENT_NOT_FOUND_CREATE_BTN,children:`Create Equipment Page`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Back to Equipment`})]})]});let A=(0,H.jsxs)(nR,{primary:d?void 0:(0,H.jsxs)(W,{variant:`outline`,onClick:k,"data-testid":sB.EQUIPMENT_DETAIL_CLONE_BTN,children:[(0,H.jsx)(Se,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,H.jsx)(W,{variant:`ghost`,size:`icon`,onClick:()=>Uz()?n(-1):n(Q.equipment),"aria-label":`Back to Equipment`,title:Uz()?`Back`:`Back to Equipment`,children:(0,H.jsx)(M,{className:`size-4`})}),(0,H.jsx)(XQ,{"data-testid":sB.EQUIPMENT_DETAIL_SOURCE,variant:u.registrySource===`bundled`?`secondary`:`default`,children:u.registrySource===`bundled`?`Bundled`:`Custom`})]});return(0,H.jsx)(`div`,{"data-testid":sB.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:u.label,titleTestId:sB.EQUIPMENT_DETAIL_LABEL,actions:A,editor:(0,H.jsxs)(`div`,{className:`relative`,"data-testid":sB.EQUIPMENT_DETAIL_NOTEBOOK_EDITOR,children:[(0,H.jsx)(sK,{noteId:w,value:s,onChange:c,onCursorPositionChange:h,onBlur:g,onSaveRequest:_,onCommitChange:_,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y}),(0,H.jsx)(nY,{data:O,up:T?.up,relatedLabel:`Used in`})]})})})}var d$=`h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`;function f$({open:e,onOpenChange:t,entry:n,mode:r,provider:i,onSaved:a,onCloned:o}){let[s,c]=(0,V.useState)(``),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)([]),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(null),y=(0,V.useRef)(!1),b=n.id,x=n.journalDate,S=n.slug,C=n.sourceId;(0,V.useEffect)(()=>{e&&(c(x??(r===`clone`?Vj():``)),u(r===`clone`?``:S??``),f(C??``),v(null))},[e,r,b,x,S,C]),(0,V.useEffect)(()=>{if(!e||r!==`relationships`)return;let t=!1;return i.getEntries().then(e=>{t||m(e.filter(e=>e.id!==n.id&&!e.catalog))}).catch(()=>{}),()=>{t=!0}},[e,r,i,n.id]);let w=r===`clone`,T=`note-placement-sources-${n.id}`,E=()=>{y.current||t(!1)};return(0,H.jsx)(lS,{open:e,onClose:E,title:w?`Clone note`:`Note relationships`,description:w?`Independent copy. Results and attachments are not copied.`:void 0,presentation:`sheet`,footer:(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(W,{type:`button`,variant:`outline`,size:`lg`,onClick:E,disabled:h,children:`Cancel`}),(0,H.jsx)(W,{type:`submit`,form:`note-placement-form`,size:`lg`,disabled:h,children:h?`Saving…`:w?`Clone`:`Save`})]}),children:(0,H.jsxs)(`form`,{id:`note-placement-form`,onSubmit:async e=>{if(e.preventDefault(),!y.current){y.current=!0,g(!0),v(null);try{let e=s.trim(),r=l.trim(),c=d.trim(),u=e===``?null:Uj(e);if(e&&!u){v(`Enter a valid date (YYYY-MM-DD).`);return}if(w){if(!e&&!r){v(`Choose a destination date or named page for the clone.`);return}let i=await Kj.create({journalDate:e||void 0,slug:r||void 0,title:n.title,rawContent:n.rawContent,tags:n.tags,sourceId:n.id,type:`journal`});o?.(i),t(!1);return}let f={};if(c!==(C??``)){if(c===``)f.sourceId=null;else try{let e=await Kj.resolve(c);if(!e||e.id===n.id)throw Error(`invalid source`);f.sourceId=e.id}catch{v(`Source note not found.`);return}}if(e!==(x??``)&&(f.journalDate=e===``?null:e,u&&(f.targetDate=u.date.getTime())),r!==(S??``)&&(f.slug=r===``?null:r),Object.keys(f).length===0){t(!1);return}let p=await i.updateEntry(n.id,f);a?.(p),t(!1)}catch{v(`Could not save — your fields are kept. Try again.`)}finally{y.current=!1,g(!1)}}},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-date`,className:`text-sm font-medium`,children:`Journal date`}),(0,H.jsx)(`input`,{id:`note-placement-date`,type:`date`,className:d$,value:s,onChange:e=>c(e.target.value),disabled:h}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:w?`Defaults to the note’s date.`:`Leave empty to detach from the calendar.`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-slug`,className:`text-sm font-medium`,children:`Named page`}),(0,H.jsx)(`input`,{id:`note-placement-slug`,type:`text`,className:d$,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. marathon-block`,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Optional /p/<slug> link. Typing an existing page's slug shares that page with its notes — it does not create a unique copy.`})]}),w?null:(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-source`,className:`text-sm font-medium`,children:`Source note`}),(0,H.jsx)(`input`,{id:`note-placement-source`,type:`text`,className:d$,value:d,onChange:e=>f(e.target.value),list:T,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,H.jsx)(`datalist`,{id:T,children:p.map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.title||`Untitled`},e.id))}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Leave empty to clear.`})]}),_&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:_})]})})}var p$=new ID;function m$({noteId:e,theme:t}){let n=Sn(),r=mt(),[i]=Ct(),[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(!1),l=(0,V.useRef)(0),u=(0,V.useRef)(null),d=(0,V.useRef)(async()=>{}),f=r.pathname.startsWith(`/p/`)||a!==null&&!Ca(a),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(null),y=qK();(0,V.useEffect)(()=>{GF().catch(()=>{})},[e]),(0,V.useEffect)(()=>{let t=!1;return o(null),c(!1),m(null),p$.getEntry(e).then(e=>{if(!t){if(!e){c(!0);return}o(e),l.current=e.sourceRevision??0,u.current={rawContent:e.rawContent,blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}}}).catch(()=>{t||c(!0)}),()=>{t=!0}},[e,i]);let b=a?.sourceId;(0,V.useEffect)(()=>{if(v(null),!b)return;let e=!1;return p$.getEntry(b).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[b]);let x=(0,V.useMemo)(()=>a?YJ(a):{zone:null,up:null,stamps:[]},[a]);gA(x.zone);let[S,w]=(0,V.useState)([]),[T,E]=(0,V.useState)([]),D=a?.id;(0,V.useEffect)(()=>{if(E([]),w([]),!D)return;let e=!1,t=()=>{X.getSessionsForNote(D).then(t=>{e||E(t)}).catch(()=>{})};t();let n=xV(n=>{!e&&n.noteId===D&&t()});return()=>{e=!0,n()}},[D]);let O=(0,V.useCallback)(async t=>{if(a)try{await d.current();let e=u.current;if(!e)throw Error(`The note draft is unavailable.`);let r=C(),i=await hF({noteId:a.id,rawContent:e.rawContent,blocks:e.blocks,expectedSourceRevision:l.current},t,r);l.current=i.note.sourceRevision,VJ.set(r,{block:i.block,noteId:a.id,captured:i,returnTo:qA(a.id)}),n(QA(r))}catch(t){m({noteId:e,message:`Workout not started. ${t instanceof Error?t.message:String(t)} Your draft is kept.`})}},[a,e,n]);WJ({content:a?.rawContent??``,scriptBlocks:S,onStartWorkout:O,results:T});let k=tY(a?{noteId:a.id,stamps:x.stamps}:{noteId:``,stamps:[]}),A=(0,V.useCallback)(e=>{l.current=e.sourceRevision;let t=u.current,n=t?.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));o(t=>t&&{...t,...n?{blocks:e.blocks}:{},sourceRevision:e.sourceRevision})},[]),j=(0,V.useCallback)(async t=>{let n=await Nj.saveNote({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:l.current});return A({rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??l.current}),m(null),o(e=>e?.id===n.id?{...e,title:n.title}:e),{rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0}},[e,A]),{onChange:M,onBlur:N,onLineChange:P,flush:F}=RJ({onSave:async e=>{await j(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])]),onError:t=>m({noteId:e,message:`Save failed. ${t instanceof Error?t.message:String(t)} Your draft is kept. Retry saving.`})});d.current=F;let I=(0,V.useCallback)(e=>{let t=u.current?.rawContent!==e.rawContent||JSON.stringify(Object.values(u.current?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));u.current=e,t&&M(e)},[M]),ee=(0,V.useCallback)(e=>{o(t=>t&&{...t,rawContent:e})},[]),te=(0,V.useCallback)(async e=>{await F();let t=u.current;if(!t)throw Error(`The note draft is unavailable.`);let n=KP({...t,sourceRevision:l.current},e),r=await j(n);u.current=r,o(e=>e&&{...e,...r})},[F,j]),ne=(0,V.useCallback)(()=>Promise.resolve(),[]),re;if(s)re=(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 text-zinc-400`,children:[(0,H.jsx)(`p`,{children:`Note not found.`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(-1),children:`Go back`})]});else if(!a)re=(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`});else{let r=`inline-flex min-h-11 items-center gap-1 rounded-pill border border-border bg-card px-2.5 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,i=(0,H.jsxs)(nR,{label:`Note actions`,children:[(0,H.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`relationships`),children:[(0,H.jsx)(dt,{className:`size-3.5`,"aria-hidden":`true`}),`Note relationships`]}),(0,H.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`clone`),children:[(0,H.jsx)(nt,{className:`size-3.5`,"aria-hidden":`true`}),`Clone`]})]});re=(0,H.jsxs)(TF,{notePersistence:Nj,provider:p$,children:[(0,H.jsx)(fL,{title:a.title,subtitle:qA(a.id),actions:i,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4 px-4 py-6 sm:px-6 min-w-0 max-w-full`,children:[(0,H.jsx)(nY,{data:k,up:x.up}),(a.journalDate||a.slug||a.sourceId)&&(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[a.journalDate&&(0,H.jsx)(Wn,{to:GA(a.journalDate),className:`underline-offset-2 hover:underline`,children:a.journalDate}),a.slug&&(0,H.jsxs)(Wn,{to:tj(a.slug),className:`underline-offset-2 hover:underline`,children:[`/p/`,a.slug]}),a.sourceId&&(0,H.jsxs)(`span`,{children:[`Cloned from`,` `,_?(0,H.jsx)(Wn,{to:qA(_.id),className:`underline-offset-2 hover:underline`,children:_.title||_.id}):(()=>{let e=XJ(a.sourceId);return e?(0,H.jsx)(Wn,{to:e.to,className:`underline-offset-2 hover:underline`,children:e.title}):a.sourceId})()]})]}),y?(0,H.jsx)(`div`,{className:`rounded-lg border border-border bg-card p-4 shadow-sm min-h-[240px] focus-within:border-accent/80 transition-colors`,children:(0,H.jsx)(sK,{value:a.rawContent,onChange:ee,onBlur:N,noteId:a.id,noteBlocks:a.blocks,sourceRevision:a.sourceRevision,onIdentityChange:I,onSaved:A,beforeRun:async()=>(await F(),l.current),onSaveRequest:F,onCommitChange:F,onCursorPositionChange:P,readonly:f,theme:t,showLineNumbers:!1,onCompleteWorkout:ne,onBlocksChange:w,placeholder:`Write workout or notes here…`})}):(0,H.jsx)(`div`,{className:`flex items-center justify-center text-zinc-400 text-sm py-8`,children:`Loading…`}),(0,H.jsx)(qP,{noteId:a.id,blocks:a.blocks,sourceRevision:a.sourceRevision,onRevert:f?void 0:te}),p?.noteId===e&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p.message})]})}),h!==null&&(0,H.jsx)(f$,{open:!0,onOpenChange:e=>{e||g(null)},entry:a,mode:h,provider:p$,onSaved:e=>o(t=>t&&t.id===e.id?{...t,journalDate:e.journalDate,slug:e.slug,sourceId:e.sourceId}:t),onCloned:e=>n(`${qA(e.id)}?edit=1`)})]})}return re}var h$=new ID;function g$(e){let t=new Map;for(let n of e){let e=n.tags[0]?.toLowerCase()??`untagged`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`day-group-${e}`,label:e===`untagged`?`Untagged`:`#${e}`,entries:t}))}function _$(e){return Bj(new Date(e.targetDate))}function v$({slug:e,date:t}){let[n,r]=(0,V.useState)(null);(0,V.useEffect)(()=>{let n=!1;return h$.getEntries().then(i=>{if(n)return;let a=i.filter(n=>n.catalog===e&&_$(n)===t);r(a.sort((e,t)=>t.createdAt-e.createdAt))}).catch(()=>{n||r([])}),()=>{n=!0}},[e,t]);let i=(0,V.useMemo)(()=>n?g$(n):[],[n]),{setL3Items:a}=hA();(0,V.useEffect)(()=>{if(i.length===0){a([]);return}let e=i.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return a(e),()=>a([])},[i,a]);let o=n===null?(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`}):n.length===0?(0,H.jsxs)(`p`,{className:`rounded-lg border border-dashed border-border p-6 text-sm text-muted-foreground`,children:[`No notes in this collection for `,t,`.`]}):(0,H.jsx)(`div`,{className:`flex flex-col gap-6`,children:i.map(e=>(0,H.jsxs)(`section`,{id:e.id,className:`flex flex-col rounded-lg border border-border overflow-hidden`,children:[(0,H.jsxs)(`h3`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[e.label,` · `,e.entries.length]}),(0,H.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:e.entries.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(Wn,{to:qA(e.id),className:`flex flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:new Date(e.createdAt).toLocaleTimeString()})]})},e.id))})]},e.id))});return(0,H.jsx)(fL,{title:t,subtitle:e,editor:(0,H.jsx)(`div`,{className:`flex flex-col gap-6 px-4 py-6 sm:px-6`,children:o})})}var y$=`__new__`;function b$(e){return e.open?(0,H.jsx)(x$,{...e},e.subsetQuery??`(whole-store)`):null}function x$({onOpenChange:e,initialQuery:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a}){let o=Sn(),{items:s,loading:c}=Lj(),l=s.filter(e=>e.editable),[u,d]=(0,V.useState)(l[0]?.slug??y$),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(null),g=()=>e(!1);return(0,H.jsx)(wX,{open:!0,onClose:g,mode:`add`,initialWql:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a,onApply:async e=>{h(null);let t={title:e.title,question:e.question,type:e.type,spanCols:e.spanCols,spanFull:e.spanFull,wql:e.wql,attributes:e.attributes};try{if(u===y$){let e=f.trim()||`New Dashboard`,n=await Jj.createDashboard(e);await Kj.update(n,b_(n.rawContent,t)),g(),o(sj(f_(e)))}else{let e=await Kj.resolve(u);await Kj.update(e,b_(e.rawContent,t)),g(),o(sj(u))}}catch(e){let t=e instanceof Error?e.message:String(e);throw h(t),e}},applyLabel:`Add to dashboard`,destination:(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Destination`}),c?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading dashboards…`}):(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[l.map(e=>(0,H.jsx)(`button`,{type:`button`,"aria-pressed":u===e.slug,onClick:()=>d(e.slug),className:`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===e.slug?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.title},e.slug)),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-dest-new`,"aria-pressed":u===y$,onClick:()=>d(y$),className:`flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===y$?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,H.jsx)(Kt,{className:`size-3`}),` New dashboard`]})]}),u===y$&&(0,H.jsx)(`input`,{type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`New Dashboard`,"data-testid":`dashboard-new-title`,className:`w-full sm:w-64 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),m&&(0,H.jsxs)(`p`,{role:`alert`,"data-testid":`dashboard-save-error`,className:`mt-2 text-xs text-destructive font-mono`,children:[`Could not save: `,m]})]})})}function S$({catalog:e}){let[t,n]=(0,V.useState)([]),[r,i]=(0,V.useState)(!1),[a,o]=(0,V.useState)(``);return(0,V.useEffect)(()=>{let t=!1,r=()=>{e.listByPrefix(a,50).then(e=>{t||n(e)}).catch(()=>{})};r();let i=e.onChange?.(()=>r());return()=>{t=!0,i?.()}},[e,a]),(0,H.jsxs)(`section`,{className:`rounded-lg border p-3 text-sm`,"data-testid":`available-fields`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`flex w-full items-center justify-between font-medium`,onClick:()=>i(e=>!e),children:[(0,H.jsxs)(`span`,{children:[`Available fields (`,t.length,`)`]}),(0,H.jsx)(`span`,{"aria-hidden":!0,children:r?`▾`:`▸`})]}),r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`input`,{className:`mt-2 w-full rounded border px-2 py-1`,placeholder:`Filter fields…`,value:a,onChange:e=>o(e.target.value)}),(0,H.jsxs)(`ul`,{className:`mt-2 max-h-64 space-y-1 overflow-auto`,children:[t.map(e=>(0,H.jsxs)(`li`,{className:`flex items-baseline justify-between gap-2`,children:[(0,H.jsx)(`span`,{className:`font-mono`,children:e.path}),(0,H.jsxs)(`span`,{className:`text-xs opacity-70`,children:[e.kind,e.dimension?` · ${e.dimension}`:``,e.units.length?` · ${e.units.join(`/`)}`:``,e.spellings.length&&e.spellings[0]!==e.path?` · “${e.spellings[0]}”`:``]})]},e.id)),t.length===0&&(0,H.jsx)(`li`,{className:`opacity-60`,children:`No discovered fields for this prefix.`})]})]})]})}function C$(e){return{id:e.id,path:e.path,kind:e.kind,...e.dimension?{dimension:e.dimension}:{},units:Object.keys(e.units??{}),spellings:Object.keys(e.spellings??{})}}var w$=new class{storageInstance;listeners=new Set;constructor(e=xD){this.storageInstance=e}async listByPrefix(e,t=20){let n=e&&typeof IDBKeyRange<`u`?IDBKeyRange.bound(e,`${e}\uFFFF`,!1,!0):void 0;return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,n,t)).map(C$)}async lookup(e){return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,e)).map(C$)}async listValues(e,t,n=20){let r=await this.lookup(e),i=[];for(let e of r){if(i.length>=n)break;let r=t&&typeof IDBKeyRange<`u`?IDBKeyRange.bound([e.id,t],[e.id,`${t}\uFFFF`],!1,!0):void 0,a=await this.storageInstance.readonly(`field_values`).getAllFromIndex(`by-field`,r,n-i.length);for(let e of a)i.push({fieldId:e.fieldId,value:e.value})}return i}notifyChanged(){for(let e of this.listeners)e()}observeStore(e){}}(xD);function T$({label:e,value:t,className:n}){return(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 rounded border border-border bg-background/60 px-2 py-1`,children:[(0,H.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground`,children:e}),(0,H.jsx)(`span`,{className:U(`font-mono text-xs`,n??`text-foreground`),children:t})]})}function E$(e){return e.kind===`relative`?`last ${e.size}${e.unit}`:e.end?`from ${e.start} to ${e.end}`:`from ${e.start}`}function D$({parsed:e}){if(e.error)return(0,H.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:e.error});if(rm(e)){let t=e.source.kind===`dataset`?(0,H.jsx)(T$,{label:`source`,value:e.source.name,className:`text-blue-400 dark:text-blue-300`}):(0,H.jsx)(T$,{label:`source`,value:`target`in e.source.query?`:${e.source.query.target}`:`:${e.source.query.agg}`,className:`text-blue-400 dark:text-blue-300`});return(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t,e.transforms.map((e,t)=>(0,H.jsx)(T$,{label:`fn ${t+1}`,value:`${e.agg}:${e.metric}`,className:`text-green-400 dark:text-green-300`},t)),e.sink&&(0,H.jsx)(T$,{label:`sink`,value:`:${e.sink.head}`,className:`text-purple-400 dark:text-purple-300`})]})}let t=e.window&&(0,H.jsx)(T$,{label:`window`,value:E$(e.window),className:`text-sky-400 dark:text-sky-300`}),n=e.filters.map((e,t)=>(0,H.jsx)(T$,{label:e.negate?`exclude`:`filter`,value:`${e.key}:${e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`)}`,className:`text-amber-400 dark:text-amber-300`},t));return nm(e)?(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,H.jsx)(T$,{label:`aggregate`,value:e.agg,className:`text-blue-400 dark:text-blue-300`}),(0,H.jsx)(T$,{label:`metric`,value:e.metric}),n,e.groupBy.map((e,t)=>(0,H.jsx)(T$,{label:`group by`,value:e,className:`text-green-400 dark:text-green-300`},t)),e.rollup&&(0,H.jsx)(T$,{label:`rollup`,value:`${e.rollup.size}${e.rollup.unit}`,className:`text-purple-400 dark:text-purple-300`}),e.displayUnit&&(0,H.jsx)(T$,{label:`in`,value:e.displayUnit,className:`text-pink-400 dark:text-pink-300`}),t,e.join&&(0,H.jsx)(T$,{label:`where`,value:`:${e.join.target}`,className:`text-teal-400 dark:text-teal-300`})]}):tm(e)?(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,H.jsx)(T$,{label:`target`,value:e.target,className:`text-blue-400 dark:text-blue-300`}),n,t,e.join&&(0,H.jsx)(T$,{label:`where`,value:`${e.join.agg}:${e.join.metric}`,className:`text-teal-400 dark:text-teal-300`})]}):null}function O$({result:e}){let{parsed:t,stages:n}=e;if(t.error)return null;let r=t.groupBy.find(e=>e===`day`||e===`week`),i=r?`by ${r}`:t.rollup?`rollup ${t.rollup.size}${t.rollup.unit}`:`no rollup`,a=t.groupBy.length?`by {${t.groupBy.join(`, `)}}`:`single series`,o=[{n:1,name:`SELECT`,desc:`tag + time index scan`,count:n.selected,unit:`points`},{n:2,name:`BUCKET`,desc:i,count:n.buckets,unit:`buckets`},{n:3,name:`AGGREGATE`,desc:`${t.agg} per bucket`,count:n.aggregated,unit:`values`},{n:4,name:`GROUP`,desc:a,count:n.groups,unit:`series`}];return(0,H.jsx)(`div`,{className:`flex items-center gap-0 mt-4 overflow-x-auto`,children:o.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex items-center`,children:[(0,H.jsxs)(`div`,{className:`border border-border rounded-lg bg-background/60 px-3 py-2 min-w-[130px]`,children:[(0,H.jsxs)(`div`,{className:`text-[10px] font-bold tracking-wide`,style:{color:qb[t%qb.length]},children:[e.n,`. `,e.name]}),(0,H.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:e.desc}),(0,H.jsxs)(`div`,{className:`text-sm font-semibold tabular-nums mt-0.5`,children:[e.count.toLocaleString(),` `,(0,H.jsx)(`span`,{className:`text-[10px] font-normal text-muted-foreground`,children:e.unit})]})]}),t<3&&(0,H.jsx)(Vn,{size:16,className:`text-muted-foreground mx-1 shrink-0`})]},e.n))})}function k$({matched:e,displayUnit:t}){let[n,r]=(0,V.useState)(!1);if(e.length===0)return null;let i=e=>{let t=[];return e.effortSlug&&t.push(`effort:${e.effortSlug}`),e.discipline&&t.push(`discipline:${e.discipline}`),e.intensityTier&&t.push(`intensity:${e.intensityTier}`),e.origin&&t.push(`origin:${e.origin}`),t},a=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};return(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg mt-3`,children:[(0,H.jsxs)(`button`,{onClick:()=>r(!n),className:`w-full flex items-center gap-2 px-4 py-2.5 text-sm text-muted-foreground hover:text-foreground`,children:[n?(0,H.jsx)(un,{size:14}):(0,H.jsx)(Vn,{size:14}),`Raw metric points behind this query (`,e.length,`)`,(0,H.jsx)(`span`,{className:`text-[11px] ml-auto`,children:`one row per fact from the analytics store`})]}),n&&(0,H.jsxs)(`div`,{className:`px-4 pb-3 overflow-x-auto`,children:[(0,H.jsxs)(`table`,{className:`w-full text-[11px] font-mono`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`text-muted-foreground text-left border-b border-border`,children:[(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`ts`}),(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`metric`}),(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`value`}),(0,H.jsx)(`th`,{className:`py-1.5 font-normal`,children:`tags`})]})}),(0,H.jsx)(`tbody`,{children:e.slice(0,12).map(e=>{let n=e.unit??e.metricUnit,r=typeof e.value==`number`?e.value:void 0,o=t&&r!==void 0&&n&&Eh(n)===Eh(t)?Th(r,n,t):void 0;return(0,H.jsxs)(`tr`,{className:`border-b border-border/40`,children:[(0,H.jsx)(`td`,{className:`py-1.5 pr-4 text-muted-foreground whitespace-nowrap`,children:a(e.timestamp)}),(0,H.jsx)(`td`,{className:`py-1.5 pr-4 text-primary whitespace-nowrap`,children:e.metricKey}),(0,H.jsxs)(`td`,{className:`py-1.5 pr-4 tabular-nums`,children:[String(e.value),n?` ${n}`:``,o!==void 0&&n!==t?` → ${o.toLocaleString()} ${t}`:``]}),(0,H.jsx)(`td`,{className:`py-1.5 text-muted-foreground`,children:i(e).map(e=>(0,H.jsx)(`span`,{className:`inline-block bg-background/80 rounded px-1.5 py-0.5 mr-1 mb-0.5`,children:e},e))})]},e.id)})})]}),e.length>12&&(0,H.jsxs)(`div`,{className:`text-[11px] text-muted-foreground pt-2`,children:[`… `,e.length-12,` more points`]})]})]})}var A$=[`totalVolume`,`tis`,`sessionLoad`,`totalReps`],j$=[`effort`,`discipline`,`intensity`,`tags`,`note`,`origin`];function M$(){let[e,t]=(0,V.useState)(A$);return(0,V.useEffect)(()=>{let e=!1;async function n(){try{let n=Date.now(),r=n-31536e6,i=await XF.getFactsByTimeRange(r,n);if(e)return;let a=new Set([...A$,...i.map(e=>e.metricKey)].filter(e=>e!==void 0));t(Array.from(a).sort())}catch{}}return n(),()=>{e=!0}},[]),{metricKeys:e,tagKeys:j$}}var N$=[4,8,16],P$=`sum:totalVolume{}`;function F$(e){let t=Number.parseInt(e??``,10);return N$.includes(t)?t:16}function I$(e={}){let{defaultQuery:t=P$,runOnLanding:n=!1}=e,[r,i]=Ct(),a=r.get(`q`)??``,o=F$(r.get(`weeks`)),[s,c]=(0,V.useState)(()=>a&&!Y(a).error?a:t),[l,u]=(0,V.useState)(a||(n?t:``)),d=(0,V.useRef)(s);d.current=s;let f=(0,V.useRef)(r);f.current=r;let p=(0,V.useRef)(!0),m=(0,V.useRef)(a);m.current=a;let h=(0,V.useRef)(a);return(0,V.useEffect)(()=>{a!==h.current&&(h.current=a,d.current!==a&&(p.current=!0,c(a&&!Y(a).error?a:t),u(a||(n?t:``))))},[a,t,n]),{draft:s,setDraft:(0,V.useCallback)(e=>{if(e===d.current)return;let t=new URLSearchParams(f.current);t.set(`q`,e),i(t,{replace:!p.current}),p.current=!1,c(e)},[i]),submitted:l,submit:(0,V.useCallback)(e=>{let t=e??d.current;if(Y(t).error)return;if(p.current&&m.current===t){u(t);return}let n=new URLSearchParams(f.current);n.set(`q`,t),i(n,{replace:!0}),p.current=!0,u(t)},[i]),weeks:o,setWeeks:(0,V.useCallback)(e=>{let t=new URLSearchParams(f.current);t.set(`weeks`,String(e)),i(t,{replace:!0})},[i])}}function L$({weeks:e,onWeeks:t,unitForced:n}){let[r,i]=(0,V.useState)(!1),a=(0,V.useRef)(null),{unit:o,setUnit:s}=jx();(0,V.useEffect)(()=>{if(!r)return;let e=e=>{a.current?.contains(e.target)||i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]);let c=e=>()=>{e(),i(!1)};return(0,H.jsxs)(`div`,{ref:a,className:`relative`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"data-testid":`explorer-options`,"aria-expanded":r,className:U(`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors`,r?`border-primary/60 text-primary bg-primary/10`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:[(0,H.jsx)(Zt,{className:`size-3.5`}),`Options`,(0,H.jsx)(un,{className:U(`size-3 transition-transform`,r&&`rotate-180`)})]}),r&&(0,H.jsxs)(`div`,{className:`absolute right-0 top-full z-40 mt-1 w-72 rounded-xl border border-border bg-card shadow-xl p-1.5`,"data-testid":`explorer-options-menu`,children:[(0,H.jsx)(`div`,{className:`px-2 pt-1.5 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:`Range`}),N$.map(n=>(0,H.jsxs)(`button`,{type:`button`,onClick:c(()=>t(n)),className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs text-foreground hover:bg-muted transition-colors`,children:[(0,H.jsx)(`span`,{className:`w-3.5 text-primary`,children:e===n?(0,H.jsx)(Zn,{className:`size-3.5`}):null}),`Past `,n,` weeks`]},n)),(0,H.jsxs)(`div`,{className:`mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:[`Units`,n?` — pinned by query`:``]}),[`kg`,`lb`].map(e=>(0,H.jsxs)(`button`,{type:`button`,disabled:n,onClick:c(()=>s(e)),className:U(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs transition-colors`,n?`text-muted-foreground/50 cursor-not-allowed`:`text-foreground hover:bg-muted`),children:[(0,H.jsx)(`span`,{className:`w-3.5 text-primary`,children:o===e?(0,H.jsx)(Zn,{className:`size-3.5`}):null}),e]},e))]})]})}var R$=X,z$=`sample`,B$=6048e5;function V$(e){return Math.round(e*10)/10}var H$={thruster:`high`,"pull-up":`high`,"push-up":`moderate`,"air-squat":`moderate`,"double-under":`high`,"sit-up":`low`,rowing:`moderate`,running:`moderate`,"recovery-run":`low`,"back-squat":`high`,deadlift:`high`},U$={fran:`high`,cindy:`moderate`,annie:`moderate`,rowing:`moderate`,running:`moderate`,strength:`high`,recoveryRun:`low`};function W$(e,t,n,r){return{effortSlug:n,discipline:r,reps:e,loadLbs:t,tisSeconds:V$(e*(n===`thruster`?2.2:1.6))}}function G$(e,t,n){let r=330-n*16,i=Math.max(180,V$(r+(Math.random()-.5)*20)),a=95+n*5;return{noteId:`sample-fran-${t}-${crypto.randomUUID()}`,title:`Sample — Fran (week ${16-t})`,workoutType:`fran`,timestamp:e-t*B$,durationSeconds:i,movements:[W$(45,a,`thruster`,`strength`),W$(45,0,`pull-up`,`gymnastics`)]}}function K$(e,t,n){let r=10+n+Math.round((Math.random()-.5)*2),i=Math.max(8,r);return{noteId:`sample-cindy-${t}-${crypto.randomUUID()}`,title:`Sample — Cindy (week ${16-t})`,workoutType:`cindy`,timestamp:e-t*B$,durationSeconds:1200,movements:[{effortSlug:`pull-up`,discipline:`gymnastics`,reps:i*5,loadLbs:0,tisSeconds:V$(i*5*1.5)},{effortSlug:`push-up`,discipline:`gymnastics`,reps:i*10,loadLbs:0,tisSeconds:V$(i*10*1.2)},{effortSlug:`air-squat`,discipline:`bodyweight`,reps:i*15,loadLbs:0,tisSeconds:V$(i*15*1.1)}]}}function q$(e,t,n){let r=540-n*22,i=Math.max(360,V$(r+(Math.random()-.5)*30));return{noteId:`sample-annie-${t}-${crypto.randomUUID()}`,title:`Sample — Annie (week ${16-t})`,workoutType:`annie`,timestamp:e-t*B$,durationSeconds:i,movements:[{effortSlug:`double-under`,discipline:`gymnastics`,reps:150,loadLbs:0,tisSeconds:V$(75)},{effortSlug:`sit-up`,discipline:`bodyweight`,reps:150,loadLbs:0,tisSeconds:V$(195)}]}}function J$(e,t,n){let r=135+n*5,i=185+n*5;return{noteId:`sample-strength-${t}-${crypto.randomUUID()}`,title:`Sample — Strength accessory (week ${16-t})`,workoutType:`strength`,timestamp:e-t*B$,durationSeconds:1800,movements:[{effortSlug:`back-squat`,discipline:`strength`,reps:25,loadLbs:r,tisSeconds:V$(62.5)},{effortSlug:`deadlift`,discipline:`strength`,reps:15,loadLbs:i,tisSeconds:V$(42)}]}}function Y$(e,t,n){let r=2e3+n*250,i=V$(r/2+(Math.random()-.5)*30);return{noteId:`sample-rowing-${t}-${crypto.randomUUID()}`,title:`Sample — Rowing (week ${16-t})`,workoutType:`rowing`,timestamp:e-t*B$,durationSeconds:i,movements:[{effortSlug:`rowing`,discipline:`rowing`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function X$(e,t,n){let r=5e3+n*500,i=V$(r/2.8+(Math.random()-.5)*60);return{noteId:`sample-running-${t}-${crypto.randomUUID()}`,title:`Sample — Running (week ${16-t})`,workoutType:`running`,timestamp:e-t*B$,durationSeconds:i,movements:[{effortSlug:`running`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function Z$(e,t,n){let r=3e3+n*50,i=V$(r/2.2+(Math.random()-.5)*60);return{noteId:`sample-recovery-run-${t}-${crypto.randomUUID()}`,title:`Sample — Recovery run (week ${16-t})`,workoutType:`recoveryRun`,timestamp:e-t*B$,durationSeconds:i,movements:[{effortSlug:`recovery-run`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function Q$(e){let t=[];for(let n=0;n<16;n++){let r=Math.floor(n/4);t.push(J$(e,n,n)),n%4==0?t.push(G$(e,n,r)):n%4==1?t.push(K$(e,n,r)):n%4==2?t.push(q$(e,n,r)):n===3||n===11?t.push(Y$(e,n,r)):(n===7||n===15)&&t.push(X$(e,n,r)),t.push(Z$(e,n,n))}return t.sort((e,t)=>e.timestamp-t.timestamp)}function $$(e){let t=e.timestamp,n=U$[e.workoutType],r=e.movements.reduce((e,t)=>e+t.reps,0),i=e.movements.reduce((e,t)=>e+t.reps*t.loadLbs,0),a=e.movements.reduce((e,t)=>e+t.tisSeconds,0),o=e.movements.reduce((e,t)=>e+(t.distanceMeters??0),0),s=V$(i/100+r+e.durationSeconds/10),c=[],l=(e,n,r,i,a)=>{let o={canonicalKey:i};a?.effortSlug&&(o.effortSlug=a.effortSlug),a?.discipline&&(o.effortDiscipline=a.discipline),a?.intensityTier&&(o.effortIntensityTier=a.intensityTier);let s={id:c.length,outputType:`analytics`,timeSpan:{started:t},metrics:[{type:G.Label,value:e,origin:`analyzed`},{type:G.Metric,value:n,unit:r,metadata:o,origin:`analyzed`}],sourceBlockKey:``,stackLevel:0};c.push(s)};if(l(`Elapsed time`,e.durationSeconds,`s`,`elapsed`,{intensityTier:n}),l(`Total reps`,r,`reps`,`totalReps`,{intensityTier:n}),l(`Time in motion`,V$(a),`s`,`tis`,{intensityTier:n}),i>0&&l(`Total volume`,V$(i),`lb`,`totalVolume`,{intensityTier:n}),o>0){let t=e.movements.find(e=>e.distanceMeters&&e.distanceMeters>0)?.discipline;l(`Total distance`,V$(o),`m`,`totalDistance`,{discipline:t,intensityTier:n})}l(`Session load`,s,`AU`,`sessionLoad`,{intensityTier:n});for(let t of e.movements){let e=t.reps*t.loadLbs,n=H$[t.effortSlug]??`moderate`,r={effortSlug:t.effortSlug,discipline:t.discipline,intensityTier:n};l(`Total reps`,t.reps,`reps`,`totalReps`,r),l(`Time in motion`,t.tisSeconds,`s`,`tis`,r),e>0&&l(`Total volume`,V$(e),`lb`,`totalVolume`,r),l(`Session load`,V$(e/100+t.reps+t.tisSeconds/10),`AU`,`sessionLoad`,r)}return c}function e1(e,t){let n=`${`sample-${e.noteId}`}-result`,r=e.timestamp,i=r+e.durationSeconds*1e3;return{id:n,noteId:e.noteId,blockId:`sample-block`,blockVersion:1,blockContentId:t,origin:`journal`,status:`completed`,createdAt:Date.now(),startTime:r,endTime:i,duration:e.durationSeconds*1e3,completed:!0}}async function t1(){return(await R$.getTagByLabel(z$))?.id}async function n1(){return(await R$.getNotesForTag(z$)).map(e=>e.id)}async function r1(){let e=await n1();return e.length!==0&&(await R$.scanAll()).some(t=>e.includes(t.noteId))}async function i1(){if(await r1()){let e=await n1();return{facts:(await R$.scanAll()).filter(t=>t.grain===`summary`&&e.includes(t.noteId)).length}}let e=Q$(Date.now()),t=0;for(let n of e){let e=n.movements.map(e=>`${e.distanceMeters?`${e.distanceMeters}m`:e.reps} ${e.effortSlug.replaceAll(`-`,` `)}${e.loadLbs?` ${e.loadLbs}lb`:``}`).join(`
169
- `),r=`# ${n.title}\n\n\`\`\`log\n${e}\n\`\`\`\n`,i=Aa(r,{sourceRevision:1,createId:()=>`sample-block`}),a=$$(n),o=e1(n,va(e)),s={noteId:n.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:n.timestamp};t+=await R$.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`],async e=>{await e.saveNoteSource({noteId:n.noteId,rawContent:r,blocks:i,expectedSourceRevision:0,metadata:{title:n.title},noteType:`playground`,createdAt:n.timestamp}),await e.setNoteTags(n.noteId,[z$]),await e.saveSession(o),await e.appendEvents(sg(a,s));let t=cg(a,s);return await e.finalizeSummaries(o.id,t),t.length})}return{facts:t}}async function a1(){let e=await n1();if(e.length!==0){for(let t of e)await R$.deleteEvents((await R$.getEventsForNote(t)).map(e=>e.id)),await R$.deleteNote(t);if((await R$.getNotesForTag(z$)).length===0){let e=await t1();e&&await R$.deleteTag(e)}}}function o1({result:e,onChanged:t,layout:n=`inline`,refreshKey:r}){let[i,a]=(0,V.useState)(void 0),[o,s]=(0,V.useState)(!1),c=(0,V.useCallback)(async()=>{a(await r1()),s(!1)},[]);(0,V.useEffect)(()=>{c()},[c,r]);let l=async()=>{await i1(),await c(),t?.()},u=(0,H.jsxs)(`div`,{className:`flex items-center justify-center gap-3 rounded-md border border-border bg-muted/50 px-3 py-2 text-xs text-foreground`,children:[(0,H.jsx)(`span`,{children:`Sample data loaded`}),(0,H.jsx)(`button`,{onClick:async()=>{await a1(),await c(),t?.()},className:`font-medium text-destructive hover:text-destructive/80 transition-colors`,children:`Purge sample data`}),(0,H.jsx)(`button`,{onClick:()=>s(!0),className:`text-muted-foreground hover:text-foreground transition-colors`,"aria-label":`Dismiss`,children:(0,H.jsx)(Te,{size:14})})]});if(n===`banner`)return i&&!o?u:null;let d=i?o?null:u:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2`,children:`Facts appear when you log or run workouts.`}),(0,H.jsxs)(`div`,{className:`flex items-center justify-center gap-3`,children:[(0,H.jsx)(`button`,{onClick:l,className:`text-xs font-medium rounded-md bg-primary text-primary-foreground px-3 py-1.5 hover:opacity-90 transition-opacity`,children:`Preview with sample data`}),(0,H.jsx)(Wn,{to:`/collections`,className:`text-xs text-primary underline-offset-2 hover:underline`,children:`Log your first workout`})]})]});return n===`card`?(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-6 flex flex-col items-center justify-center text-sm text-muted-foreground`,children:[e!==void 0&&(0,H.jsx)(Bb,{result:e}),i!==void 0&&d&&(0,H.jsx)(`div`,{className:`mt-3`,children:d})]}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center`,children:[e!==void 0&&(0,H.jsx)(Bb,{result:e}),i!==void 0&&d&&(0,H.jsx)(`div`,{className:`mt-3`,children:d})]})}var s1=`:dashboard{}`,c1=864e5,l1=`agg:metric{filters} by {dims} .rollup(period)`,u1=new Set([`tags`,`catalog`,`text`,`type`,`has`]);function d1(e){let t=e.find(e=>e.key===`source`&&!e.negate);return t?t.values.map(e=>e.value).join(`|`):null}function f1({entries:e,stickyOffset:t,idPrefix:n=``}){return(0,H.jsx)(`div`,{className:`-mx-4`,children:fZ(e,`date`).map(e=>(0,H.jsxs)(`div`,{id:`${n}${e.id}`,className:`flex flex-col`,children:[(0,H.jsx)(oL,{top:t,icon:(0,H.jsx)(qt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,meta:(0,H.jsx)(`span`,{"data-testid":`library-group-count`,className:`font-bold tabular-nums`,children:e.entries.length})}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0 pb-1`,children:e.entries.map(e=>(0,H.jsx)(QZ,{entry:e,dateLabel:e.date?vz(e.date):void 0},e.block?`${e.id}#${e.block.blockId}`:e.id))})]},e.id))})}function p1(e,t){if(e===t)return!0;let n=Y(e),r=Y(t);return!n.error&&!r.error&&Km(n)===Km(r)}function m1({actions:e}){(0,V.useEffect)(()=>{},[]);let t=(0,V.useMemo)(()=>HM(`/dashboards`),[]),{draft:n,setDraft:r,submitted:i,submit:a,weeks:o,setWeeks:s}=I$({defaultQuery:t.defaultWql??s1,runOnLanding:!0}),{unit:c}=jx(),{forced:l}=(0,V.useMemo)(()=>Mx(i,c),[i,c]),[u,d]=(0,V.useState)(void 0),[f,p]=(0,V.useState)(void 0),[m,h]=(0,V.useState)(void 0),[g,_]=(0,V.useState)(void 0),[v,y]=(0,V.useState)(!1),[b,x]=(0,V.useState)(!1),[S,C]=(0,V.useState)(!0),w=M$(),T=t.typeOptions,E=(0,V.useMemo)(()=>Y(n),[n]),D=d1(tm(E)?E.filters:[]),O=tm(E)&&E.window?E$(E.window):null,k=aL(104),A=!E.error&&n.trim().length>0,j=A&&S,M=(0,V.useMemo)(()=>{if(!A)return null;if(tm(E))return n;if(nm(E)&&E.join){let e=E.join;return Km({family:`find`,raw:``,target:e.target,filters:e.filters,window:e.last?{kind:`relative`,size:e.last.size,unit:e.last.unit}:void 0})}return null},[E,n,A]),N=(0,V.useMemo)(()=>{if(!i)return null;let e=Y(i);if(tm(e)||e.error)return null;if(e.join){let t=e.join;return Km({family:`find`,raw:``,target:t.target,filters:t.filters,window:t.last?{kind:`relative`,size:t.last.size,unit:t.last.unit}:void 0})}return Km({family:`find`,raw:``,target:`note`,filters:e.filters.filter(e=>u1.has(e.key)&&!e.negate),window:{kind:`relative`,size:o,unit:`w`}})},[i,o]);(0,V.useEffect)(()=>{if(!N){h(void 0);return}let e=!1;return kI(N).then(t=>{e||h(t)}).catch(()=>{e||h(void 0)}),()=>{e=!0}},[N]);let[P,F]=(0,V.useState)(0),[I,ee]=(0,V.useState)(!1),[te,ne]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=!1;if(!i){d(void 0),p(void 0),_(void 0),y(!1);return}y(!0);let t=Y(i);if(tm(t))d(void 0),t.target===`effort`?XF.runFind(t).then(t=>{e||(_(t.efforts??[]),p([]))}).catch(()=>{e||(_(void 0),p(void 0))}).finally(()=>{e||y(!1)}):kI(i).then(t=>{e||(p(t),_([]))}).catch(()=>{e||(p(void 0),_(void 0))}).finally(()=>{e||y(!1)});else{p(void 0),_(void 0);let t=Date.now(),n=t-o*7*c1;XF.runQuery(i,{rangeStart:n,rangeEnd:t,preferredUnit:c}).then(t=>{e||d(t)}).catch(()=>{e||d(void 0)}).finally(()=>{e||y(!1)})}return()=>{e=!0}},[i,o,P,c]);let re=zb(u),ie=e=>{let t=VZ(n,e);r(t),a(t)},{setL3Items:ae}=hA(),oe=(0,V.useMemo)(()=>f!==void 0&&f.length>0?fZ(f,`date`):[],[f]);(0,V.useEffect)(()=>{if(oe.length===0){ae([]);return}let e=oe.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return ae(e),()=>ae([])},[oe,ae]);let se=Yj.find(e=>e.query===i)?.question??`custom query`,ce=(0,V.useMemo)(()=>{let e=Y(i);return e.error?i:Km(e)},[i]),L=u!==void 0&&(p1(u.parsed.raw,n)||u.parsed.raw===i&&n===ce),le=!i||!v&&re.kind===`empty`,ue=(0,H.jsxs)(`button`,{type:`button`,"data-testid":`inspect-pipeline`,"aria-expanded":I,onClick:()=>ee(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[I?(0,H.jsx)(un,{size:12}):(0,H.jsx)(Vn,{size:12}),`Inspect pipeline`]});return(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,children:[(0,H.jsx)(S$,{catalog:w$}),(0,H.jsx)($I,{title:`Metric Explorer`,actions:(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,H.jsx)(L$,{weeks:o,onWeeks:s,unitForced:l}),e]})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-h-0 p-4`,children:[(0,H.jsx)(`div`,{className:`min-w-[280px]`,children:(0,H.jsx)(EC,{query:n,onQueryChange:r,onValidationChange:e=>C(e.valid),onSubmit:e=>a(e),actionLabel:`Run`,preferredChoices:T,showDiagnostics:!1,placeholder:l1,diagnosticsActions:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`save-query`,disabled:!j,onClick:()=>x(!0),title:`Save this query — decide where it lands (dashboard, …)`,className:`flex min-h-12 items-center gap-1.5 rounded-lg border border-primary/40 text-primary px-3 text-[11px] font-semibold hover:bg-primary/10 transition-all shrink-0 disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,H.jsx)(kt,{size:12}),` Save`]})})}),(0,H.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1`,"data-testid":`explorer-meta`,children:[n.trim().length>0&&(0,H.jsx)(`span`,{"data-testid":`draft-validity`,className:`mr-1 inline-flex items-center gap-1 text-[11px]`,children:E.error?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-mono text-red-600`,children:[(0,H.jsx)(gt,{size:11,className:`shrink-0`}),` `,E.error]}):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-green-600`,children:[(0,H.jsx)(yn,{size:11,className:`shrink-0`}),` valid`]})}),w.metricKeys.map(e=>(0,H.jsx)(`button`,{type:`button`,disabled:!j||!nm(E),title:A&&!nm(E)?`Metric shortcuts apply to measure queries — pivot the kind through the composer first`:void 0,onClick:()=>ie(e),className:U(`rounded-full border px-2 py-0.5 text-[11px] font-mono transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,n.includes(e)?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:e},e)),(0,H.jsx)(`span`,{className:`mx-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/50`,children:`filters`}),w.tagKeys.map(e=>(0,H.jsx)(`span`,{className:`rounded-full border border-border/60 px-2 py-0.5 text-[11px] font-mono text-muted-foreground/70`,children:e},e))]}),(0,H.jsx)(`section`,{className:`min-w-0`,children:tm(E)?(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-4`,children:[(0,H.jsxs)(`div`,{className:`text-[11px] uppercase tracking-wider text-muted-foreground mb-2`,children:[`Find `,E.target,D&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`in `,D]}),O&&(0,H.jsx)(`span`,{className:`ml-1`,children:O})]}),E.error?(0,H.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:E.error}):v?(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Searching…`}):g&&g.length>0?(0,H.jsx)(`div`,{className:`flex flex-col divide-y divide-border/50`,children:g.map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-3 py-2.5`,children:[(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground font-mono`,children:e.slug}),e.baseAttributes.discipline&&(0,H.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground`,children:e.baseAttributes.discipline})]},e.slug))}):f&&f.length>0?(0,H.jsx)(f1,{entries:f,stickyOffset:k}):(0,H.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`No `,E.target,`s found.`]})]})}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsx)(o1,{layout:`banner`,refreshKey:P,onChanged:()=>F(e=>e+1)})}),E.error&&i&&(0,H.jsx)(`div`,{"data-testid":`explorer-results-stale`,className:`mt-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs font-medium text-amber-700`,children:`Stale — showing the last run's results; the current draft is invalid and not applied.`}),(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsx)(Ib,{title:`Query result`,question:se,query:i||`(empty)`,children:(0,H.jsx)(`div`,{className:`h-64`,children:i?v?(0,H.jsx)(Bb,{result:void 0}):re.kind===`error`?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-sm text-destructive font-mono px-4 text-center`,children:re.message}):re.kind===`empty`?(0,H.jsxs)(`div`,{className:`h-full flex flex-wrap items-center justify-center gap-6`,children:[(0,H.jsx)(o1,{result:u,refreshKey:P,onChanged:()=>F(e=>e+1)}),ue]}):re.kind===`scalar`?(0,H.jsx)(Vb,{result:u,label:`${u.parsed.agg}(${u.parsed.metric})`}):re.kind===`timeseries`?(0,H.jsx)(Jb,{result:u}):(0,H.jsx)(Yb,{result:u}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-3`,children:[(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Enter a WQL query or choose an example to explore your data.`}),ue]})})})}),i&&(0,H.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[!v&&!le&&ue,N&&m!==void 0&&(0,H.jsxs)(`button`,{type:`button`,"data-testid":`records-toggle`,"aria-expanded":te,onClick:()=>ne(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[te?(0,H.jsx)(un,{size:12}):(0,H.jsx)(Vn,{size:12}),`Records in this calculation`,(0,H.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 tabular-nums`,children:m.length})]})]}),I&&(0,H.jsx)(`div`,{className:`mt-3`,"data-testid":`pipeline-anatomy`,children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(D$,{parsed:L?u.parsed:E}),L&&(0,H.jsx)(O$,{result:u})]}):(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Submit a query to see its anatomy.`})}),te&&N&&m!==void 0&&(0,H.jsxs)(`div`,{className:`mt-3`,children:[(0,H.jsx)(`code`,{className:`block mb-3 rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground`,"data-testid":`records-wql`,children:N}),m.length===0?(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No records match this calculation.`}):(0,H.jsx)(f1,{entries:m,stickyOffset:k,idPrefix:`records-`})]}),u&&(0,H.jsx)(k$,{matched:u.matched,displayUnit:u.unit})]})})]}),(0,H.jsx)(b$,{open:b,onOpenChange:x,initialQuery:n,subsetQuery:M,rangeStart:Date.now()-o*7*c1,rangeEnd:Date.now(),preferredUnit:c})]})}function h1({className:e,...t}){return(0,H.jsx)(E,{"data-slot":`control`,...t,className:U(e,`group relative isolate inline-flex h-6 w-10 cursor-default rounded-full p-[3px] sm:h-5 sm:w-8`,`transition duration-0 ease-in-out data-changing:duration-200`,`forced-colors:outline forced-colors:bg-[Highlight] dark:forced-colors:bg-[Highlight]`,`bg-muted ring-1 ring-black/5 ring-inset dark:bg-white/5 dark:ring-white/15`,`data-checked:bg-primary data-checked:ring-primary/90`,`dark:data-checked:bg-primary dark:data-checked:ring-primary/90`,`focus:not-data-[focus]:outline-hidden data-[focus]:outline-2 data-[focus]:outline-offset-2 data-[focus]:outline-ring`,`data-[hover]:ring-black/15 dark:data-[hover]:ring-white/25 data-[hover]:data-checked:ring-primary/90 dark:data-[hover]:data-checked:ring-primary/90`,`data-[disabled]:bg-muted dark:data-[disabled]:bg-white/15 data-[disabled]:opacity-50 data-[disabled]:data-checked:bg-muted dark:data-[disabled]:data-checked:bg-white/15 data-[disabled]:data-checked:ring-black/5 dark:data-[disabled]:data-checked:ring-white/15`),children:(0,H.jsx)(`span`,{"aria-hidden":`true`,className:U(`pointer-events-none relative inline-block size-4.5 rounded-full sm:size-3.5`,`translate-x-0 transition duration-200 ease-in-out`,`border border-transparent`,`bg-background shadow-sm ring-1 ring-black/5 dark:ring-white/5`,`group-data-checked:bg-primary-foreground group-data-checked:shadow-sm group-data-checked:ring-primary/90`,`group-data-checked:translate-x-4 sm:group-data-checked:translate-x-3`,`group-data-checked:group-data-[disabled]:bg-background group-data-checked:group-data-[disabled]:shadow-sm group-data-checked:group-data-[disabled]:ring-black/5 dark:group-data-checked:group-data-[disabled]:ring-white/5`)})})}var g1=[{id:kA.route,label:`Journal`,profile:kA,shortcuts:!0},{id:jA.route,label:`Notes`,profile:jA,shortcuts:!0},{id:AA.route,label:`Notebooks`,profile:AA},{id:MA.route,label:`Efforts`,profile:MA,shortcuts:!0},{id:PA.route,label:`Sessions`,profile:PA,shortcuts:!0},{id:FA.route,label:`Playgrounds`,profile:FA,shortcuts:!0},{id:`/dashboards`,label:`Dashboards`,systemDefaultWql:`:dashboard{}`},{id:MM,label:`⌘/ Command Palette`}];function _1(e){return{defaultWql:e.defaultWql??``,customType:e.typeOptions!==void 0,typeOptions:e.typeOptions??[],customGroup:e.groupByOptions!==void 0,groupByOptions:e.groupByOptions??[]}}function v1(e){return{defaultWql:e.defaultWql.trim()||void 0,typeOptions:e.customType?e.typeOptions:void 0,groupByOptions:e.customGroup?e.groupByOptions:void 0}}var y1=Object.fromEntries([...mS,...pS].map(e=>[e.value,e.label])),b1=Object.fromEntries(FM.map(e=>[e.id,e.label]));function x1({values:e,choices:t,labels:n,onChange:r,testPrefix:i}){return(0,H.jsxs)(`div`,{className:`space-y-2`,children:[e.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map(t=>(0,H.jsxs)(`span`,{"data-testid":`${i}-chip-${t}`,className:`inline-flex items-center gap-1 rounded-full border border-border/70 bg-muted/40 px-2.5 py-1 text-xs font-medium`,children:[n[t]??t,(0,H.jsx)(`button`,{type:`button`,"aria-label":`Remove ${t}`,"data-testid":`${i}-remove-${t}`,onClick:()=>r(e.filter(e=>e!==t)),className:`text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3`})})]},t))}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.filter(t=>!e.includes(t.value)).map(t=>(0,H.jsxs)(`button`,{type:`button`,"aria-label":`Add ${t.value}`,"data-testid":`${i}-add-${t.value}`,onClick:()=>r([...e,t.value]),className:`rounded-full border border-dashed border-border/70 px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-foreground/40`,children:[`+ `,t.label]},t.value))})]})}function S1({surface:e}){let t=e.profile?.defaultWql??e.systemDefaultWql??`:note{source:journal,feeds} by {date}`,n=e.profile?.target,r=e.profile?.scopeOptions??[],[i,a]=(0,V.useState)(()=>_1(HM(e.id))),[o,s]=(0,V.useState)(()=>HM(e.id)),[c,l]=(0,V.useState)(null),u=(0,V.useMemo)(()=>{let e=i.defaultWql.trim();return e?_C(e).error??null:null},[i.defaultWql]),d=v1(i),f=JSON.stringify(d)!==JSON.stringify(o),p=Object.values(o).some(e=>e!==void 0),m=[...o.invalidTypeOptions??[],...o.invalidGroupByOptions??[]];return(0,H.jsxs)(`div`,{className:`space-y-4 rounded-lg border border-border/60 bg-card/40 p-4`,"data-testid":`query-defaults-card-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:e.id})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Landing default query`}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`System default: `,(0,H.jsx)(`span`,{className:`font-mono`,children:t})]}),(0,H.jsx)(`textarea`,{rows:2,value:i.defaultWql,onChange:e=>a({...i,defaultWql:e.target.value}),placeholder:t,"data-testid":`query-defaults-wql-${e.id}`,className:`w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs focus:outline-none focus:ring-1 focus:ring-primary/40`}),u?(0,H.jsxs)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-defaults-wql-error-${e.id}`,children:[`Couldn't parse — `,u]}):!i.defaultWql.trim()&&(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Empty — the system default is used.`})]}),m.length>0&&(0,H.jsxs)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-defaults-invalid-${e.id}`,children:[`Stored options no longer recognized: `,m.join(`, `),` — remove them; they are never turned into query clauses.`]}),e.profile&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Where-stored options`}),(0,H.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[`Custom`,(0,H.jsx)(h1,{checked:i.customType,onChange:e=>a({...i,customType:e}),"data-testid":`query-defaults-type-custom-${e.id}`})]})]}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`System: target `,n,`, scopes `,r.join(`, `)||`—`]}),i.customType&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(x1,{values:i.typeOptions,choices:n===`note`?mS:[],labels:y1,onChange:e=>a({...i,typeOptions:e}),testPrefix:`query-defaults-type-${e.id}`}),i.typeOptions.length===0&&(0,H.jsx)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-defaults-type-empty-${e.id}`,children:`No predefined options — the route nudges for a pick instead.`})]})]}),e.profile&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Arrange-cards-by options`}),(0,H.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[`Custom`,(0,H.jsx)(h1,{checked:i.customGroup,onChange:e=>a({...i,customGroup:e}),"data-testid":`query-defaults-group-custom-${e.id}`})]})]}),i.customGroup&&(0,H.jsx)(x1,{values:i.groupByOptions,choices:FM.map(e=>({value:e.id,label:e.label})),labels:b1,onChange:e=>a({...i,groupByOptions:e}),testPrefix:`query-defaults-group-${e.id}`})]}),e.shortcuts&&(0,H.jsx)(C1,{surface:e}),c&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-defaults-storage-error-${e.id}`,role:`alert`,children:c}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsx)(W,{size:`sm`,onClick:async()=>{if(!f)return;let t=i.defaultWql.trim();if(!(t&&_C(t).error)){if(!await UM(e.id,d)){l(`Save failed — storage is unavailable; the previous default still stands.`);return}l(null),s(HM(e.id))}},disabled:!f||!!u,"data-testid":`query-defaults-save-${e.id}`,children:`Save`}),p&&(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:async()=>{if(!await WM(e.id)){l(`Reset failed — storage is unavailable; the stored override still stands.`);return}l(null),s({}),a(_1({}))},"data-testid":`query-defaults-reset-${e.id}`,children:[(0,H.jsx)(Dn,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Reset to system default`})]})]})]})}function C1({surface:e}){let t=EM(e.id),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(null),o=async n=>{a(null),await bM(e.id,t.filter(e=>e.id!==n.id))||a(`Delete failed — storage is unavailable. Nothing was lost; the link remains.`)};return(0,H.jsxs)(`div`,{className:`space-y-2`,"data-testid":`query-defaults-shortcuts-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Saved shortcuts (navigation links)`}),(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>r({editing:null}),"data-testid":`query-defaults-shortcut-new-${e.id}`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New shortcut`})]})]}),t.map(t=>{let n=uM[t.icon],i=t.to?`Opens ${t.to}`:t.wql||`Landing (no query)`;return(0,H.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border/50 px-2 py-1.5`,"data-testid":`query-defaults-shortcut-${e.id}:${t.id}`,children:[(0,H.jsx)(n,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`min-w-0 max-w-40 truncate text-xs font-medium`,children:t.label}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[10px] text-muted-foreground`,children:i}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Edit ${t.label}`,"data-testid":`query-defaults-shortcut-edit-${e.id}:${t.id}`,onClick:()=>r({editing:t}),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(ut,{className:`size-3`})}),!t.to&&t.id!==`all`&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete ${t.label}`,"data-testid":`query-defaults-shortcut-delete-${e.id}:${t.id}`,onClick:()=>o(t),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-destructive`,children:(0,H.jsx)(j,{className:`size-3`})})]},t.id)}),i&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`query-defaults-shortcut-error-${e.id}`,children:i}),n&&(0,H.jsx)(jM,{open:!0,onOpenChange:e=>{e||r(null)},route:e.id,editing:n.editing})]})}function w1(){return(0,H.jsxs)(`section`,{"data-testid":`query-defaults-section`,className:`space-y-6`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground`,children:`Query Defaults`}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Override the landing query and the Where-stored / arrangement options per surface. An empty query uses the system default; an emptied options list nudges you to pick instead of presetting one. Option lists are favorites — they reorder choices, they don't change what queries mean. Stored`,` `,UD?`on the server.`:`in this browser only.`]})]}),g1.map(e=>(0,H.jsx)(S1,{surface:e},e.id))]})}var T1=2.20462,E1=2.54,D1=`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`;function O1(e){if(!e)return;let t=new Date(e);if(Number.isNaN(t.getTime()))return;let n=new Date,r=n.getFullYear()-t.getFullYear(),i=n.getMonth()-t.getMonth();return(i<0||i===0&&n.getDate()<t.getDate())&&r--,r}function k1(e){let t=(e??``).trim().split(/\s+/).filter(Boolean);return t.length===0?`?`:t.slice(0,2).map(e=>e[0].toUpperCase()).join(``)}function A1({unit:e,other:t,onSwitch:n}){return(0,H.jsx)(`div`,{className:`flex rounded-md border border-input overflow-hidden shrink-0`,role:`group`,children:[e,t].map((e,t)=>(0,H.jsx)(`button`,{type:`button`,"aria-pressed":t===0,onClick:t===1?n:void 0,className:U(`px-2.5 h-9 text-xs font-medium transition-colors`,t===0?`bg-primary/10 text-primary`:`bg-background text-muted-foreground hover:bg-muted`),children:e},e))})}function j1(){let[e,t]=(0,V.useState)(null),[n,r]=(0,V.useState)({displayName:``,birthDate:``,weight:``,height:``}),i=(0,V.useRef)(null);(0,V.useEffect)(()=>{let e=!0;return vD.current().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,V.useEffect)(()=>{e&&r({displayName:e.displayName?.trim()||`Anonymous`,birthDate:e.birthDate??``,weight:e.weight==null?``:String(e.weight),height:e.height==null?``:String(e.height)})},[e?.id]);let a=(0,V.useCallback)(async e=>{try{t(await vD.update(e))}catch(e){console.error(e)}},[]),o=(0,V.useCallback)(async e=>{if(e)try{await a({picture:await tb(e)})}catch(e){console.error(e)}},[a]);if(!e)return(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,"data-testid":`profile-loading`,children:`Loading profile…`});let s=O1(e.birthDate),c=e.weightUnit??`kg`,l=e.heightUnit??`cm`;return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(f,{className:`size-4 text-primary`}),`Profile Picture`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Click the picture to choose an image — it is center-cropped and stored locally.`})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i.current?.click(),"aria-label":`Change profile picture`,"data-testid":`profile-avatar`,className:`relative group size-20 rounded-full overflow-hidden border border-border bg-muted shrink-0 cursor-pointer`,children:[e.picture?(0,H.jsx)(`img`,{src:e.picture,alt:``,className:`size-full object-cover`}):(0,H.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center text-lg font-semibold text-muted-foreground`,children:k1(e.displayName)}),(0,H.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/45 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity`,children:(0,H.jsx)(mn,{className:`size-5 text-white`})})]}),(0,H.jsx)(`input`,{ref:i,type:`file`,accept:`image/*`,className:`hidden`,"aria-hidden":`true`,tabIndex:-1,onChange:e=>{o(e.target.files?.[0]),e.target.value=``}})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Details`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Used by journal analytics (age from birth date, metric conversions). Changes are saved immediately.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-display-name`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Name`}),(0,H.jsx)(`input`,{id:`profile-display-name`,"data-testid":`profile-display-name`,className:D1,placeholder:`Anonymous`,value:n.displayName,onChange:e=>{r(t=>({...t,displayName:e.target.value})),a({displayName:e.target.value})}})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{htmlFor:`profile-birth-date`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:[`Birth Date`,s===void 0?``:` · Age ${s}`]}),(0,H.jsx)(`input`,{id:`profile-birth-date`,"data-testid":`profile-birth-date`,type:`date`,className:D1,value:n.birthDate,onChange:e=>{r(t=>({...t,birthDate:e.target.value})),a({birthDate:e.target.value||void 0})}})]}),(0,H.jsx)(`div`,{})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-weight`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Weight`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{id:`profile-weight`,"data-testid":`profile-weight`,type:`number`,inputMode:`decimal`,min:`0`,className:D1,placeholder:c===`kg`?`e.g. 75`:`e.g. 165`,value:n.weight,onChange:e=>{let t=e.target.value;r(e=>({...e,weight:t})),t===``?a({weight:void 0}):Number.isFinite(Number(t))&&a({weight:Number(t)})}}),(0,H.jsx)(A1,{unit:c,other:c===`kg`?`lb`:`kg`,onSwitch:()=>void a({weightUnit:c===`kg`?`lb`:`kg`,weight:e.weight==null?void 0:c===`kg`?e.weight*T1:e.weight/T1})})]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-height`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Height`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{id:`profile-height`,"data-testid":`profile-height`,type:`number`,inputMode:`decimal`,min:`0`,className:D1,placeholder:l===`cm`?`e.g. 180`:`e.g. 71`,value:n.height,onChange:e=>{let t=e.target.value;r(e=>({...e,height:t})),t===``?a({height:void 0}):Number.isFinite(Number(t))&&a({height:Number(t)})}}),(0,H.jsx)(A1,{unit:l,other:l===`cm`?`in`:`cm`,onSwitch:()=>void a({heightUnit:l===`cm`?`in`:`cm`,height:e.height==null?void 0:l===`cm`?e.height/E1:e.height*E1})})]})]})]})]})]})]})}function M1(){let[e]=(0,V.useState)(hD);return e?.state,(0,H.jsx)(`div`,{className:`space-y-8`,children:(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Storage`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This deployment uses its API server for storage and queries.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,"data-testid":`storage-option-api`,children:`This deployment stores data on its server; storage is managed by the deployment.`})]})})}var N1=[{id:`appearance`,content:(0,H.jsx)(I1,{})},{id:`profile`,content:(0,H.jsx)(j1,{})},{id:`storage`,content:(0,H.jsx)(M1,{})},{id:`sync`,content:(0,H.jsx)(kZ,{})},{id:`queries`,content:(0,H.jsx)(w1,{})},{id:`tags`,content:(0,H.jsx)(R1,{})},{id:`routes`,content:(0,H.jsx)(F1,{})},{id:`system`,content:(0,H.jsx)(L1,{})}];function P1(){let e=mt(),t=e.pathname.endsWith(`/system`)?`system`:e.pathname.endsWith(`/profile`)?`profile`:e.pathname.endsWith(`/storage`)?`storage`:e.pathname.endsWith(`/sync`)?`sync`:e.pathname.endsWith(`/queries`)?`queries`:e.pathname.endsWith(`/tags`)?`tags`:e.pathname.endsWith(`/routes`)?`routes`:`appearance`;return(0,H.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 bg-background`,children:[(0,H.jsx)($I,{title:`Settings`,subtitle:`Manage profile, appearance, audio, and system preferences`}),(0,H.jsx)(`main`,{className:`flex-1 overflow-y-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8`,children:(0,H.jsx)(`div`,{className:`max-w-4xl mx-auto space-y-8`,children:N1.find(e=>e.id===t)?.content})})]})}function F1(){let[e,t]=(0,V.useState)([]);return(0,V.useEffect)(()=>{let e=!0;return xD.readonly(`page`).getAll().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,H.jsxs)(`section`,{className:`space-y-6`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{className:`text-lg font-medium`,children:`Route Review`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:"All page routes (`/p/:slug`, `/c/:slug`, `/journal/:date`) currently registered in storage."})]}),(0,H.jsx)(`div`,{className:`border rounded-md`,children:(0,H.jsxs)(`table`,{className:`w-full text-sm text-left`,children:[(0,H.jsx)(`thead`,{className:`bg-muted/50 border-b`,children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Route`}),(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Title`}),(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`ID`})]})}),(0,H.jsx)(`tbody`,{className:`divide-y`,children:e.length===0?(0,H.jsx)(`tr`,{children:(0,H.jsx)(`td`,{colSpan:3,className:`px-4 py-4 text-center text-muted-foreground`,children:`No pages found.`})}):e.map(e=>(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs`,children:e.slug?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-primary/10 text-primary`,children:`SLUG`}),e.slug]}):e.date?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-secondary/10 text-secondary`,children:`DATE`}),e.date]}):`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2`,children:e.title??`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono text-[10px] text-muted-foreground`,children:e.id})]},e.id))})]})})]})}function I1(){let{theme:e,setTheme:t}=ji(),[n,r]=XL(),i={right:cr,left:Fe};return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Interface Theme`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select your preferred color theme. Changes are saved and applied immediately.`})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4`,children:[{id:`system`,label:`System`,description:`Follows your operating system color scheme preferences`,icon:_e,isDefault:!0},{id:`light`,label:`Light`,description:`Crisp light background with dark text for high daytime readability`,icon:et},{id:`dark`,label:`Dark`,description:`Relaxed dark background for lower eye strain in low-light settings`,icon:ir}].map(n=>{let r=e===n.id,i=n.icon;return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`theme-option-${n.id}`,onClick:()=>t(n.id),className:U(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,r?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,H.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,H.jsx)(`div`,{className:U(`p-2 rounded-lg`,r?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,H.jsx)(i,{className:`size-5`})}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[n.isDefault&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,H.jsx)(`div`,{className:U(`size-4 rounded-full border flex items-center justify-center transition-colors`,r?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:r&&(0,H.jsx)(Zn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,H.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:n.label}),(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:n.description})]},n.id)})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(Xn,{className:`size-4 text-primary`}),`Actions Button Position`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`On phones, search and page actions float as a button cluster at the bottom of the screen. Place the cluster near your dominant thumb.`})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4`,children:GL.map(e=>{let t=n===e.id,a=i[e.id];return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`fab-alignment-${e.id}`,onClick:()=>r(e.id),className:U(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,t?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,H.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,H.jsx)(`div`,{className:U(`p-2 rounded-lg`,t?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,H.jsx)(a,{className:`size-5`})}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[e.id===`right`&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,H.jsx)(`div`,{className:U(`size-4 rounded-full border flex items-center justify-center transition-colors`,t?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:t&&(0,H.jsx)(Zn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,H.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:e.label}),(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:e.description})]},e.id)})})]})]})}function L1(){let{isEnabled:e,toggleAudio:t,playTestSound:n}=tk(),{isDebugMode:r,toggleDebugMode:i}=ty(),{consent:a,setConsent:o}=ZV(),[s,c]=(0,V.useState)(!1),[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(null);hD();let p=`your Wod Wiki server`;return(0,V.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),c(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,"data-testid":`settings-about`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(Ce,{className:`size-4 text-primary`}),`About`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Build version and release information for this playground.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsxs)(`p`,{className:`text-sm font-medium text-foreground font-mono`,children:[`v`,VI]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Wod Wiki playground build`})]}),(0,H.jsx)(W,{asChild:!0,variant:`outline`,size:`sm`,className:`gap-2`,children:(0,H.jsxs)(`a`,{href:UI(VI),target:`_blank`,rel:`noopener noreferrer`,"data-testid":`settings-release-link`,children:[(0,H.jsx)(k,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Release notes`})]})})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[e?(0,H.jsx)(fe,{className:`size-4 text-primary`}):(0,H.jsx)(ne,{className:`size-4 text-muted-foreground`}),`Audio Feedback`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Configure sound effects for workout timers, interval countdowns, and completion cues.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`sound-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Workout Sound Effects`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Play countdown beeps, interval alerts, and workout finish chimes`})]}),(0,H.jsx)(h1,{id:`sound-switch`,"data-testid":`sound-toggle`,checked:e,onChange:t})]}),(0,H.jsxs)(`div`,{className:`pt-3 border-t border-border/50 flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Test audio output device`}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:n,disabled:!e,"data-testid":`play-test-sound-btn`,className:`gap-2`,children:[(0,H.jsx)(fe,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Play Test Chime`})]})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(tr,{className:`size-4 text-primary`}),`Developer Diagnostics`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Logging and runtime inspection tools for Whiteboard scripts and execution trees.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`debug-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Debug Mode`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Output verbose AST compilation and runtime execution traces to browser console`})]}),(0,H.jsx)(h1,{id:`debug-switch`,"data-testid":`debug-mode-toggle`,checked:r,onChange:i})]})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,"data-testid":`settings-telemetry`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(S,{className:`size-4 text-primary`}),`Anonymous Telemetry`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Anonymous usage telemetry is internal to Wod Wiki only. It helps us improve timer accuracy, workout execution, and query reliability. Your data will never be sold or shared with third parties.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`telemetry-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Share Anonymous Usage Statistics`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends anonymous feature usage events. Turn off to opt out at any time.`})]}),(0,H.jsx)(h1,{id:`telemetry-switch`,"data-testid":`telemetry-toggle`,checked:a,onChange:o})]})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-destructive flex items-center gap-2`,children:[(0,H.jsx)(Ze,{className:`size-4 text-destructive`}),`Data & Cache (Danger Zone)`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Manage your local database storage and reset client state.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 p-4 sm:p-5 space-y-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`div`,{className:`font-semibold text-sm text-foreground`,children:`Reset & Clear Cache`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:(0,H.jsxs)(H.Fragment,{children:[`Wipes ALL data stored in `,p,`: notes, workouts, custom efforts, recorded results, and attachments, plus this browser's localStorage preferences. Your separate IndexedDB copy is kept. Bundled core content re-imports automatically on the next launch; community and custom libraries must be re-synced from Settings > Sync. Your connection settings are preserved.`]})})]}),(0,H.jsx)(`div`,{children:(0,H.jsxs)(W,{variant:`destructive`,size:`sm`,onClick:()=>c(!0),"data-testid":`reset-cache-button`,className:`gap-2`,children:[(0,H.jsx)(Dn,{className:`size-4`}),(0,H.jsx)(`span`,{children:`Reset & Clear Cache`})]})})]})]}),s&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-150`,onClick:e=>{e.target===e.currentTarget&&!l&&c(!1)},"data-testid":`reset-confirmation-modal`,children:(0,H.jsxs)(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl flex flex-col gap-4`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`reset-modal-title`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 text-destructive font-semibold text-base`,id:`reset-modal-title`,children:[(0,H.jsx)(Ze,{className:`size-5`}),`Reset All Application Data?`]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:(0,H.jsxs)(H.Fragment,{children:[`This permanently deletes every note, result, cached effort, and local setting stored in `,p,`. It cannot be undone.`]})}),d&&(0,H.jsxs)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`reset-error`,children:[`Reset failed: `,d,` — your data and connection were left untouched; try again.`]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-2`,children:[(0,H.jsx)(W,{variant:`outline`,onClick:()=>c(!1),disabled:l,children:`Cancel`}),(0,H.jsx)(W,{variant:`destructive`,onClick:async()=>{u(!0),f(null);try{await HY(),window.location.reload()}catch(e){f(e instanceof Error?e.message:String(e)),u(!1)}},disabled:l,"data-testid":`confirm-reset-button`,className:`gap-2`,children:l?(0,H.jsx)(`span`,{children:`Resetting…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Dn,{className:`size-4`}),(0,H.jsx)(`span`,{children:`Yes, Reset Everything`})]})})]})]})})]})}function R1(){let[e,t]=(0,V.useState)([]),[n,r]=(0,V.useState)([]),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(``),[c,l]=(0,V.useState)(`#3b82f6`),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(``),[g,_]=(0,V.useState)(``),[v,y]=(0,V.useState)(null),[b,x]=(0,V.useState)(``),[S,C]=(0,V.useState)(null),w=(0,V.useCallback)(async()=>{try{let[e,n]=await Promise.all([X.getAllTagTypes(),X.getAllTags()]);t(e),r(n)}catch{}},[]);(0,V.useEffect)(()=>{w()},[w]);let T=async t=>{t.preventDefault();let n=i.trim().toLowerCase().replace(/[^a-z0-9_-]/g,`-`),r=o.trim();if(!n||!r){C(`Both type name and display label are required`);return}if(e.some(e=>e.name.toLowerCase()===n)){C(`Tag type "${n}" already exists`);return}C(null);let l={id:typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,name:n,label:r,color:c,createdAt:Date.now()};await X.putTagType(l),a(``),s(``),await w()},E=async e=>{if(n.some(t=>t.type?.toLowerCase()===e.name.toLowerCase())){C(`Cannot delete tag type "${e.label}" while tags are assigned to it`);return}C(null),await X.deleteTagType(e.id),await w()},D=async e=>{e.preventDefault();let t=u.trim();if(!t)return;let r=n.find(e=>e.label.toLowerCase()===t.toLowerCase());if(r)f&&r.type!==f&&await X.updateTagType(r.id,f);else{let e={id:typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,label:t,type:f||void 0,createdAt:Date.now()};await X.putTag(e)}d(``),await w()},O=async(e,t)=>{await X.updateTagType(e,t===``?void 0:t),await w()},k=async e=>{await X.deleteTag(e),await w()},A=async e=>{let t=b.trim();if(y(null),!t)return;let r=n.find(t=>t.id===e);!r||r.label===t||(await X.putTag({...r,label:t}),await w())},M=n.filter(t=>!t.type||!e.some(e=>e.name.toLowerCase()===t.type?.toLowerCase()));return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tag Types`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Define classification dimensions for tags. Note frontmatter properties matching a type name will automatically provide typeahead suggestions.`})]}),(0,H.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,H.jsxs)(`form`,{onSubmit:T,className:`flex flex-wrap items-end gap-3`,children:[(0,H.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Type Name`}),(0,H.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,placeholder:`Type name (e.g. discipline)`,value:i,onChange:e=>a(e.target.value)})]}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Label`}),(0,H.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`,placeholder:`Display label (e.g. Discipline)`,value:o,onChange:e=>s(e.target.value)})]}),(0,H.jsxs)(`div`,{className:`w-24`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Color`}),(0,H.jsx)(`input`,{type:`color`,className:`w-full h-9 p-1 rounded-md border border-input bg-background cursor-pointer`,value:c,onChange:e=>l(e.target.value)})]}),(0,H.jsxs)(W,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,H.jsx)(Kt,{className:`size-3.5 mr-1`}),` Add Type`]})]}),S&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,children:S}),(0,H.jsxs)(`div`,{className:`border-t border-border pt-3`,children:[(0,H.jsx)(`h3`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2`,children:`Registered Types`}),e.length===0?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No custom tag types created yet.`}):(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2`,children:e.map(e=>{let t=n.filter(t=>t.type?.toLowerCase()===e.name.toLowerCase()).length;return(0,H.jsxs)(`div`,{className:`flex items-center justify-between p-2.5 rounded-lg border border-border/70 bg-background/50 text-xs`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,H.jsx)(`span`,{className:`size-2.5 rounded-full shrink-0`,style:{backgroundColor:e.color||`#3b82f6`}}),(0,H.jsx)(`span`,{className:`font-semibold truncate`,children:e.label}),(0,H.jsxs)(`span`,{className:`text-muted-foreground font-mono text-[11px] truncate`,children:[`(`,e.name,`)`]}),(0,H.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.2 text-[10px] text-muted-foreground`,children:t})]}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete tag type ${e.label}`,disabled:t>0,title:t>0?`Cannot delete type while ${t} tag(s) are assigned`:`Delete unused tag type`,className:U(`p-1 rounded transition`,t>0?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground hover:text-destructive cursor-pointer`),onClick:()=>E(e),children:(0,H.jsx)(j,{className:`size-3.5`})})]},e.id)})})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsx)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3`,children:(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tags Table`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Filter, search, edit, reassign, or delete stored tags.`})]})}),(0,H.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsxs)(`div`,{className:`relative flex-1 min-w-[200px]`,children:[(0,H.jsx)(Xn,{className:`absolute left-2.5 top-2.5 size-3.5 text-muted-foreground`}),(0,H.jsx)(`input`,{"aria-label":`Filter tags`,className:`w-full h-9 rounded-md border border-input bg-background pl-8 pr-3 text-xs outline-none focus:border-primary`,placeholder:`Filter tags by label…`,value:m,onChange:e=>h(e.target.value)})]}),(0,H.jsx)(`div`,{className:`w-48`,children:(0,H.jsxs)(`select`,{"aria-label":`Filter by type`,className:`w-full h-9 rounded-md border border-input bg-background px-2.5 text-xs outline-none focus:border-primary`,value:g,onChange:e=>_(e.target.value),children:[(0,H.jsxs)(`option`,{value:``,children:[`All Types (`,n.length,`)`]}),(0,H.jsxs)(`option`,{value:`__untyped__`,children:[`Untyped / General (`,M.length,`)`]}),e.map(e=>{let t=n.filter(t=>t.type?.toLowerCase()===e.name.toLowerCase()).length;return(0,H.jsxs)(`option`,{value:e.name,children:[e.label,` (`,t,`)`]},e.id)})]})}),(0,H.jsxs)(`form`,{onSubmit:D,className:`flex items-center gap-2`,children:[(0,H.jsx)(`input`,{className:`h-9 w-36 sm:w-44 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,placeholder:`New tag…`,value:u,onChange:e=>d(e.target.value)}),(0,H.jsxs)(`select`,{className:`h-9 w-28 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,value:f,onChange:e=>p(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`Untyped`}),e.map(e=>(0,H.jsx)(`option`,{value:e.name,children:e.label},e.id))]}),(0,H.jsxs)(W,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,H.jsx)(Kt,{className:`size-3.5 mr-1`}),` Add`]})]})]}),(0,H.jsx)(`div`,{className:`border border-border rounded-lg overflow-hidden`,children:(0,H.jsx)(`div`,{className:`overflow-x-auto`,children:(0,H.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,H.jsx)(`thead`,{className:`bg-muted/50 border-b border-border`,children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Tag Label`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Type`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Created`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium text-right`,children:`Actions`})]})}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border`,children:n.filter(t=>m&&!t.label.toLowerCase().includes(m.toLowerCase().trim())?!1:g===`__untyped__`?!t.type||!e.some(e=>e.name.toLowerCase()===t.type?.toLowerCase()):!g||t.type?.toLowerCase()===g.toLowerCase()).map(t=>{let n=e.find(e=>e.name.toLowerCase()===t.type?.toLowerCase()),r=v===t.id;return(0,H.jsxs)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono`,children:r?(0,H.jsx)(`input`,{autoFocus:!0,className:`h-7 w-full max-w-[200px] rounded border border-primary bg-background px-2 font-mono text-xs outline-none`,value:b,onChange:e=>x(e.target.value),onKeyDown:async e=>{e.key===`Enter`?await A(t.id):e.key===`Escape`&&y(null)},onBlur:()=>A(t.id)}):(0,H.jsx)(`button`,{type:`button`,className:`font-mono text-foreground hover:underline text-left`,title:`Click to rename`,onClick:()=>{y(t.id),x(t.label)},children:t.label})}),(0,H.jsx)(`td`,{className:`px-4 py-2`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[n&&(0,H.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:n.color||`#3b82f6`}}),(0,H.jsxs)(`select`,{"aria-label":`Type for ${t.label}`,className:`h-7 rounded border border-input bg-background px-2 text-xs outline-none cursor-pointer focus:border-primary`,value:t.type??``,onChange:e=>O(t.id,e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`Untyped`}),e.map(e=>(0,H.jsx)(`option`,{value:e.name,children:e.label},e.id))]})]})}),(0,H.jsx)(`td`,{className:`px-4 py-2 text-muted-foreground text-[11px]`,children:t.createdAt?new Date(t.createdAt).toLocaleDateString():`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2 text-right`,children:(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete tag ${t.label}`,className:`text-muted-foreground hover:text-destructive p-1 rounded transition`,onClick:()=>k(t.id),children:(0,H.jsx)(j,{className:`size-3.5`})})})]},t.id)})})]})})})]})]})]})}var z1=`dashboard-title`;function B1(){let{slug:e}=zn(),t=Sn(),[n]=bX(),{unit:r}=jx(),i=Date.now()-n*7*864e5,a=Date.now(),[o,s]=(0,V.useState)(0),[c,l]=(0,V.useState)(null);(0,V.useEffect)(()=>{let e=!1;return X.countEvents().then(t=>{e||l(t>0)}),()=>{e=!0}},[o]);let{source:u,loading:d}=Ij(e,o),f=(0,V.useMemo)(()=>{if(!u?.rawContent)return null;let{meta:e,sections:t}=u_(u.rawContent);return{doc:i_(t,e),sections:t}},[u]),p=f?.doc??null,{setL3Items:m,registerScrollFn:h}=hA(),g=(0,V.useMemo)(()=>{if(!f)return{headings:[],items:[]};let{doc:e,sections:t}=f,n=new Set;t.forEach((e,r)=>{if(e.type!==`query`)return;let i=t[r-1];if(i?.type===`markdown`&&i.subtype===`paragraph`){let e=t[r-2];e?.type===`markdown`&&e.subtype===`heading`&&n.add(r-2)}else i?.type===`markdown`&&i.subtype===`heading`&&n.add(r-1)});let r=[],i=[];e.title&&i.push({id:z1,label:e.title,level:3,action:{type:`scroll`,sectionId:z1}});let a=0;return t.forEach((t,o)=>{if(t.type===`markdown`&&t.subtype===`heading`){if(n.has(o)||/^#\s/.test(t.content))return;let e=`note-h${o}`,s=t.content.replace(/^#+\s*/,``);r.push({id:e,level:/^#+/.exec(t.content)?.[0].length??2,text:s,beforeWidget:a}),i.push({id:e,label:s,level:3,action:{type:`scroll`,sectionId:e}});return}if(t.type!==`query`)return;let s=e.widgets[a];if(!s)return;a++;let c=`widget-${s.key}`;i.push({id:c,label:s.title||s.body,level:3,action:{type:`scroll`,sectionId:c}})}),{headings:r,items:i}},[f]),_=g.items;(0,V.useEffect)(()=>(m(_),()=>m([])),[_,m]),(0,V.useEffect)(()=>(h(e=>{let t=globalThis.document.getElementById(e);t&&(window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`}),typeof t.animate==`function`&&t.animate([{boxShadow:`0 0 0 3px hsl(var(--primary))`},{boxShadow:`0 0 0 3px transparent`}],{duration:1500,easing:`ease-out`}))}),()=>h(e=>{let t=globalThis.document.getElementById(e);t&&window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`})})),[h]);let[v,y]=(0,V.useState)(!1),[b,x]=(0,V.useState)(null),[S,C]=(0,V.useState)(null),w=(0,V.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await Kj.getById(u.noteId);if(n.rawContent!==e)throw s(e=>e+1),Error(`The dashboard changed elsewhere — this edit was not saved.`);let r=t(n.rawContent);if(r==null)throw s(e=>e+1),Error(`The widget changed on disk — this edit was not saved.`);await Kj.update(n,typeof r==`string`?r:r.note,typeof r==`string`?void 0:r),s(e=>e+1)},[u]),T=(0,V.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await Kj.getById(u.noteId),{meta:r,body:i}=Sb(n.rawContent),a=`---\n${Eb($g(r,e,t))}\n---\n${i}`;await Kj.update(n,a),s(e=>e+1)},[u]),E=(0,V.useCallback)((e,t)=>{C(null),w(e,e=>{let n=t(e);if(!n.ok){let e=n.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return n}).catch(e=>{C(e instanceof Error?e.message:String(e))})},[w]),D=(0,V.useCallback)(async e=>{if(!(!b||b.mode===`inspect`)){if(b.mode===`add`)await w(b.expectedRaw,t=>b_(t,e));else{let t=b.widget;await w(b.expectedRaw,n=>{let r=C_(n,t.key,t.body,e);if(!r.ok){let e=r.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return r})}}},[b,w]),O=(0,V.useCallback)(async()=>{!u||u.editable||(await Jj.cloneDashboard(u.slug,u.rawContent,u.title),s(e=>e+1))},[u]),k=u!=null&&u.slug===e;if(d&&!k)return(0,H.jsx)(`div`,{className:`p-8 text-sm text-muted-foreground`,children:`Loading dashboard…`});if(!k||!u)return(0,H.jsxs)(`div`,{className:`p-8`,"data-testid":`dashboard-not-found`,children:[(0,H.jsx)(`h1`,{className:`text-lg font-bold text-foreground mb-2`,children:`Dashboard not found`}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground mb-4`,children:[`No dashboard named `,(0,H.jsx)(`code`,{children:e}),`. It may have been removed.`]}),(0,H.jsx)(`button`,{onClick:()=>t(`/dashboard`),className:`px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90`,children:`Back to explorer`})]});let A=u.editable;return(0,H.jsxs)(`div`,{className:`min-h-screen bg-background flex flex-col`,children:[(0,H.jsx)($I,{id:z1,title:p?.title||u.title,subtitle:A?`Editable dashboard note.`:`Prebuilt — read-only until cloned to your vault.`,actions:(0,H.jsxs)(nR,{label:`Dashboard actions`,primary:A?(0,H.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-edit-toggle`,"aria-pressed":v,onClick:()=>y(e=>!e),className:`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors ${v?`bg-primary text-primary-foreground`:`border border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,H.jsx)(ut,{size:12}),` `,v?`Done`:`Edit`]}):void 0,children:[(0,H.jsx)(Sx,{}),(0,H.jsx)(Nx,{})]})}),(0,H.jsxs)(`div`,{className:`max-w-[1500px] w-full mx-auto p-4 md:p-6 lg:p-8 flex-1`,children:[S&&(0,H.jsxs)(`div`,{role:`alert`,"data-testid":`dashboard-action-error`,className:`mb-4 flex items-center justify-between rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2 text-xs text-destructive`,children:[(0,H.jsx)(`span`,{children:S}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:()=>C(null),className:`font-medium hover:opacity-70 transition-opacity`,children:`×`})]}),!A&&(0,H.jsxs)(`div`,{className:`mb-4 flex items-center justify-between rounded-lg border border-primary/30 bg-primary/5 px-4 py-2 text-xs`,children:[(0,H.jsx)(`span`,{className:`text-foreground`,children:`This is a read-only prebuilt. Clone it to edit widgets and tokens.`}),(0,H.jsx)(`button`,{type:`button`,"data-testid":`clone-dashboard`,onClick:O,className:`font-medium text-primary hover:text-primary/80 transition-colors`,children:`Clone to vault`})]}),A&&v&&(0,H.jsxs)(`button`,{type:`button`,"data-testid":`add-widget`,onClick:()=>x({mode:`add`,expectedRaw:u.rawContent}),className:`mb-4 flex items-center gap-1.5 rounded-lg border border-dashed border-primary/50 px-4 py-2 text-xs font-semibold text-primary hover:bg-primary/5 transition-colors`,children:[(0,H.jsx)(Kt,{size:13}),` Add widget`]}),c===!1?(0,H.jsx)(o1,{layout:`card`,refreshKey:o,onChanged:()=>s(e=>e+1)}):(0,H.jsx)(`div`,{className:`mb-4`,children:(0,H.jsx)(o1,{layout:`banner`,refreshKey:o,onChanged:()=>s(e=>e+1)})}),p&&(0,H.jsx)(xx,{document:p,headings:g.headings,executor:XF,onTokenChange:A?T:void 0,editMode:A&&v,onEditWidget:A?e=>x({mode:`edit`,widget:e,expectedRaw:u.rawContent}):void 0,onDuplicateWidget:A?e=>E(u.rawContent,t=>w_(t,e.key,e.body)):void 0,onRemoveWidget:A?e=>E(u.rawContent,t=>T_(t,e.key,e.body)):void 0,onMoveWidget:A?(e,t)=>E(u.rawContent,n=>E_(n,e.key,e.body,t)):void 0,onResizeWidget:A?(e,t)=>E(u.rawContent,n=>D_(n,e.key,e.body,t)):void 0,onInspectWidget:A?void 0:e=>x({mode:`inspect`,widget:e,expectedRaw:u.rawContent}),onOpenInExplorer:(e,n)=>t(aj({q:n})),rangeStart:i,rangeEnd:a,preferredUnit:r})]}),(0,H.jsx)(wX,{open:b!==null,onClose:()=>x(null),mode:b?.mode??`add`,initialWql:b&&b.mode!==`add`?b.widget.body:`sum:totalVolume{}`,initial:b&&b.mode!==`add`?{title:b.widget.title,question:b.widget.question,type:b.widget.type,spanCols:b.widget.spanCols,spanFull:b.widget.spanFull,attributes:b.widget.attributes}:void 0,executor:XF,rangeStart:i,rangeEnd:a,preferredUnit:r,tokenValues:p?Qg(p.tokens):void 0,onApply:b?.mode===`inspect`?void 0:D,footerExtra:b?.mode===`inspect`?(0,H.jsx)(`button`,{type:`button`,"data-testid":`inspect-clone`,onClick:()=>{O().then(()=>{x(null),y(!0)})},className:`px-3 py-1.5 text-xs font-medium text-primary hover:text-primary/80 rounded-lg border border-primary/40 hover:bg-primary/10 transition-colors`,children:`Clone to vault to edit`}):void 0})]})}function V1({sessionId:e}){let[t,n]=(0,V.useState)(null),[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(``);return(0,V.useEffect)(()=>{let t=!1;return n(null),i(null),(async()=>{let r=await Nj.getSessionById?.(e);if(!r)throw Error(`Session not found.`);let i=await Nj.getBlockRevision(r.noteId,r.blockId,r.blockVersion);if(!i)throw Error(`The pinned saved workout is unavailable.`);t||n({session:r,revision:i})})().catch(e=>{t||i(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]),(0,H.jsxs)(`section`,{"aria-label":`Pinned workout source`,className:`space-y-3 border-b p-4`,children:[(0,H.jsx)(`h2`,{className:`font-semibold`,children:`Saved workout used by this session`}),r&&(0,H.jsx)(`p`,{role:`alert`,children:r}),t?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`p`,{className:`break-all text-sm`,children:[`Block `,t.session.blockId,` · v`,t.revision.version,` · `,t.revision.dialect,t.revision.sport?` · ${t.revision.sport}`:``]}),(0,H.jsx)(`pre`,{className:`max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-3 text-xs`,children:t.revision.rawContent}),(0,H.jsx)(`button`,{type:`button`,disabled:a,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:async()=>{o(!0),i(null);try{await new Mj().rederiveResultAnalytics(e),c(`Analytics replayed from the pinned saved workout. Reload the results to view them.`)}catch(e){i(e instanceof Error?e.message:String(e))}finally{o(!1)}},children:a?`Replaying…`:`Replay saved analytics`}),(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:s}),(0,H.jsx)(qP,{noteId:t.session.noteId})]}):r?null:(0,H.jsx)(`p`,{role:`status`,children:`Loading saved workout…`})]})}function H1({searchHandlerRef:e}){let t=Sn(),n=mt(),{theme:r}=ji(),i=sD()??vR,a=_R(),o=jP(),s=PR(),c=NR(),{workout:l,nav:u}=s,[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)(`blank`),h=(0,V.useCallback)(e=>{m(e?.mode??`blank`),f(!0)},[]),g=(0,V.useMemo)(()=>/^\/journal\/(\d{4}-\d{2}-\d{2})\/?$/.exec(n.pathname)?.[1],[n.pathname]),_=(0,V.useCallback)(e=>{t(`${qA(e.id)}?edit=1`)},[t]),{tree:v,navState:y,setL3Items:b,setSecondarySpec:x,registerCreateJournal:S}=hA(),C=y?.activeL1Id??null,w=(v??[]).find(e=>e?.id===C)??null,T=s.shell.title??l.name,E=(0,V.useMemo)(()=>s.page===`library`?GM(VA(n.pathname)):void 0,[s.page,n.pathname]),D=s.shell.secondary;(0,V.useEffect)(()=>(x(D),()=>x(void 0)),[D,x]),(0,V.useEffect)(()=>S(h),[S,h]),(0,V.useEffect)(()=>{let e=new URLSearchParams(n.search);if(e.get(`create`)===`1`||e.get(`new`)===`1`){let r=e.get(`mode`)===`source`?`source`:`blank`;h({mode:r}),e.delete(`create`),e.delete(`new`),e.delete(`mode`);let i=e.toString()?`?${e.toString()}`:``;t(`${n.pathname}${i}`,{replace:!0})}},[n.pathname,n.search,h,t]),(0,V.useEffect)(()=>{if(!(!s.shell.withIndex||u.length===0))return b(Gz(u)),()=>b([])},[s.shell.withIndex,u,b]);let O=(0,V.useRef)(()=>null),k=(0,V.useCallback)(e=>(O.current=e,()=>{O.current===e&&(O.current=()=>null)}),[]),A=(0,V.useCallback)(()=>{UR.getState().open({wql:{initialQuery:O.current()??Fz(),execute:Lz,preferredChoices:Iz()},sources:[Mz(),Pz(dz(o)),Pz(iz())]}).then(e=>{e.dismissed||Rz(e.item,t)})},[t,o]);(0,V.useEffect)(()=>{e.current=A},[A,e]),(0,V.useEffect)(()=>{let e=e=>{e.key===`/`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.stopPropagation(),A())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[A]);let[j,M]=(0,V.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches),{handleViewCreated:N,scrollToSection:P}=Kz(u);(0,V.useEffect)(()=>{if(r!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>M(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let F=(0,V.useMemo)(()=>r===`system`?j?`vs-dark`:`vs`:r===`dark`?`vs-dark`:`vs`,[r,j]),I={feedDetail:()=>(0,H.jsx)(jJ,{feedSlug:decodeURIComponent(s.feedDetailMatch)}),feedItem:()=>(0,H.jsx)(vY,{feedSlug:decodeURIComponent(s.feedItemMatch[0]),feedDate:decodeURIComponent(s.feedItemMatch[1]),feedItem:decodeURIComponent(s.feedItemMatch[2]),theme:F,onViewCreated:N,onScrollToSection:P}),effortDetail:()=>(0,H.jsx)(a$,{}),equipmentDetail:()=>(0,H.jsx)(u$,{}),analyticsExplorer:()=>(0,H.jsx)(m1,{actions:(0,H.jsx)(_Y,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardExplorer:()=>(0,H.jsx)(m1,{actions:(0,H.jsx)(_Y,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardView:()=>(0,H.jsx)(B1,{}),canvas:()=>s.canvasPage.route===`/`?(0,H.jsx)(BX,{wodFiles:i,theme:F}):s.canvasPage.scroll?(0,H.jsx)(SJ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}):(0,H.jsx)(iJ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}),playground:()=>(0,H.jsx)(qQ,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.effectivePlaygroundId),journalEntry:()=>(0,H.jsx)(jQ,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.journalEntryId),note:()=>(0,H.jsx)(m$,{noteId:s.noteById,theme:F},s.noteById),collectionDate:()=>(0,H.jsx)(v$,{slug:s.collectionDate.slug,date:s.collectionDate.date,theme:F},`${s.collectionDate.slug}/${s.collectionDate.date}`),workout:()=>(0,H.jsx)(JQ,{category:s.workout.category,name:s.workout.name,mdContent:s.workout.content,theme:F,onViewCreated:N},`${s.workout.category}/${s.workout.name}`),library:()=>{let e=E??GM(VA(n.pathname));return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(U1,{pathname:n.pathname}),(0,H.jsx)(wQ,{profile:e,registerStreamDraft:k,actions:(0,H.jsx)(_Y,{mode:`collection-readonly`,currentWorkout:l,index:[]})},e.route)]})},settings:()=>(0,H.jsx)(P1,{})},ee=s.page===`canvas`?s.canvasPage?.route:void 0,te=ee===`/`||!!ee?.startsWith(`/guide/`),ne=s.page===`canvas`&&s.canvasPage?(0,H.jsx)(H.Fragment,{children:s.canvasPage.quests.length>0&&(0,H.jsx)(TQ,{pageRoute:s.canvasPage.route,quests:s.canvasPage.quests,challengeSectionMap:rP(s.canvasPage),onScrollToSection:P})}):void 0;return(0,H.jsxs)(dR,{navbar:(0,H.jsxs)(NP,{children:[(0,H.jsxs)(`nav`,{"aria-label":`Breadcrumb`,className:`flex items-center gap-1.5 min-w-0 shrink-2 truncate text-sm`,children:[w&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>w?.action?.type===`route`&&t(w.action.to),className:`shrink-0 text-muted-foreground hover:text-foreground transition-colors`,children:w.label}),w&&!!T&&T.toLowerCase()!==w.label.toLowerCase()&&(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/50 shrink-0`,children:`›`}),T&&T.toLowerCase()!==w?.label.toLowerCase()&&(0,H.jsx)(`span`,{className:`text-sm font-semibold text-zinc-950 dark:text-white truncate`,children:T}),ne]}),(0,H.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,H.jsx)(IR,{}),(0,H.jsx)(iR,{}),(0,H.jsx)(RG,{})]})]}),sidebar:(0,H.jsx)(BI,{navSpec:s.shell.nav}),hideDesktopSidebar:te,secondary:D,pageAction:l.content===``?void 0:(0,H.jsx)(fY,{currentWorkout:l}),onSearch:A,onCreate:h,children:[(0,H.jsx)(xz,{open:d,onOpenChange:f,defaultDate:g,defaultMode:p,onCreated:_}),(0,H.jsx)(`div`,{className:`flex flex-col h-full min-h-[calc(100vh-theme(spacing.20))]`,children:(0,H.jsx)(`div`,{className:`flex-1 flex flex-col min-h-0`,children:(e=>{if(s.shell.wrap===`bare`)return e;let t=s.shell.subheader===`filter-collection-workouts`?(0,H.jsx)(BK,{placeholder:`Filter notebook notes… Press / to start filtering`}):void 0;return(0,H.jsx)(tL,{title:s.shell.title,titleAccessory:ne,subheader:t,index:s.shell.withIndex?u:void 0,actions:s.shell.actionsMode?(0,H.jsx)(_Y,{mode:s.shell.actionsMode,currentWorkout:l,index:u}):void 0,children:e})})(I[s.page]())})}),(0,H.jsx)(nz,{}),(0,H.jsx)(VR,{})]})}function U1({pathname:e}){let t=/^\/results\/([^/]+)\/?$/.exec(e);return t?(0,H.jsx)(V1,{sessionId:decodeURIComponent(t[1])}):null}function W1(){let{name:e}=zn();return(0,H.jsx)(_n,{to:WA(e),replace:!0})}function G1(){let{category:e,name:t}=zn();return(0,H.jsx)(_n,{to:ZA(e,t),replace:!0})}function K1(){let{slug:e,target:t}=zn(),{search:n}=mt();return t==null?(0,H.jsx)(_n,{to:{pathname:XA(e),search:n},replace:!0}):SR(decodeURIComponent(t))?(0,H.jsx)(_n,{to:{pathname:qA(decodeURIComponent(t)),search:n},replace:!0}):(0,H.jsx)(_n,{to:{pathname:ZA(e,decodeURIComponent(t)),search:n},replace:!0})}function q1(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/feeds`,search:e},replace:!0})}function J1(){let{slug:e}=zn();return(0,H.jsx)(_n,{to:cj(e),replace:!0})}function Y1(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/sessions`,search:e},replace:!0})}function X1(){return(0,H.jsx)(_n,{to:`/sessions?q=%3Asegment%7B%7D%20last%208w`,replace:!0})}function Z1(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/dashboards`,search:e},replace:!0})}function Q1(){let{runtimeId:e}=zn();return(0,H.jsx)(_n,{to:QA(e),replace:!0})}function $1(){let{runtimeId:e,noteId:t,resultId:n}=zn(),r=n??e;return r?(0,H.jsx)(_n,{to:ej(r),replace:!0}):t?(0,H.jsx)(_n,{to:`/sessions?q=${encodeURIComponent(`:session{note:${t}}`)}`,replace:!0}):(0,H.jsx)(_n,{to:`/sessions`,replace:!0})}function e0(){let e=mt().search,t=e&&e.startsWith(`?`)?`${e}&mode=plan`:`?mode=plan`;return(0,H.jsx)(_n,{to:`/journal${t}`,replace:!0})}function t0(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/dashboards`,search:e},replace:!0})}var n0=`G-PROD-ID`,r0=!1;function i0(){if(r0||typeof document>`u`)return;r0=!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=${n0}`,document.head.appendChild(e),window.gtag(`js`,new Date),window.gtag(`config`,n0,{send_page_view:!1})}function a0(e,t){typeof window>`u`||!YV.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})}YV.setForwarder(e=>{window.gtag?.(`event`,e.name,e.payload??{})}),YV.consent?i0():YV.subscribeConsent(e=>{e&&i0()});function o0(){let e=mt();return(0,V.useEffect)(()=>{let t=e.pathname;if(!t.startsWith(`/effort/`)&&!t.startsWith(`/e/`)&&!t.startsWith(`/playground/`)&&!t.startsWith(`/equipment/`)){let e=`Wod.Wiki`;t.startsWith(`/journal`)?e=`Wod.Wiki - Journal`:t.startsWith(`/catalogs`)?e=`Wod.Wiki - Notebooks`:t.startsWith(`/feeds`)||t.startsWith(`/feed`)||t.startsWith(`/collections`)||t.startsWith(`/c/`)?e=`Wod.Wiki - Notes`:t.startsWith(`/efforts`)?e=`Wod.Wiki - Efforts`:t.startsWith(`/equipment`)?e=`Wod.Wiki - Equipment`:t.startsWith(`/sessions`)||t.startsWith(`/session/`)||t.startsWith(`/results`)?e=`Wod.Wiki - Sessions`:t.startsWith(`/dashboards`)||t===`/dashboard`||t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)?e=`Wod.Wiki - Dashboards`:t.startsWith(`/playgrounds`)?e=`Wod.Wiki - Playgrounds`:t.startsWith(`/syntax`)?e=`Wod.Wiki - Syntax`:t.startsWith(`/analytics`)&&(e=`Wod.Wiki - Analytics`),document.title=e}let n=setTimeout(()=>{a0(document.title,e.pathname+e.search)},0);return()=>clearTimeout(n)},[e.pathname,e.search]),null}function s0(e,t){let n=e.match(RegExp(`^${t}:\\s*"([^"]+)"`,`m`));if(!n?.[1])throw Error(`Guide example is missing frontmatter field: ${t}`);return n[1]}function c0(e){let t=e.match(/```time\n([\s\S]*?)\n```/);if(!t)throw Error("Guide example is missing a ```time fenced block.");return t[1]}function l0(e,t){let n=s0(e,`title`),r=s0(e,`subtitle`),i=c0(e);return{title:n,subtitle:r,docsPath:t,workout:i,storyContent:[`# `+n,``,r,``,"```time",i,"```"].join(`
170
- `)}}var u0={coreRules:{path:`markdown/canvas/syntax/core-rules.md`,docsPath:`/guide/start?h=first-workout`},measurements:{path:`markdown/canvas/syntax/measurements.md`,docsPath:`/guide/start?h=measurements`},timerModifiers:{path:`markdown/canvas/syntax/timer-modifiers.md`,docsPath:`/guide/protocols?h=countdown-countup`},simpleRounds:{path:`markdown/canvas/syntax/groups-1.md`,docsPath:`/guide/structure?h=rounds`},repSchemes:{path:`markdown/canvas/syntax/groups-2.md`,docsPath:`/guide/structure?h=rep-schemes`},timersAndRest:{path:`markdown/canvas/syntax/timers-rest.md`,docsPath:`/guide/protocols?h=required-rest`},classicAmrap:{path:`markdown/canvas/syntax/classic-amrap.md`,docsPath:`/guide/protocols?h=amrap`},basicEmom:{path:`markdown/canvas/syntax/basic-emom.md`,docsPath:`/guide/protocols?h=emom`},standardTabata:{path:`markdown/canvas/syntax/protocols-4.md`,docsPath:`/guide/protocols?h=tabata-intervals`},mixedSections:{path:`markdown/canvas/syntax/mixed-sections.md`,docsPath:`/guide/structure?h=named-sections`},complexNestedProtocols:{path:`markdown/canvas/syntax/complex-nested-protocols.md`,docsPath:`/guide/sessions?h=nested`}};function d0(e){let t={};for(let[n,{path:r,docsPath:i}]of Object.entries(u0)){let a=e[r];if(!a){t[n]=void 0;continue}try{t[n]=l0(a,i)}catch{t[n]=void 0}}return t}function f0({actionsSlot:e,heroSlot:t,children:n,className:r}){return(0,H.jsxs)(`main`,{className:U(`mx-auto w-full max-w-7xl px-6 py-10 sm:px-8 lg:px-12 lg:py-14`,r),children:[e&&(0,H.jsx)(`div`,{className:`mb-6 flex justify-end`,children:e}),t,n]})}var p0={headline:`Build and preview widget-driven workout pages.`,subtitle:`Phase 2.2 integrates the attention, code-example, and syntax-group widgets into one interactive playground surface.`,pillars:[{icon:(0,H.jsx)(vn,{className:`size-4`,"aria-hidden":`true`}),label:`Attention widget`,description:`High-signal hero block with actionable CTAs.`},{icon:(0,H.jsx)(yt,{className:`size-4`,"aria-hidden":`true`}),label:`Code example widget`,description:`Editable CodeMirror sample with runnable workout output.`},{icon:(0,H.jsx)(s,{className:`size-4`,"aria-hidden":`true`}),label:`Syntax group widget`,description:`Grouped syntax cards linked to docs.`}],actions:[{label:`Jump to workout`,action:`scroll-to-workout`,variant:`primary`},{label:`Open search`,action:`open-search`,variant:`secondary`}]};function m0(){let e=Sn(),{theme:t,setTheme:n}=ji(),r=(0,V.useRef)(null),i=sD(),a=(0,V.useMemo)(()=>i?d0(i):null,[i]),o=(0,V.useMemo)(()=>(a?.classicAmrap?.workout??`20:00 AMRAP
179
+ `));let i=e,a=t.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(a!==t.slug&&(t.slug=a,i=Wa(i,[`slug`],a)),t.label.trim()!==t.label&&(t.label=t.label.trim(),i=Wa(i,[`label`],t.label)),t.updatedAt=new Date().toISOString(),t.registrySource===`bundled`){let e=v$(i,t.slug,t.label);i=e.raw,t.id=e.id,t.slug=e.slug,t.label=e.label,t.registrySource=`user`}try{let e=t.ownerNoteId??_.current?.id??`equipment/${t.slug}`,n=_.current?.id===e?_.current.revision:0,a=await d$({kind:`equipment`,slug:t.slug,rawContent:i,title:t.label,expectedSourceRevision:n,noteId:e});_.current={id:a.id,revision:a.sourceRevision},await r(),d(t)}catch(e){throw Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`}),e}},[u,r]),{onChange:y,onLineChange:b,onBlur:x,flush:S}=YJ({onSave:v});return{document:i,setDocument:(0,V.useCallback)(e=>{a(e),y(e)},[y]),isLoading:o,equipment:u,isEditable:g,notFound:f,flush:S,save:(0,V.useCallback)(e=>v(e??i),[v,i]),remove:(0,V.useCallback)(async()=>{let e=u?.slug;if(e)try{await f$(`equipment`,e),_.current=null,d(null),await r()}catch(e){throw Z({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete equipment.`,variant:`destructive`}),e}},[u,r]),cloneForEdit:(0,V.useCallback)(async()=>{if(!u||u.registrySource!==`bundled`)return null;let e=v$(i||hc(u),u.slug,u.label),t={...u,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,ownerNoteId:`equipment/${e.slug}`,sourceId:`equipment`,sourcePath:`equipment/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};d(t),a(e.raw);try{let t=await d$({kind:`equipment`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});_.current={id:t.id,revision:t.sourceRevision},await r()}catch(e){throw Z({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[u,i,r]),error:c,isAliasMatch:m}}function b$(e){let{isReady:t,registry:n}=Wk(),{isReady:r,registry:i}=Vk(),[a,o]=(0,V.useState)({efforts:[],usedBy:[]});return(0,V.useEffect)(()=>{if(!t||!r||!e){o({efforts:[],usedBy:[]});return}let n=!1;async function a(){let t=i.list().filter(t=>t.equipment?.includes(e)??!1),r=await X.getEquipmentUsage(e);n||o({efforts:t,usedBy:r})}return a(),()=>{n=!0}},[e,t,r,n,i]),a}function x$(){let{slug:e}=zn(),[t]=Ct(),n=Sn(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{isReady:a,refresh:o}=Wk(),{document:s,setDocument:c,isLoading:l,equipment:u,isEditable:d,notFound:f,cloneForEdit:p,error:m,onLineChange:h,onBlur:g,flush:_}=y$(e),[v,y]=(0,V.useState)([]),b=t.get(`mode`)===`create`,[x,S]=(0,V.useState)(()=>_$(e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``)),C=(0,V.useCallback)(async()=>{let{equipment:e,errors:t}=mc(x);if(t.length>0){Z({title:`Invalid YAML`,description:t.join(`
180
+ `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Z({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Z({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await d$({kind:`equipment`,slug:r,rawContent:x,title:e.label.trim()||zE(r),expectedSourceRevision:0}),await o(),n(ij(r),{replace:!0})}catch(e){Z({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`})}},[x,o,n]);tY({content:b?x:s,scriptBlocks:v});let w=u?.ownerNoteId??(e?`equipment/${e}`:``),T=(0,V.useMemo)(()=>w?oY({id:w,type:`collection`}):null,[w]),E=fY({noteId:w,stamps:T?.stamps??[]}),D=b$(u?.slug),O=(0,V.useMemo)(()=>({efforts:D.efforts.map(e=>({id:e.slug,title:e.label,to:cj(e.slug)})),related:D.usedBy.map(e=>({id:e.noteId,title:e.title,to:rY(e.noteId)})),backlinks:E.backlinks}),[D,E.backlinks]);(0,V.useEffect)(()=>{u&&(window.document.title=`Wod.Wiki - ${u.label}`)},[u]);let k=(0,V.useCallback)(async()=>{if(u)try{let e=await p();e&&(n(ij(e.slug)),Z({title:`Cloned`,description:`Created a custom copy of "${u.label}". You can now edit it.`}))}catch(e){Z({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[p,u,n]);if(!a||l)return(0,H.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,H.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(b){let t=(0,H.jsx)(nR,{primary:(0,H.jsx)(W,{onClick:C,"data-testid":sB.EQUIPMENT_CREATE_BTN,children:`Create Equipment`}),children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Cancel`})});return(0,H.jsx)(`div`,{"data-testid":sB.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:e&&e!==`new`?`New equipment: ${e}`:`New equipment`,actions:t,editor:(0,H.jsx)(`div`,{className:`relative`,"data-testid":`equipment-create-editor`,children:(0,H.jsx)(vK,{value:x,onChange:S,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y})})})})}if(m)return(0,H.jsxs)(`div`,{"data-testid":sB.EQUIPMENT_LOAD_ERROR,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Equipment could not be loaded`}),(0,H.jsx)(`p`,{className:`text-sm text-destructive`,children:m})]}),(0,H.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Back to Equipment`})})]});if(f||!u)return(0,H.jsxs)(`div`,{"data-testid":sB.EQUIPMENT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Equipment “`,e,`” not found`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No equipment definition exists for this slug yet. You can create a new definition page for it.`})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,H.jsx)(W,{onClick:()=>n(`${ij(e??`new`)}?mode=create`),"data-testid":sB.EQUIPMENT_NOT_FOUND_CREATE_BTN,children:`Create Equipment Page`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(Q.equipment),children:`Back to Equipment`})]})]});let A=(0,H.jsxs)(nR,{primary:d?void 0:(0,H.jsxs)(W,{variant:`outline`,onClick:k,"data-testid":sB.EQUIPMENT_DETAIL_CLONE_BTN,children:[(0,H.jsx)(Se,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,H.jsx)(W,{variant:`ghost`,size:`icon`,onClick:()=>Uz()?n(-1):n(Q.equipment),"aria-label":`Back to Equipment`,title:Uz()?`Back`:`Back to Equipment`,children:(0,H.jsx)(M,{className:`size-4`})}),(0,H.jsx)(s$,{"data-testid":sB.EQUIPMENT_DETAIL_SOURCE,variant:u.registrySource===`bundled`?`secondary`:`default`,children:u.registrySource===`bundled`?`Bundled`:`Custom`})]});return(0,H.jsx)(`div`,{"data-testid":sB.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,H.jsx)(fL,{title:u.label,titleTestId:sB.EQUIPMENT_DETAIL_LABEL,actions:A,editor:(0,H.jsxs)(`div`,{className:`relative`,"data-testid":sB.EQUIPMENT_DETAIL_NOTEBOOK_EDITOR,children:[(0,H.jsx)(vK,{noteId:w,value:s,onChange:c,onCursorPositionChange:h,onBlur:g,onSaveRequest:_,onCommitChange:_,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y}),(0,H.jsx)(pY,{data:O,up:T?.up,relatedLabel:`Used in`})]})})})}var S$=`h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`;function C$({open:e,onOpenChange:t,entry:n,mode:r,provider:i,onSaved:a,onCloned:o}){let[s,c]=(0,V.useState)(``),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)([]),[h,g]=(0,V.useState)(!1),[_,v]=(0,V.useState)(null),y=(0,V.useRef)(!1),b=n.id,x=n.journalDate,S=n.slug,C=n.sourceId;(0,V.useEffect)(()=>{e&&(c(x??(r===`clone`?Vj():``)),u(r===`clone`?``:S??``),f(C??``),v(null))},[e,r,b,x,S,C]),(0,V.useEffect)(()=>{if(!e||r!==`relationships`)return;let t=!1;return i.getEntries().then(e=>{t||m(e.filter(e=>e.id!==n.id&&!e.catalog))}).catch(()=>{}),()=>{t=!0}},[e,r,i,n.id]);let w=r===`clone`,T=`note-placement-sources-${n.id}`,E=()=>{y.current||t(!1)};return(0,H.jsx)(lS,{open:e,onClose:E,title:w?`Clone note`:`Note relationships`,description:w?`Independent copy. Results and attachments are not copied.`:void 0,presentation:`sheet`,footer:(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(W,{type:`button`,variant:`outline`,size:`lg`,onClick:E,disabled:h,children:`Cancel`}),(0,H.jsx)(W,{type:`submit`,form:`note-placement-form`,size:`lg`,disabled:h,children:h?`Saving…`:w?`Clone`:`Save`})]}),children:(0,H.jsxs)(`form`,{id:`note-placement-form`,onSubmit:async e=>{if(e.preventDefault(),!y.current){y.current=!0,g(!0),v(null);try{let e=s.trim(),r=l.trim(),c=d.trim(),u=e===``?null:Uj(e);if(e&&!u){v(`Enter a valid date (YYYY-MM-DD).`);return}if(w){if(!e&&!r){v(`Choose a destination date or named page for the clone.`);return}let i=await Kj.create({journalDate:e||void 0,slug:r||void 0,title:n.title,rawContent:n.rawContent,tags:n.tags,sourceId:n.id,type:`journal`});o?.(i),t(!1);return}let f={};if(c!==(C??``)){if(c===``)f.sourceId=null;else try{let e=await Kj.resolve(c);if(!e||e.id===n.id)throw Error(`invalid source`);f.sourceId=e.id}catch{v(`Source note not found.`);return}}if(e!==(x??``)&&(f.journalDate=e===``?null:e,u&&(f.targetDate=u.date.getTime())),r!==(S??``)&&(f.slug=r===``?null:r),Object.keys(f).length===0){t(!1);return}let p=await i.updateEntry(n.id,f);a?.(p),t(!1)}catch{v(`Could not save — your fields are kept. Try again.`)}finally{y.current=!1,g(!1)}}},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-date`,className:`text-sm font-medium`,children:`Journal date`}),(0,H.jsx)(`input`,{id:`note-placement-date`,type:`date`,className:S$,value:s,onChange:e=>c(e.target.value),disabled:h}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:w?`Defaults to the note’s date.`:`Leave empty to detach from the calendar.`})]}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-slug`,className:`text-sm font-medium`,children:`Named page`}),(0,H.jsx)(`input`,{id:`note-placement-slug`,type:`text`,className:S$,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. marathon-block`,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Optional /p/<slug> link. Typing an existing page's slug shares that page with its notes — it does not create a unique copy.`})]}),w?null:(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`note-placement-source`,className:`text-sm font-medium`,children:`Source note`}),(0,H.jsx)(`input`,{id:`note-placement-source`,type:`text`,className:S$,value:d,onChange:e=>f(e.target.value),list:T,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,H.jsx)(`datalist`,{id:T,children:p.map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.title||`Untitled`},e.id))}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Leave empty to clear.`})]}),_&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:_})]})})}var w$=new ID;function T$({noteId:e,theme:t}){let n=Sn(),r=mt(),[i]=Ct(),[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(!1),l=(0,V.useRef)(0),u=(0,V.useRef)(null),d=(0,V.useRef)(async()=>{}),f=r.pathname.startsWith(`/p/`)||a!==null&&!Ca(a),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(null),y=iq();(0,V.useEffect)(()=>{GF().catch(()=>{})},[e]),(0,V.useEffect)(()=>{let t=!1;return o(null),c(!1),m(null),w$.getEntry(e).then(e=>{if(!t){if(!e){c(!0);return}o(e),l.current=e.sourceRevision??0,u.current={rawContent:e.rawContent,blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}}}).catch(()=>{t||c(!0)}),()=>{t=!0}},[e,i]);let b=a?.sourceId;(0,V.useEffect)(()=>{if(v(null),!b)return;let e=!1;return w$.getEntry(b).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[b]);let x=(0,V.useMemo)(()=>a?oY(a):{zone:null,up:null,stamps:[]},[a]);gA(x.zone);let[S,w]=(0,V.useState)([]),[T,E]=(0,V.useState)([]),D=a?.id;(0,V.useEffect)(()=>{if(E([]),w([]),!D)return;let e=!1,t=()=>{X.getSessionsForNote(D).then(t=>{e||E(t)}).catch(()=>{})};t();let n=MV(n=>{!e&&n.noteId===D&&t()});return()=>{e=!0,n()}},[D]);let O=(0,V.useCallback)(async t=>{if(a)try{await d.current();let e=u.current;if(!e)throw Error(`The note draft is unavailable.`);let r=C(),i=await hF({noteId:a.id,rawContent:e.rawContent,blocks:e.blocks,expectedSourceRevision:l.current},t,r);l.current=i.note.sourceRevision,QJ.set(r,{block:i.block,noteId:a.id,captured:i,returnTo:qA(a.id)}),n(QA(r))}catch(t){m({noteId:e,message:`Workout not started. ${t instanceof Error?t.message:String(t)} Your draft is kept.`})}},[a,e,n]);tY({content:a?.rawContent??``,scriptBlocks:S,onStartWorkout:O,results:T});let k=fY(a?{noteId:a.id,stamps:x.stamps}:{noteId:``,stamps:[]}),A=(0,V.useCallback)(e=>{l.current=e.sourceRevision;let t=u.current,n=t?.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));o(t=>t&&{...t,...n?{blocks:e.blocks}:{},sourceRevision:e.sourceRevision})},[]),j=(0,V.useCallback)(async t=>{let n=await Nj.saveNote({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:l.current});return A({rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??l.current}),m(null),o(e=>e?.id===n.id?{...e,title:n.title}:e),{rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0}},[e,A]),{onChange:M,onBlur:N,onLineChange:P,flush:F}=YJ({onSave:async e=>{await j(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])]),onError:t=>m({noteId:e,message:`Save failed. ${t instanceof Error?t.message:String(t)} Your draft is kept. Retry saving.`})});d.current=F;let I=(0,V.useCallback)(e=>{let t=u.current?.rawContent!==e.rawContent||JSON.stringify(Object.values(u.current?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));u.current=e,t&&M(e)},[M]),ee=(0,V.useCallback)(e=>{o(t=>t&&{...t,rawContent:e})},[]),te=(0,V.useCallback)(async e=>{await F();let t=u.current;if(!t)throw Error(`The note draft is unavailable.`);let n=KP({...t,sourceRevision:l.current},e),r=await j(n);u.current=r,o(e=>e&&{...e,...r})},[F,j]),ne=(0,V.useCallback)(()=>Promise.resolve(),[]),re;if(s)re=(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 text-zinc-400`,children:[(0,H.jsx)(`p`,{children:`Note not found.`}),(0,H.jsx)(W,{variant:`outline`,onClick:()=>n(-1),children:`Go back`})]});else if(!a)re=(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`});else{let r=`inline-flex min-h-11 items-center gap-1 rounded-pill border border-border bg-card px-2.5 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,i=(0,H.jsxs)(nR,{label:`Note actions`,children:[(0,H.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`relationships`),children:[(0,H.jsx)(dt,{className:`size-3.5`,"aria-hidden":`true`}),`Note relationships`]}),(0,H.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`clone`),children:[(0,H.jsx)(nt,{className:`size-3.5`,"aria-hidden":`true`}),`Clone`]})]});re=(0,H.jsxs)(TF,{notePersistence:Nj,provider:w$,children:[(0,H.jsx)(fL,{title:a.title,subtitle:qA(a.id),actions:i,editor:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4 px-4 py-6 sm:px-6 min-w-0 max-w-full`,children:[(0,H.jsx)(pY,{data:k,up:x.up}),(a.journalDate||a.slug||a.sourceId)&&(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[a.journalDate&&(0,H.jsx)(Wn,{to:GA(a.journalDate),className:`underline-offset-2 hover:underline`,children:a.journalDate}),a.slug&&(0,H.jsxs)(Wn,{to:tj(a.slug),className:`underline-offset-2 hover:underline`,children:[`/p/`,a.slug]}),a.sourceId&&(0,H.jsxs)(`span`,{children:[`Cloned from`,` `,_?(0,H.jsx)(Wn,{to:qA(_.id),className:`underline-offset-2 hover:underline`,children:_.title||_.id}):(()=>{let e=sY(a.sourceId);return e?(0,H.jsx)(Wn,{to:e.to,className:`underline-offset-2 hover:underline`,children:e.title}):a.sourceId})()]})]}),y?(0,H.jsx)(`div`,{className:`rounded-lg border border-border bg-card p-4 shadow-sm min-h-[240px] focus-within:border-accent/80 transition-colors`,children:(0,H.jsx)(vK,{value:a.rawContent,onChange:ee,onBlur:N,noteId:a.id,noteBlocks:a.blocks,sourceRevision:a.sourceRevision,onIdentityChange:I,onSaved:A,beforeRun:async()=>(await F(),l.current),onSaveRequest:F,onCommitChange:F,onCursorPositionChange:P,readonly:f,theme:t,showLineNumbers:!1,onCompleteWorkout:ne,onBlocksChange:w,placeholder:`Write workout or notes here…`})}):(0,H.jsx)(`div`,{className:`flex items-center justify-center text-zinc-400 text-sm py-8`,children:`Loading…`}),(0,H.jsx)(qP,{noteId:a.id,blocks:a.blocks,sourceRevision:a.sourceRevision,onRevert:f?void 0:te}),p?.noteId===e&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p.message})]})}),h!==null&&(0,H.jsx)(C$,{open:!0,onOpenChange:e=>{e||g(null)},entry:a,mode:h,provider:w$,onSaved:e=>o(t=>t&&t.id===e.id?{...t,journalDate:e.journalDate,slug:e.slug,sourceId:e.sourceId}:t),onCloned:e=>n(`${qA(e.id)}?edit=1`)})]})}return re}var E$=new ID;function D$(e){let t=new Map;for(let n of e){let e=n.tags[0]?.toLowerCase()??`untagged`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`day-group-${e}`,label:e===`untagged`?`Untagged`:`#${e}`,entries:t}))}function O$(e){return Bj(new Date(e.targetDate))}function k$({slug:e,date:t}){let[n,r]=(0,V.useState)(null);(0,V.useEffect)(()=>{let n=!1;return E$.getEntries().then(i=>{if(n)return;let a=i.filter(n=>n.catalog===e&&O$(n)===t);r(a.sort((e,t)=>t.createdAt-e.createdAt))}).catch(()=>{n||r([])}),()=>{n=!0}},[e,t]);let i=(0,V.useMemo)(()=>n?D$(n):[],[n]),{setL3Items:a}=hA();(0,V.useEffect)(()=>{if(i.length===0){a([]);return}let e=i.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return a(e),()=>a([])},[i,a]);let o=n===null?(0,H.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`}):n.length===0?(0,H.jsxs)(`p`,{className:`rounded-lg border border-dashed border-border p-6 text-sm text-muted-foreground`,children:[`No notes in this collection for `,t,`.`]}):(0,H.jsx)(`div`,{className:`flex flex-col gap-6`,children:i.map(e=>(0,H.jsxs)(`section`,{id:e.id,className:`flex flex-col rounded-lg border border-border overflow-hidden`,children:[(0,H.jsxs)(`h3`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[e.label,` · `,e.entries.length]}),(0,H.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:e.entries.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(Wn,{to:qA(e.id),className:`flex flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:new Date(e.createdAt).toLocaleTimeString()})]})},e.id))})]},e.id))});return(0,H.jsx)(fL,{title:t,subtitle:e,editor:(0,H.jsx)(`div`,{className:`flex flex-col gap-6 px-4 py-6 sm:px-6`,children:o})})}var A$=`__new__`;function j$(e){return e.open?(0,H.jsx)(M$,{...e},e.subsetQuery??`(whole-store)`):null}function M$({onOpenChange:e,initialQuery:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a}){let o=Sn(),{items:s,loading:c}=Lj(),l=s.filter(e=>e.editable),[u,d]=(0,V.useState)(l[0]?.slug??A$),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(null),g=()=>e(!1);return(0,H.jsx)(FX,{open:!0,onClose:g,mode:`add`,initialWql:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a,onApply:async e=>{h(null);let t={title:e.title,question:e.question,type:e.type,spanCols:e.spanCols,spanFull:e.spanFull,wql:e.wql,attributes:e.attributes};try{if(u===A$){let e=f.trim()||`New Dashboard`,n=await Jj.createDashboard(e);await Kj.update(n,b_(n.rawContent,t)),g(),o(sj(f_(e)))}else{let e=await Kj.resolve(u);await Kj.update(e,b_(e.rawContent,t)),g(),o(sj(u))}}catch(e){let t=e instanceof Error?e.message:String(e);throw h(t),e}},applyLabel:`Add to dashboard`,destination:(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Destination`}),c?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading dashboards…`}):(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[l.map(e=>(0,H.jsx)(`button`,{type:`button`,"aria-pressed":u===e.slug,onClick:()=>d(e.slug),className:`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===e.slug?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.title},e.slug)),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-dest-new`,"aria-pressed":u===A$,onClick:()=>d(A$),className:`flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===A$?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,H.jsx)(Kt,{className:`size-3`}),` New dashboard`]})]}),u===A$&&(0,H.jsx)(`input`,{type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`New Dashboard`,"data-testid":`dashboard-new-title`,className:`w-full sm:w-64 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),m&&(0,H.jsxs)(`p`,{role:`alert`,"data-testid":`dashboard-save-error`,className:`mt-2 text-xs text-destructive font-mono`,children:[`Could not save: `,m]})]})})}function N$({catalog:e}){let[t,n]=(0,V.useState)([]),[r,i]=(0,V.useState)(!1),[a,o]=(0,V.useState)(``);return(0,V.useEffect)(()=>{let t=!1,r=()=>{e.listByPrefix(a,50).then(e=>{t||n(e)}).catch(()=>{})};r();let i=e.onChange?.(()=>r());return()=>{t=!0,i?.()}},[e,a]),(0,H.jsxs)(`section`,{className:`rounded-lg border p-3 text-sm`,"data-testid":`available-fields`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`flex w-full items-center justify-between font-medium`,onClick:()=>i(e=>!e),children:[(0,H.jsxs)(`span`,{children:[`Available fields (`,t.length,`)`]}),(0,H.jsx)(`span`,{"aria-hidden":!0,children:r?`▾`:`▸`})]}),r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`input`,{className:`mt-2 w-full rounded border px-2 py-1`,placeholder:`Filter fields…`,value:a,onChange:e=>o(e.target.value)}),(0,H.jsxs)(`ul`,{className:`mt-2 max-h-64 space-y-1 overflow-auto`,children:[t.map(e=>(0,H.jsxs)(`li`,{className:`flex items-baseline justify-between gap-2`,children:[(0,H.jsx)(`span`,{className:`font-mono`,children:e.path}),(0,H.jsxs)(`span`,{className:`text-xs opacity-70`,children:[e.kind,e.dimension?` · ${e.dimension}`:``,e.units.length?` · ${e.units.join(`/`)}`:``,e.spellings.length&&e.spellings[0]!==e.path?` · “${e.spellings[0]}”`:``]})]},e.id)),t.length===0&&(0,H.jsx)(`li`,{className:`opacity-60`,children:`No discovered fields for this prefix.`})]})]})]})}function P$(e){return{id:e.id,path:e.path,kind:e.kind,...e.dimension?{dimension:e.dimension}:{},units:Object.keys(e.units??{}),spellings:Object.keys(e.spellings??{})}}var F$=new class{storageInstance;listeners=new Set;constructor(e=xD){this.storageInstance=e}async listByPrefix(e,t=20){let n=e&&typeof IDBKeyRange<`u`?IDBKeyRange.bound(e,`${e}\uFFFF`,!1,!0):void 0;return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,n,t)).map(P$)}async lookup(e){return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,e)).map(P$)}async listValues(e,t,n=20){let r=await this.lookup(e),i=[];for(let e of r){if(i.length>=n)break;let r=t&&typeof IDBKeyRange<`u`?IDBKeyRange.bound([e.id,t],[e.id,`${t}\uFFFF`],!1,!0):void 0,a=await this.storageInstance.readonly(`field_values`).getAllFromIndex(`by-field`,r,n-i.length);for(let e of a)i.push({fieldId:e.fieldId,value:e.value})}return i}notifyChanged(){for(let e of this.listeners)e()}observeStore(e){}}(xD);function I$({label:e,value:t,className:n}){return(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 rounded border border-border bg-background/60 px-2 py-1`,children:[(0,H.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground`,children:e}),(0,H.jsx)(`span`,{className:U(`font-mono text-xs`,n??`text-foreground`),children:t})]})}function L$(e){return e.kind===`relative`?`last ${e.size}${e.unit}`:e.end?`from ${e.start} to ${e.end}`:`from ${e.start}`}function R$({parsed:e}){if(e.error)return(0,H.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:e.error});if(rm(e)){let t=e.source.kind===`dataset`?(0,H.jsx)(I$,{label:`source`,value:e.source.name,className:`text-blue-400 dark:text-blue-300`}):(0,H.jsx)(I$,{label:`source`,value:`target`in e.source.query?`:${e.source.query.target}`:`:${e.source.query.agg}`,className:`text-blue-400 dark:text-blue-300`});return(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t,e.transforms.map((e,t)=>(0,H.jsx)(I$,{label:`fn ${t+1}`,value:`${e.agg}:${e.metric}`,className:`text-green-400 dark:text-green-300`},t)),e.sink&&(0,H.jsx)(I$,{label:`sink`,value:`:${e.sink.head}`,className:`text-purple-400 dark:text-purple-300`})]})}let t=e.window&&(0,H.jsx)(I$,{label:`window`,value:L$(e.window),className:`text-sky-400 dark:text-sky-300`}),n=e.filters.map((e,t)=>(0,H.jsx)(I$,{label:e.negate?`exclude`:`filter`,value:`${e.key}:${e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`)}`,className:`text-amber-400 dark:text-amber-300`},t));return nm(e)?(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,H.jsx)(I$,{label:`aggregate`,value:e.agg,className:`text-blue-400 dark:text-blue-300`}),(0,H.jsx)(I$,{label:`metric`,value:e.metric}),n,e.groupBy.map((e,t)=>(0,H.jsx)(I$,{label:`group by`,value:e,className:`text-green-400 dark:text-green-300`},t)),e.rollup&&(0,H.jsx)(I$,{label:`rollup`,value:`${e.rollup.size}${e.rollup.unit}`,className:`text-purple-400 dark:text-purple-300`}),e.displayUnit&&(0,H.jsx)(I$,{label:`in`,value:e.displayUnit,className:`text-pink-400 dark:text-pink-300`}),t,e.join&&(0,H.jsx)(I$,{label:`where`,value:`:${e.join.target}`,className:`text-teal-400 dark:text-teal-300`})]}):tm(e)?(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,H.jsx)(I$,{label:`target`,value:e.target,className:`text-blue-400 dark:text-blue-300`}),n,t,e.join&&(0,H.jsx)(I$,{label:`where`,value:`${e.join.agg}:${e.join.metric}`,className:`text-teal-400 dark:text-teal-300`})]}):null}function z$({result:e}){let{parsed:t,stages:n}=e;if(t.error)return null;let r=t.groupBy.find(e=>e===`day`||e===`week`),i=r?`by ${r}`:t.rollup?`rollup ${t.rollup.size}${t.rollup.unit}`:`no rollup`,a=t.groupBy.length?`by {${t.groupBy.join(`, `)}}`:`single series`,o=[{n:1,name:`SELECT`,desc:`tag + time index scan`,count:n.selected,unit:`points`},{n:2,name:`BUCKET`,desc:i,count:n.buckets,unit:`buckets`},{n:3,name:`AGGREGATE`,desc:`${t.agg} per bucket`,count:n.aggregated,unit:`values`},{n:4,name:`GROUP`,desc:a,count:n.groups,unit:`series`}];return(0,H.jsx)(`div`,{className:`flex items-center gap-0 mt-4 overflow-x-auto`,children:o.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex items-center`,children:[(0,H.jsxs)(`div`,{className:`border border-border rounded-lg bg-background/60 px-3 py-2 min-w-[130px]`,children:[(0,H.jsxs)(`div`,{className:`text-[10px] font-bold tracking-wide`,style:{color:qb[t%qb.length]},children:[e.n,`. `,e.name]}),(0,H.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:e.desc}),(0,H.jsxs)(`div`,{className:`text-sm font-semibold tabular-nums mt-0.5`,children:[e.count.toLocaleString(),` `,(0,H.jsx)(`span`,{className:`text-[10px] font-normal text-muted-foreground`,children:e.unit})]})]}),t<3&&(0,H.jsx)(Vn,{size:16,className:`text-muted-foreground mx-1 shrink-0`})]},e.n))})}function B$({matched:e,displayUnit:t}){let[n,r]=(0,V.useState)(!1);if(e.length===0)return null;let i=e=>{let t=[];return e.effortSlug&&t.push(`effort:${e.effortSlug}`),e.discipline&&t.push(`discipline:${e.discipline}`),e.intensityTier&&t.push(`intensity:${e.intensityTier}`),e.origin&&t.push(`origin:${e.origin}`),t},a=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};return(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg mt-3`,children:[(0,H.jsxs)(`button`,{onClick:()=>r(!n),className:`w-full flex items-center gap-2 px-4 py-2.5 text-sm text-muted-foreground hover:text-foreground`,children:[n?(0,H.jsx)(un,{size:14}):(0,H.jsx)(Vn,{size:14}),`Raw metric points behind this query (`,e.length,`)`,(0,H.jsx)(`span`,{className:`text-[11px] ml-auto`,children:`one row per fact from the analytics store`})]}),n&&(0,H.jsxs)(`div`,{className:`px-4 pb-3 overflow-x-auto`,children:[(0,H.jsxs)(`table`,{className:`w-full text-[11px] font-mono`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`text-muted-foreground text-left border-b border-border`,children:[(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`ts`}),(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`metric`}),(0,H.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`value`}),(0,H.jsx)(`th`,{className:`py-1.5 font-normal`,children:`tags`})]})}),(0,H.jsx)(`tbody`,{children:e.slice(0,12).map(e=>{let n=e.unit??e.metricUnit,r=typeof e.value==`number`?e.value:void 0,o=t&&r!==void 0&&n&&Eh(n)===Eh(t)?Th(r,n,t):void 0;return(0,H.jsxs)(`tr`,{className:`border-b border-border/40`,children:[(0,H.jsx)(`td`,{className:`py-1.5 pr-4 text-muted-foreground whitespace-nowrap`,children:a(e.timestamp)}),(0,H.jsx)(`td`,{className:`py-1.5 pr-4 text-primary whitespace-nowrap`,children:e.metricKey}),(0,H.jsxs)(`td`,{className:`py-1.5 pr-4 tabular-nums`,children:[String(e.value),n?` ${n}`:``,o!==void 0&&n!==t?` → ${o.toLocaleString()} ${t}`:``]}),(0,H.jsx)(`td`,{className:`py-1.5 text-muted-foreground`,children:i(e).map(e=>(0,H.jsx)(`span`,{className:`inline-block bg-background/80 rounded px-1.5 py-0.5 mr-1 mb-0.5`,children:e},e))})]},e.id)})})]}),e.length>12&&(0,H.jsxs)(`div`,{className:`text-[11px] text-muted-foreground pt-2`,children:[`… `,e.length-12,` more points`]})]})]})}var V$=[`totalVolume`,`tis`,`sessionLoad`,`totalReps`],H$=[`effort`,`discipline`,`intensity`,`tags`,`note`,`origin`];function U$(){let[e,t]=(0,V.useState)(V$);return(0,V.useEffect)(()=>{let e=!1;async function n(){try{let n=Date.now(),r=n-31536e6,i=await XF.getFactsByTimeRange(r,n);if(e)return;let a=new Set([...V$,...i.map(e=>e.metricKey)].filter(e=>e!==void 0));t(Array.from(a).sort())}catch{}}return n(),()=>{e=!0}},[]),{metricKeys:e,tagKeys:H$}}var W$=[4,8,16],G$=`sum:totalVolume{}`;function K$(e){let t=Number.parseInt(e??``,10);return W$.includes(t)?t:16}function q$(e={}){let{defaultQuery:t=G$,runOnLanding:n=!1}=e,[r,i]=Ct(),a=r.get(`q`)??``,o=K$(r.get(`weeks`)),[s,c]=(0,V.useState)(()=>a&&!Y(a).error?a:t),[l,u]=(0,V.useState)(a||(n?t:``)),d=(0,V.useRef)(s);d.current=s;let f=(0,V.useRef)(r);f.current=r;let p=(0,V.useRef)(!0),m=(0,V.useRef)(a);m.current=a;let h=(0,V.useRef)(a);return(0,V.useEffect)(()=>{a!==h.current&&(h.current=a,d.current!==a&&(p.current=!0,c(a&&!Y(a).error?a:t),u(a||(n?t:``))))},[a,t,n]),{draft:s,setDraft:(0,V.useCallback)(e=>{if(e===d.current)return;let t=new URLSearchParams(f.current);t.set(`q`,e),i(t,{replace:!p.current}),p.current=!1,c(e)},[i]),submitted:l,submit:(0,V.useCallback)(e=>{let t=e??d.current;if(Y(t).error)return;if(p.current&&m.current===t){u(t);return}let n=new URLSearchParams(f.current);n.set(`q`,t),i(n,{replace:!0}),p.current=!0,u(t)},[i]),weeks:o,setWeeks:(0,V.useCallback)(e=>{let t=new URLSearchParams(f.current);t.set(`weeks`,String(e)),i(t,{replace:!0})},[i])}}function J$({weeks:e,onWeeks:t,unitForced:n}){let[r,i]=(0,V.useState)(!1),a=(0,V.useRef)(null),{unit:o,setUnit:s}=jx();(0,V.useEffect)(()=>{if(!r)return;let e=e=>{a.current?.contains(e.target)||i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]);let c=e=>()=>{e(),i(!1)};return(0,H.jsxs)(`div`,{ref:a,className:`relative`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"data-testid":`explorer-options`,"aria-expanded":r,className:U(`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors`,r?`border-primary/60 text-primary bg-primary/10`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:[(0,H.jsx)(Zt,{className:`size-3.5`}),`Options`,(0,H.jsx)(un,{className:U(`size-3 transition-transform`,r&&`rotate-180`)})]}),r&&(0,H.jsxs)(`div`,{className:`absolute right-0 top-full z-40 mt-1 w-72 rounded-xl border border-border bg-card shadow-xl p-1.5`,"data-testid":`explorer-options-menu`,children:[(0,H.jsx)(`div`,{className:`px-2 pt-1.5 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:`Range`}),W$.map(n=>(0,H.jsxs)(`button`,{type:`button`,onClick:c(()=>t(n)),className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs text-foreground hover:bg-muted transition-colors`,children:[(0,H.jsx)(`span`,{className:`w-3.5 text-primary`,children:e===n?(0,H.jsx)(Zn,{className:`size-3.5`}):null}),`Past `,n,` weeks`]},n)),(0,H.jsxs)(`div`,{className:`mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:[`Units`,n?` — pinned by query`:``]}),[`kg`,`lb`].map(e=>(0,H.jsxs)(`button`,{type:`button`,disabled:n,onClick:c(()=>s(e)),className:U(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs transition-colors`,n?`text-muted-foreground/50 cursor-not-allowed`:`text-foreground hover:bg-muted`),children:[(0,H.jsx)(`span`,{className:`w-3.5 text-primary`,children:o===e?(0,H.jsx)(Zn,{className:`size-3.5`}):null}),e]},e))]})]})}var Y$=X,X$=`sample`,Z$=6048e5;function Q$(e){return Math.round(e*10)/10}var $$={thruster:`high`,"pull-up":`high`,"push-up":`moderate`,"air-squat":`moderate`,"double-under":`high`,"sit-up":`low`,rowing:`moderate`,running:`moderate`,"recovery-run":`low`,"back-squat":`high`,deadlift:`high`},e1={fran:`high`,cindy:`moderate`,annie:`moderate`,rowing:`moderate`,running:`moderate`,strength:`high`,recoveryRun:`low`};function t1(e,t,n,r){return{effortSlug:n,discipline:r,reps:e,loadLbs:t,tisSeconds:Q$(e*(n===`thruster`?2.2:1.6))}}function n1(e,t,n){let r=330-n*16,i=Math.max(180,Q$(r+(Math.random()-.5)*20)),a=95+n*5;return{noteId:`sample-fran-${t}-${crypto.randomUUID()}`,title:`Sample — Fran (week ${16-t})`,workoutType:`fran`,timestamp:e-t*Z$,durationSeconds:i,movements:[t1(45,a,`thruster`,`strength`),t1(45,0,`pull-up`,`gymnastics`)]}}function r1(e,t,n){let r=10+n+Math.round((Math.random()-.5)*2),i=Math.max(8,r);return{noteId:`sample-cindy-${t}-${crypto.randomUUID()}`,title:`Sample — Cindy (week ${16-t})`,workoutType:`cindy`,timestamp:e-t*Z$,durationSeconds:1200,movements:[{effortSlug:`pull-up`,discipline:`gymnastics`,reps:i*5,loadLbs:0,tisSeconds:Q$(i*5*1.5)},{effortSlug:`push-up`,discipline:`gymnastics`,reps:i*10,loadLbs:0,tisSeconds:Q$(i*10*1.2)},{effortSlug:`air-squat`,discipline:`bodyweight`,reps:i*15,loadLbs:0,tisSeconds:Q$(i*15*1.1)}]}}function i1(e,t,n){let r=540-n*22,i=Math.max(360,Q$(r+(Math.random()-.5)*30));return{noteId:`sample-annie-${t}-${crypto.randomUUID()}`,title:`Sample — Annie (week ${16-t})`,workoutType:`annie`,timestamp:e-t*Z$,durationSeconds:i,movements:[{effortSlug:`double-under`,discipline:`gymnastics`,reps:150,loadLbs:0,tisSeconds:Q$(75)},{effortSlug:`sit-up`,discipline:`bodyweight`,reps:150,loadLbs:0,tisSeconds:Q$(195)}]}}function a1(e,t,n){let r=135+n*5,i=185+n*5;return{noteId:`sample-strength-${t}-${crypto.randomUUID()}`,title:`Sample — Strength accessory (week ${16-t})`,workoutType:`strength`,timestamp:e-t*Z$,durationSeconds:1800,movements:[{effortSlug:`back-squat`,discipline:`strength`,reps:25,loadLbs:r,tisSeconds:Q$(62.5)},{effortSlug:`deadlift`,discipline:`strength`,reps:15,loadLbs:i,tisSeconds:Q$(42)}]}}function o1(e,t,n){let r=2e3+n*250,i=Q$(r/2+(Math.random()-.5)*30);return{noteId:`sample-rowing-${t}-${crypto.randomUUID()}`,title:`Sample — Rowing (week ${16-t})`,workoutType:`rowing`,timestamp:e-t*Z$,durationSeconds:i,movements:[{effortSlug:`rowing`,discipline:`rowing`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function s1(e,t,n){let r=5e3+n*500,i=Q$(r/2.8+(Math.random()-.5)*60);return{noteId:`sample-running-${t}-${crypto.randomUUID()}`,title:`Sample — Running (week ${16-t})`,workoutType:`running`,timestamp:e-t*Z$,durationSeconds:i,movements:[{effortSlug:`running`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function c1(e,t,n){let r=3e3+n*50,i=Q$(r/2.2+(Math.random()-.5)*60);return{noteId:`sample-recovery-run-${t}-${crypto.randomUUID()}`,title:`Sample — Recovery run (week ${16-t})`,workoutType:`recoveryRun`,timestamp:e-t*Z$,durationSeconds:i,movements:[{effortSlug:`recovery-run`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function l1(e){let t=[];for(let n=0;n<16;n++){let r=Math.floor(n/4);t.push(a1(e,n,n)),n%4==0?t.push(n1(e,n,r)):n%4==1?t.push(r1(e,n,r)):n%4==2?t.push(i1(e,n,r)):n===3||n===11?t.push(o1(e,n,r)):(n===7||n===15)&&t.push(s1(e,n,r)),t.push(c1(e,n,n))}return t.sort((e,t)=>e.timestamp-t.timestamp)}function u1(e){let t=e.timestamp,n=e1[e.workoutType],r=e.movements.reduce((e,t)=>e+t.reps,0),i=e.movements.reduce((e,t)=>e+t.reps*t.loadLbs,0),a=e.movements.reduce((e,t)=>e+t.tisSeconds,0),o=e.movements.reduce((e,t)=>e+(t.distanceMeters??0),0),s=Q$(i/100+r+e.durationSeconds/10),c=[],l=(e,n,r,i,a)=>{let o={canonicalKey:i};a?.effortSlug&&(o.effortSlug=a.effortSlug),a?.discipline&&(o.effortDiscipline=a.discipline),a?.intensityTier&&(o.effortIntensityTier=a.intensityTier);let s={id:c.length,outputType:`analytics`,timeSpan:{started:t},metrics:[{type:G.Label,value:e,origin:`analyzed`},{type:G.Metric,value:n,unit:r,metadata:o,origin:`analyzed`}],sourceBlockKey:``,stackLevel:0};c.push(s)};if(l(`Elapsed time`,e.durationSeconds,`s`,`elapsed`,{intensityTier:n}),l(`Total reps`,r,`reps`,`totalReps`,{intensityTier:n}),l(`Time in motion`,Q$(a),`s`,`tis`,{intensityTier:n}),i>0&&l(`Total volume`,Q$(i),`lb`,`totalVolume`,{intensityTier:n}),o>0){let t=e.movements.find(e=>e.distanceMeters&&e.distanceMeters>0)?.discipline;l(`Total distance`,Q$(o),`m`,`totalDistance`,{discipline:t,intensityTier:n})}l(`Session load`,s,`AU`,`sessionLoad`,{intensityTier:n});for(let t of e.movements){let e=t.reps*t.loadLbs,n=$$[t.effortSlug]??`moderate`,r={effortSlug:t.effortSlug,discipline:t.discipline,intensityTier:n};l(`Total reps`,t.reps,`reps`,`totalReps`,r),l(`Time in motion`,t.tisSeconds,`s`,`tis`,r),e>0&&l(`Total volume`,Q$(e),`lb`,`totalVolume`,r),l(`Session load`,Q$(e/100+t.reps+t.tisSeconds/10),`AU`,`sessionLoad`,r)}return c}function d1(e,t){let n=`${`sample-${e.noteId}`}-result`,r=e.timestamp,i=r+e.durationSeconds*1e3;return{id:n,noteId:e.noteId,blockId:`sample-block`,blockVersion:1,blockContentId:t,origin:`journal`,status:`completed`,createdAt:Date.now(),startTime:r,endTime:i,duration:e.durationSeconds*1e3,completed:!0}}async function f1(){return(await Y$.getTagByLabel(X$))?.id}async function p1(){return(await Y$.getNotesForTag(X$)).map(e=>e.id)}async function m1(){let e=await p1();return e.length!==0&&(await Y$.scanAll()).some(t=>e.includes(t.noteId))}async function h1(){if(await m1()){let e=await p1();return{facts:(await Y$.scanAll()).filter(t=>t.grain===`summary`&&e.includes(t.noteId)).length}}let e=l1(Date.now()),t=0;for(let n of e){let e=n.movements.map(e=>`${e.distanceMeters?`${e.distanceMeters}m`:e.reps} ${e.effortSlug.replaceAll(`-`,` `)}${e.loadLbs?` ${e.loadLbs}lb`:``}`).join(`
181
+ `),r=`# ${n.title}\n\n\`\`\`log\n${e}\n\`\`\`\n`,i=Aa(r,{sourceRevision:1,createId:()=>`sample-block`}),a=u1(n),o=d1(n,va(e)),s={noteId:n.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:n.timestamp};t+=await Y$.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`],async e=>{await e.saveNoteSource({noteId:n.noteId,rawContent:r,blocks:i,expectedSourceRevision:0,metadata:{title:n.title},noteType:`playground`,createdAt:n.timestamp}),await e.setNoteTags(n.noteId,[X$]),await e.saveSession(o),await e.appendEvents(sg(a,s));let t=cg(a,s);return await e.finalizeSummaries(o.id,t),t.length})}return{facts:t}}async function g1(){let e=await p1();if(e.length!==0){for(let t of e)await Y$.deleteEvents((await Y$.getEventsForNote(t)).map(e=>e.id)),await Y$.deleteNote(t);if((await Y$.getNotesForTag(X$)).length===0){let e=await f1();e&&await Y$.deleteTag(e)}}}function _1({result:e,onChanged:t,layout:n=`inline`,refreshKey:r}){let[i,a]=(0,V.useState)(void 0),[o,s]=(0,V.useState)(!1),c=(0,V.useCallback)(async()=>{a(await m1()),s(!1)},[]);(0,V.useEffect)(()=>{c()},[c,r]);let l=async()=>{await h1(),await c(),t?.()},u=(0,H.jsxs)(`div`,{className:`flex items-center justify-center gap-3 rounded-md border border-border bg-muted/50 px-3 py-2 text-xs text-foreground`,children:[(0,H.jsx)(`span`,{children:`Sample data loaded`}),(0,H.jsx)(`button`,{onClick:async()=>{await g1(),await c(),t?.()},className:`font-medium text-destructive hover:text-destructive/80 transition-colors`,children:`Purge sample data`}),(0,H.jsx)(`button`,{onClick:()=>s(!0),className:`text-muted-foreground hover:text-foreground transition-colors`,"aria-label":`Dismiss`,children:(0,H.jsx)(Te,{size:14})})]});if(n===`banner`)return i&&!o?u:null;let d=i?o?null:u:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2`,children:`Facts appear when you log or run workouts.`}),(0,H.jsxs)(`div`,{className:`flex items-center justify-center gap-3`,children:[(0,H.jsx)(`button`,{onClick:l,className:`text-xs font-medium rounded-md bg-primary text-primary-foreground px-3 py-1.5 hover:opacity-90 transition-opacity`,children:`Preview with sample data`}),(0,H.jsx)(Wn,{to:`/collections`,className:`text-xs text-primary underline-offset-2 hover:underline`,children:`Log your first workout`})]})]});return n===`card`?(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-6 flex flex-col items-center justify-center text-sm text-muted-foreground`,children:[e!==void 0&&(0,H.jsx)(Bb,{result:e}),i!==void 0&&d&&(0,H.jsx)(`div`,{className:`mt-3`,children:d})]}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center`,children:[e!==void 0&&(0,H.jsx)(Bb,{result:e}),i!==void 0&&d&&(0,H.jsx)(`div`,{className:`mt-3`,children:d})]})}var v1=`:dashboard{}`,y1=864e5,b1=`agg:metric{filters} by {dims} .rollup(period)`,x1=new Set([`tags`,`catalog`,`text`,`type`,`has`]);function S1(e){let t=e.find(e=>e.key===`source`&&!e.negate);return t?t.values.map(e=>e.value).join(`|`):null}function C1({entries:e,stickyOffset:t,idPrefix:n=``}){return(0,H.jsx)(`div`,{className:`-mx-4`,children:CZ(e,`date`).map(e=>(0,H.jsxs)(`div`,{id:`${n}${e.id}`,className:`flex flex-col`,children:[(0,H.jsx)(oL,{top:t,icon:(0,H.jsx)(qt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,meta:(0,H.jsx)(`span`,{"data-testid":`library-group-count`,className:`font-bold tabular-nums`,children:e.entries.length})}),(0,H.jsx)(`div`,{className:`flex flex-col gap-0 pb-1`,children:e.entries.map(e=>(0,H.jsx)(lQ,{entry:e,dateLabel:e.date?vz(e.date):void 0},e.block?`${e.id}#${e.block.blockId}`:e.id))})]},e.id))})}function w1(e,t){if(e===t)return!0;let n=Y(e),r=Y(t);return!n.error&&!r.error&&Km(n)===Km(r)}function T1({actions:e}){(0,V.useEffect)(()=>{},[]);let t=(0,V.useMemo)(()=>HM(`/dashboards`),[]),{draft:n,setDraft:r,submitted:i,submit:a,weeks:o,setWeeks:s}=q$({defaultQuery:t.defaultWql??v1,runOnLanding:!0}),{unit:c}=jx(),{forced:l}=(0,V.useMemo)(()=>Mx(i,c),[i,c]),[u,d]=(0,V.useState)(void 0),[f,p]=(0,V.useState)(void 0),[m,h]=(0,V.useState)(void 0),[g,_]=(0,V.useState)(void 0),[v,y]=(0,V.useState)(!1),[b,x]=(0,V.useState)(!1),[S,C]=(0,V.useState)(!0),w=U$(),T=t.typeOptions,E=(0,V.useMemo)(()=>Y(n),[n]),D=S1(tm(E)?E.filters:[]),O=tm(E)&&E.window?L$(E.window):null,k=aL(104),A=!E.error&&n.trim().length>0,j=A&&S,M=(0,V.useMemo)(()=>{if(!A)return null;if(tm(E))return n;if(nm(E)&&E.join){let e=E.join;return Km({family:`find`,raw:``,target:e.target,filters:e.filters,window:e.last?{kind:`relative`,size:e.last.size,unit:e.last.unit}:void 0})}return null},[E,n,A]),N=(0,V.useMemo)(()=>{if(!i)return null;let e=Y(i);if(tm(e)||e.error)return null;if(e.join){let t=e.join;return Km({family:`find`,raw:``,target:t.target,filters:t.filters,window:t.last?{kind:`relative`,size:t.last.size,unit:t.last.unit}:void 0})}return Km({family:`find`,raw:``,target:`note`,filters:e.filters.filter(e=>x1.has(e.key)&&!e.negate),window:{kind:`relative`,size:o,unit:`w`}})},[i,o]);(0,V.useEffect)(()=>{if(!N){h(void 0);return}let e=!1;return kI(N).then(t=>{e||h(t)}).catch(()=>{e||h(void 0)}),()=>{e=!0}},[N]);let[P,F]=(0,V.useState)(0),[I,ee]=(0,V.useState)(!1),[te,ne]=(0,V.useState)(!1);(0,V.useEffect)(()=>{let e=!1;if(!i){d(void 0),p(void 0),_(void 0),y(!1);return}y(!0);let t=Y(i);if(tm(t))d(void 0),t.target===`effort`?XF.runFind(t).then(t=>{e||(_(t.efforts??[]),p([]))}).catch(()=>{e||(_(void 0),p(void 0))}).finally(()=>{e||y(!1)}):kI(i).then(t=>{e||(p(t),_([]))}).catch(()=>{e||(p(void 0),_(void 0))}).finally(()=>{e||y(!1)});else{p(void 0),_(void 0);let t=Date.now(),n=t-o*7*y1;XF.runQuery(i,{rangeStart:n,rangeEnd:t,preferredUnit:c}).then(t=>{e||d(t)}).catch(()=>{e||d(void 0)}).finally(()=>{e||y(!1)})}return()=>{e=!0}},[i,o,P,c]);let re=zb(u),ie=e=>{let t=QZ(n,e);r(t),a(t)},{setL3Items:ae}=hA(),oe=(0,V.useMemo)(()=>f!==void 0&&f.length>0?CZ(f,`date`):[],[f]);(0,V.useEffect)(()=>{if(oe.length===0){ae([]);return}let e=oe.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return ae(e),()=>ae([])},[oe,ae]);let se=Yj.find(e=>e.query===i)?.question??`custom query`,ce=(0,V.useMemo)(()=>{let e=Y(i);return e.error?i:Km(e)},[i]),L=u!==void 0&&(w1(u.parsed.raw,n)||u.parsed.raw===i&&n===ce),le=!i||!v&&re.kind===`empty`,ue=(0,H.jsxs)(`button`,{type:`button`,"data-testid":`inspect-pipeline`,"aria-expanded":I,onClick:()=>ee(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[I?(0,H.jsx)(un,{size:12}):(0,H.jsx)(Vn,{size:12}),`Inspect pipeline`]});return(0,H.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,children:[(0,H.jsx)(N$,{catalog:F$}),(0,H.jsx)($I,{title:`Metric Explorer`,actions:(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,H.jsx)(J$,{weeks:o,onWeeks:s,unitForced:l}),e]})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-h-0 p-4`,children:[(0,H.jsx)(`div`,{className:`min-w-[280px]`,children:(0,H.jsx)(EC,{query:n,onQueryChange:r,onValidationChange:e=>C(e.valid),onSubmit:e=>a(e),actionLabel:`Run`,preferredChoices:T,showDiagnostics:!1,placeholder:b1,diagnosticsActions:(0,H.jsxs)(`button`,{type:`button`,"data-testid":`save-query`,disabled:!j,onClick:()=>x(!0),title:`Save this query — decide where it lands (dashboard, …)`,className:`flex min-h-12 items-center gap-1.5 rounded-lg border border-primary/40 text-primary px-3 text-[11px] font-semibold hover:bg-primary/10 transition-all shrink-0 disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,H.jsx)(kt,{size:12}),` Save`]})})}),(0,H.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1`,"data-testid":`explorer-meta`,children:[n.trim().length>0&&(0,H.jsx)(`span`,{"data-testid":`draft-validity`,className:`mr-1 inline-flex items-center gap-1 text-[11px]`,children:E.error?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-mono text-red-600`,children:[(0,H.jsx)(gt,{size:11,className:`shrink-0`}),` `,E.error]}):(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-green-600`,children:[(0,H.jsx)(yn,{size:11,className:`shrink-0`}),` valid`]})}),w.metricKeys.map(e=>(0,H.jsx)(`button`,{type:`button`,disabled:!j||!nm(E),title:A&&!nm(E)?`Metric shortcuts apply to measure queries — pivot the kind through the composer first`:void 0,onClick:()=>ie(e),className:U(`rounded-full border px-2 py-0.5 text-[11px] font-mono transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,n.includes(e)?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:e},e)),(0,H.jsx)(`span`,{className:`mx-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/50`,children:`filters`}),w.tagKeys.map(e=>(0,H.jsx)(`span`,{className:`rounded-full border border-border/60 px-2 py-0.5 text-[11px] font-mono text-muted-foreground/70`,children:e},e))]}),(0,H.jsx)(`section`,{className:`min-w-0`,children:tm(E)?(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-4`,children:[(0,H.jsxs)(`div`,{className:`text-[11px] uppercase tracking-wider text-muted-foreground mb-2`,children:[`Find `,E.target,D&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`in `,D]}),O&&(0,H.jsx)(`span`,{className:`ml-1`,children:O})]}),E.error?(0,H.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:E.error}):v?(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Searching…`}):g&&g.length>0?(0,H.jsx)(`div`,{className:`flex flex-col divide-y divide-border/50`,children:g.map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-3 py-2.5`,children:[(0,H.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground font-mono`,children:e.slug}),e.baseAttributes.discipline&&(0,H.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground`,children:e.baseAttributes.discipline})]},e.slug))}):f&&f.length>0?(0,H.jsx)(C1,{entries:f,stickyOffset:k}):(0,H.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`No `,E.target,`s found.`]})]})}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsx)(_1,{layout:`banner`,refreshKey:P,onChanged:()=>F(e=>e+1)})}),E.error&&i&&(0,H.jsx)(`div`,{"data-testid":`explorer-results-stale`,className:`mt-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs font-medium text-amber-700`,children:`Stale — showing the last run's results; the current draft is invalid and not applied.`}),(0,H.jsx)(`div`,{className:`mt-3`,children:(0,H.jsx)(Ib,{title:`Query result`,question:se,query:i||`(empty)`,children:(0,H.jsx)(`div`,{className:`h-64`,children:i?v?(0,H.jsx)(Bb,{result:void 0}):re.kind===`error`?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center text-sm text-destructive font-mono px-4 text-center`,children:re.message}):re.kind===`empty`?(0,H.jsxs)(`div`,{className:`h-full flex flex-wrap items-center justify-center gap-6`,children:[(0,H.jsx)(_1,{result:u,refreshKey:P,onChanged:()=>F(e=>e+1)}),ue]}):re.kind===`scalar`?(0,H.jsx)(Vb,{result:u,label:`${u.parsed.agg}(${u.parsed.metric})`}):re.kind===`timeseries`?(0,H.jsx)(Jb,{result:u}):(0,H.jsx)(Yb,{result:u}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-3`,children:[(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Enter a WQL query or choose an example to explore your data.`}),ue]})})})}),i&&(0,H.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[!v&&!le&&ue,N&&m!==void 0&&(0,H.jsxs)(`button`,{type:`button`,"data-testid":`records-toggle`,"aria-expanded":te,onClick:()=>ne(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[te?(0,H.jsx)(un,{size:12}):(0,H.jsx)(Vn,{size:12}),`Records in this calculation`,(0,H.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 tabular-nums`,children:m.length})]})]}),I&&(0,H.jsx)(`div`,{className:`mt-3`,"data-testid":`pipeline-anatomy`,children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(R$,{parsed:L?u.parsed:E}),L&&(0,H.jsx)(z$,{result:u})]}):(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Submit a query to see its anatomy.`})}),te&&N&&m!==void 0&&(0,H.jsxs)(`div`,{className:`mt-3`,children:[(0,H.jsx)(`code`,{className:`block mb-3 rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground`,"data-testid":`records-wql`,children:N}),m.length===0?(0,H.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No records match this calculation.`}):(0,H.jsx)(C1,{entries:m,stickyOffset:k,idPrefix:`records-`})]}),u&&(0,H.jsx)(B$,{matched:u.matched,displayUnit:u.unit})]})})]}),(0,H.jsx)(j$,{open:b,onOpenChange:x,initialQuery:n,subsetQuery:M,rangeStart:Date.now()-o*7*y1,rangeEnd:Date.now(),preferredUnit:c})]})}function E1({className:e,...t}){return(0,H.jsx)(E,{"data-slot":`control`,...t,className:U(e,`group relative isolate inline-flex h-6 w-10 cursor-default rounded-full p-[3px] sm:h-5 sm:w-8`,`transition duration-0 ease-in-out data-changing:duration-200`,`forced-colors:outline forced-colors:bg-[Highlight] dark:forced-colors:bg-[Highlight]`,`bg-muted ring-1 ring-black/5 ring-inset dark:bg-white/5 dark:ring-white/15`,`data-checked:bg-primary data-checked:ring-primary/90`,`dark:data-checked:bg-primary dark:data-checked:ring-primary/90`,`focus:not-data-[focus]:outline-hidden data-[focus]:outline-2 data-[focus]:outline-offset-2 data-[focus]:outline-ring`,`data-[hover]:ring-black/15 dark:data-[hover]:ring-white/25 data-[hover]:data-checked:ring-primary/90 dark:data-[hover]:data-checked:ring-primary/90`,`data-[disabled]:bg-muted dark:data-[disabled]:bg-white/15 data-[disabled]:opacity-50 data-[disabled]:data-checked:bg-muted dark:data-[disabled]:data-checked:bg-white/15 data-[disabled]:data-checked:ring-black/5 dark:data-[disabled]:data-checked:ring-white/15`),children:(0,H.jsx)(`span`,{"aria-hidden":`true`,className:U(`pointer-events-none relative inline-block size-4.5 rounded-full sm:size-3.5`,`translate-x-0 transition duration-200 ease-in-out`,`border border-transparent`,`bg-background shadow-sm ring-1 ring-black/5 dark:ring-white/5`,`group-data-checked:bg-primary-foreground group-data-checked:shadow-sm group-data-checked:ring-primary/90`,`group-data-checked:translate-x-4 sm:group-data-checked:translate-x-3`,`group-data-checked:group-data-[disabled]:bg-background group-data-checked:group-data-[disabled]:shadow-sm group-data-checked:group-data-[disabled]:ring-black/5 dark:group-data-checked:group-data-[disabled]:ring-white/5`)})})}var D1=[{id:kA.route,label:`Journal`,profile:kA,shortcuts:!0},{id:jA.route,label:`Notes`,profile:jA,shortcuts:!0},{id:AA.route,label:`Notebooks`,profile:AA},{id:MA.route,label:`Efforts`,profile:MA,shortcuts:!0},{id:PA.route,label:`Sessions`,profile:PA,shortcuts:!0},{id:FA.route,label:`Playgrounds`,profile:FA,shortcuts:!0},{id:`/dashboards`,label:`Dashboards`,systemDefaultWql:`:dashboard{}`},{id:MM,label:`⌘/ Command Palette`}];function O1(e){return{defaultWql:e.defaultWql??``,customType:e.typeOptions!==void 0,typeOptions:e.typeOptions??[],customGroup:e.groupByOptions!==void 0,groupByOptions:e.groupByOptions??[]}}function k1(e){return{defaultWql:e.defaultWql.trim()||void 0,typeOptions:e.customType?e.typeOptions:void 0,groupByOptions:e.customGroup?e.groupByOptions:void 0}}var A1=Object.fromEntries([...mS,...pS].map(e=>[e.value,e.label])),j1=Object.fromEntries(FM.map(e=>[e.id,e.label]));function M1({values:e,choices:t,labels:n,onChange:r,testPrefix:i}){return(0,H.jsxs)(`div`,{className:`space-y-2`,children:[e.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map(t=>(0,H.jsxs)(`span`,{"data-testid":`${i}-chip-${t}`,className:`inline-flex items-center gap-1 rounded-full border border-border/70 bg-muted/40 px-2.5 py-1 text-xs font-medium`,children:[n[t]??t,(0,H.jsx)(`button`,{type:`button`,"aria-label":`Remove ${t}`,"data-testid":`${i}-remove-${t}`,onClick:()=>r(e.filter(e=>e!==t)),className:`text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(Te,{className:`size-3`})})]},t))}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.filter(t=>!e.includes(t.value)).map(t=>(0,H.jsxs)(`button`,{type:`button`,"aria-label":`Add ${t.value}`,"data-testid":`${i}-add-${t.value}`,onClick:()=>r([...e,t.value]),className:`rounded-full border border-dashed border-border/70 px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-foreground/40`,children:[`+ `,t.label]},t.value))})]})}function N1({surface:e}){let t=e.profile?.defaultWql??e.systemDefaultWql??`:note{source:journal,feeds} by {date}`,n=e.profile?.target,r=e.profile?.scopeOptions??[],[i,a]=(0,V.useState)(()=>O1(HM(e.id))),[o,s]=(0,V.useState)(()=>HM(e.id)),[c,l]=(0,V.useState)(null),u=(0,V.useMemo)(()=>{let e=i.defaultWql.trim();return e?_C(e).error??null:null},[i.defaultWql]),d=k1(i),f=JSON.stringify(d)!==JSON.stringify(o),p=Object.values(o).some(e=>e!==void 0),m=[...o.invalidTypeOptions??[],...o.invalidGroupByOptions??[]];return(0,H.jsxs)(`div`,{className:`space-y-4 rounded-lg border border-border/60 bg-card/40 p-4`,"data-testid":`query-defaults-card-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,H.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:e.label}),(0,H.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:e.id})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Landing default query`}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`System default: `,(0,H.jsx)(`span`,{className:`font-mono`,children:t})]}),(0,H.jsx)(`textarea`,{rows:2,value:i.defaultWql,onChange:e=>a({...i,defaultWql:e.target.value}),placeholder:t,"data-testid":`query-defaults-wql-${e.id}`,className:`w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs focus:outline-none focus:ring-1 focus:ring-primary/40`}),u?(0,H.jsxs)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-defaults-wql-error-${e.id}`,children:[`Couldn't parse — `,u]}):!i.defaultWql.trim()&&(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Empty — the system default is used.`})]}),m.length>0&&(0,H.jsxs)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-defaults-invalid-${e.id}`,children:[`Stored options no longer recognized: `,m.join(`, `),` — remove them; they are never turned into query clauses.`]}),e.profile&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Where-stored options`}),(0,H.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[`Custom`,(0,H.jsx)(E1,{checked:i.customType,onChange:e=>a({...i,customType:e}),"data-testid":`query-defaults-type-custom-${e.id}`})]})]}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`System: target `,n,`, scopes `,r.join(`, `)||`—`]}),i.customType&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(M1,{values:i.typeOptions,choices:n===`note`?mS:[],labels:A1,onChange:e=>a({...i,typeOptions:e}),testPrefix:`query-defaults-type-${e.id}`}),i.typeOptions.length===0&&(0,H.jsx)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-defaults-type-empty-${e.id}`,children:`No predefined options — the route nudges for a pick instead.`})]})]}),e.profile&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Arrange-cards-by options`}),(0,H.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[`Custom`,(0,H.jsx)(E1,{checked:i.customGroup,onChange:e=>a({...i,customGroup:e}),"data-testid":`query-defaults-group-custom-${e.id}`})]})]}),i.customGroup&&(0,H.jsx)(M1,{values:i.groupByOptions,choices:FM.map(e=>({value:e.id,label:e.label})),labels:j1,onChange:e=>a({...i,groupByOptions:e}),testPrefix:`query-defaults-group-${e.id}`})]}),e.shortcuts&&(0,H.jsx)(P1,{surface:e}),c&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-defaults-storage-error-${e.id}`,role:`alert`,children:c}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsx)(W,{size:`sm`,onClick:async()=>{if(!f)return;let t=i.defaultWql.trim();if(!(t&&_C(t).error)){if(!await UM(e.id,d)){l(`Save failed — storage is unavailable; the previous default still stands.`);return}l(null),s(HM(e.id))}},disabled:!f||!!u,"data-testid":`query-defaults-save-${e.id}`,children:`Save`}),p&&(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:async()=>{if(!await WM(e.id)){l(`Reset failed — storage is unavailable; the stored override still stands.`);return}l(null),s({}),a(O1({}))},"data-testid":`query-defaults-reset-${e.id}`,children:[(0,H.jsx)(Dn,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Reset to system default`})]})]})]})}function P1({surface:e}){let t=EM(e.id),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(null),o=async n=>{a(null),await bM(e.id,t.filter(e=>e.id!==n.id))||a(`Delete failed — storage is unavailable. Nothing was lost; the link remains.`)};return(0,H.jsxs)(`div`,{className:`space-y-2`,"data-testid":`query-defaults-shortcuts-${e.id}`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Saved shortcuts (navigation links)`}),(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>r({editing:null}),"data-testid":`query-defaults-shortcut-new-${e.id}`,children:[(0,H.jsx)(Kt,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`New shortcut`})]})]}),t.map(t=>{let n=uM[t.icon],i=t.to?`Opens ${t.to}`:t.wql||`Landing (no query)`;return(0,H.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border/50 px-2 py-1.5`,"data-testid":`query-defaults-shortcut-${e.id}:${t.id}`,children:[(0,H.jsx)(n,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`min-w-0 max-w-40 truncate text-xs font-medium`,children:t.label}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[10px] text-muted-foreground`,children:i}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Edit ${t.label}`,"data-testid":`query-defaults-shortcut-edit-${e.id}:${t.id}`,onClick:()=>r({editing:t}),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,children:(0,H.jsx)(ut,{className:`size-3`})}),!t.to&&t.id!==`all`&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete ${t.label}`,"data-testid":`query-defaults-shortcut-delete-${e.id}:${t.id}`,onClick:()=>o(t),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-destructive`,children:(0,H.jsx)(j,{className:`size-3`})})]},t.id)}),i&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`query-defaults-shortcut-error-${e.id}`,children:i}),n&&(0,H.jsx)(jM,{open:!0,onOpenChange:e=>{e||r(null)},route:e.id,editing:n.editing})]})}function F1(){return(0,H.jsxs)(`section`,{"data-testid":`query-defaults-section`,className:`space-y-6`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground`,children:`Query Defaults`}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Override the landing query and the Where-stored / arrangement options per surface. An empty query uses the system default; an emptied options list nudges you to pick instead of presetting one. Option lists are favorites — they reorder choices, they don't change what queries mean. Stored`,` `,UD?`on the server.`:`in this browser only.`]})]}),D1.map(e=>(0,H.jsx)(N1,{surface:e},e.id))]})}var I1=2.20462,L1=2.54,R1=`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`;function z1(e){if(!e)return;let t=new Date(e);if(Number.isNaN(t.getTime()))return;let n=new Date,r=n.getFullYear()-t.getFullYear(),i=n.getMonth()-t.getMonth();return(i<0||i===0&&n.getDate()<t.getDate())&&r--,r}function B1(e){let t=(e??``).trim().split(/\s+/).filter(Boolean);return t.length===0?`?`:t.slice(0,2).map(e=>e[0].toUpperCase()).join(``)}function V1({unit:e,other:t,onSwitch:n}){return(0,H.jsx)(`div`,{className:`flex rounded-md border border-input overflow-hidden shrink-0`,role:`group`,children:[e,t].map((e,t)=>(0,H.jsx)(`button`,{type:`button`,"aria-pressed":t===0,onClick:t===1?n:void 0,className:U(`px-2.5 h-9 text-xs font-medium transition-colors`,t===0?`bg-primary/10 text-primary`:`bg-background text-muted-foreground hover:bg-muted`),children:e},e))})}function H1(){let[e,t]=(0,V.useState)(null),[n,r]=(0,V.useState)({displayName:``,birthDate:``,weight:``,height:``}),i=(0,V.useRef)(null);(0,V.useEffect)(()=>{let e=!0;return vD.current().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,V.useEffect)(()=>{e&&r({displayName:e.displayName?.trim()||`Anonymous`,birthDate:e.birthDate??``,weight:e.weight==null?``:String(e.weight),height:e.height==null?``:String(e.height)})},[e?.id]);let a=(0,V.useCallback)(async e=>{try{t(await vD.update(e))}catch(e){console.error(e)}},[]),o=(0,V.useCallback)(async e=>{if(e)try{await a({picture:await tb(e)})}catch(e){console.error(e)}},[a]);if(!e)return(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,"data-testid":`profile-loading`,children:`Loading profile…`});let s=z1(e.birthDate),c=e.weightUnit??`kg`,l=e.heightUnit??`cm`;return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(f,{className:`size-4 text-primary`}),`Profile Picture`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Click the picture to choose an image — it is center-cropped and stored locally.`})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i.current?.click(),"aria-label":`Change profile picture`,"data-testid":`profile-avatar`,className:`relative group size-20 rounded-full overflow-hidden border border-border bg-muted shrink-0 cursor-pointer`,children:[e.picture?(0,H.jsx)(`img`,{src:e.picture,alt:``,className:`size-full object-cover`}):(0,H.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center text-lg font-semibold text-muted-foreground`,children:B1(e.displayName)}),(0,H.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/45 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity`,children:(0,H.jsx)(mn,{className:`size-5 text-white`})})]}),(0,H.jsx)(`input`,{ref:i,type:`file`,accept:`image/*`,className:`hidden`,"aria-hidden":`true`,tabIndex:-1,onChange:e=>{o(e.target.files?.[0]),e.target.value=``}})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Details`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Used by journal analytics (age from birth date, metric conversions). Changes are saved immediately.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-display-name`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Name`}),(0,H.jsx)(`input`,{id:`profile-display-name`,"data-testid":`profile-display-name`,className:R1,placeholder:`Anonymous`,value:n.displayName,onChange:e=>{r(t=>({...t,displayName:e.target.value})),a({displayName:e.target.value})}})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`label`,{htmlFor:`profile-birth-date`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:[`Birth Date`,s===void 0?``:` · Age ${s}`]}),(0,H.jsx)(`input`,{id:`profile-birth-date`,"data-testid":`profile-birth-date`,type:`date`,className:R1,value:n.birthDate,onChange:e=>{r(t=>({...t,birthDate:e.target.value})),a({birthDate:e.target.value||void 0})}})]}),(0,H.jsx)(`div`,{})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-weight`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Weight`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{id:`profile-weight`,"data-testid":`profile-weight`,type:`number`,inputMode:`decimal`,min:`0`,className:R1,placeholder:c===`kg`?`e.g. 75`:`e.g. 165`,value:n.weight,onChange:e=>{let t=e.target.value;r(e=>({...e,weight:t})),t===``?a({weight:void 0}):Number.isFinite(Number(t))&&a({weight:Number(t)})}}),(0,H.jsx)(V1,{unit:c,other:c===`kg`?`lb`:`kg`,onSwitch:()=>void a({weightUnit:c===`kg`?`lb`:`kg`,weight:e.weight==null?void 0:c===`kg`?e.weight*I1:e.weight/I1})})]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`label`,{htmlFor:`profile-height`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Height`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{id:`profile-height`,"data-testid":`profile-height`,type:`number`,inputMode:`decimal`,min:`0`,className:R1,placeholder:l===`cm`?`e.g. 180`:`e.g. 71`,value:n.height,onChange:e=>{let t=e.target.value;r(e=>({...e,height:t})),t===``?a({height:void 0}):Number.isFinite(Number(t))&&a({height:Number(t)})}}),(0,H.jsx)(V1,{unit:l,other:l===`cm`?`in`:`cm`,onSwitch:()=>void a({heightUnit:l===`cm`?`in`:`cm`,height:e.height==null?void 0:l===`cm`?e.height/L1:e.height*L1})})]})]})]})]})]})]})}function U1(){let[e]=(0,V.useState)(hD);return e?.state,(0,H.jsx)(`div`,{className:`space-y-8`,children:(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Storage`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This deployment uses its API server for storage and queries.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,"data-testid":`storage-option-api`,children:`This deployment stores data on its server; storage is managed by the deployment.`})]})})}var W1=[{id:`appearance`,content:(0,H.jsx)(q1,{})},{id:`profile`,content:(0,H.jsx)(H1,{})},{id:`storage`,content:(0,H.jsx)(U1,{})},{id:`sync`,content:(0,H.jsx)(BZ,{})},{id:`queries`,content:(0,H.jsx)(F1,{})},{id:`tags`,content:(0,H.jsx)(Y1,{})},{id:`routes`,content:(0,H.jsx)(K1,{})},{id:`system`,content:(0,H.jsx)(J1,{})}];function G1(){let e=mt(),t=e.pathname.endsWith(`/system`)?`system`:e.pathname.endsWith(`/profile`)?`profile`:e.pathname.endsWith(`/storage`)?`storage`:e.pathname.endsWith(`/sync`)?`sync`:e.pathname.endsWith(`/queries`)?`queries`:e.pathname.endsWith(`/tags`)?`tags`:e.pathname.endsWith(`/routes`)?`routes`:`appearance`;return(0,H.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 bg-background`,children:[(0,H.jsx)($I,{title:`Settings`,subtitle:`Manage profile, appearance, audio, and system preferences`}),(0,H.jsx)(`main`,{className:`flex-1 overflow-y-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8`,children:(0,H.jsx)(`div`,{className:`max-w-4xl mx-auto space-y-8`,children:W1.find(e=>e.id===t)?.content})})]})}function K1(){let[e,t]=(0,V.useState)([]);return(0,V.useEffect)(()=>{let e=!0;return xD.readonly(`page`).getAll().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,H.jsxs)(`section`,{className:`space-y-6`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{className:`text-lg font-medium`,children:`Route Review`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:"All page routes (`/p/:slug`, `/c/:slug`, `/journal/:date`) currently registered in storage."})]}),(0,H.jsx)(`div`,{className:`border rounded-md`,children:(0,H.jsxs)(`table`,{className:`w-full text-sm text-left`,children:[(0,H.jsx)(`thead`,{className:`bg-muted/50 border-b`,children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Route`}),(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Title`}),(0,H.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`ID`})]})}),(0,H.jsx)(`tbody`,{className:`divide-y`,children:e.length===0?(0,H.jsx)(`tr`,{children:(0,H.jsx)(`td`,{colSpan:3,className:`px-4 py-4 text-center text-muted-foreground`,children:`No pages found.`})}):e.map(e=>(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs`,children:e.slug?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-primary/10 text-primary`,children:`SLUG`}),e.slug]}):e.date?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-secondary/10 text-secondary`,children:`DATE`}),e.date]}):`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2`,children:e.title??`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono text-[10px] text-muted-foreground`,children:e.id})]},e.id))})]})})]})}function q1(){let{theme:e,setTheme:t}=ji(),[n,r]=XL(),i={right:cr,left:Fe};return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Interface Theme`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select your preferred color theme. Changes are saved and applied immediately.`})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4`,children:[{id:`system`,label:`System`,description:`Follows your operating system color scheme preferences`,icon:_e,isDefault:!0},{id:`light`,label:`Light`,description:`Crisp light background with dark text for high daytime readability`,icon:et},{id:`dark`,label:`Dark`,description:`Relaxed dark background for lower eye strain in low-light settings`,icon:ir}].map(n=>{let r=e===n.id,i=n.icon;return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`theme-option-${n.id}`,onClick:()=>t(n.id),className:U(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,r?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,H.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,H.jsx)(`div`,{className:U(`p-2 rounded-lg`,r?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,H.jsx)(i,{className:`size-5`})}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[n.isDefault&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,H.jsx)(`div`,{className:U(`size-4 rounded-full border flex items-center justify-center transition-colors`,r?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:r&&(0,H.jsx)(Zn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,H.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:n.label}),(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:n.description})]},n.id)})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(Xn,{className:`size-4 text-primary`}),`Actions Button Position`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`On phones, search and page actions float as a button cluster at the bottom of the screen. Place the cluster near your dominant thumb.`})]}),(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4`,children:GL.map(e=>{let t=n===e.id,a=i[e.id];return(0,H.jsxs)(`button`,{type:`button`,"data-testid":`fab-alignment-${e.id}`,onClick:()=>r(e.id),className:U(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,t?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,H.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,H.jsx)(`div`,{className:U(`p-2 rounded-lg`,t?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,H.jsx)(a,{className:`size-5`})}),(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[e.id===`right`&&(0,H.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,H.jsx)(`div`,{className:U(`size-4 rounded-full border flex items-center justify-center transition-colors`,t?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:t&&(0,H.jsx)(Zn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,H.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:e.label}),(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:e.description})]},e.id)})})]})]})}function J1(){let{isEnabled:e,toggleAudio:t,playTestSound:n}=tk(),{isDebugMode:r,toggleDebugMode:i}=ty(),{consent:a,setConsent:o}=cH(),[s,c]=(0,V.useState)(!1),[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(null);hD();let p=`your Wod Wiki server`;return(0,V.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),c(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,"data-testid":`settings-about`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(Ce,{className:`size-4 text-primary`}),`About`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Build version and release information for this playground.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsxs)(`p`,{className:`text-sm font-medium text-foreground font-mono`,children:[`v`,VI]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Wod Wiki playground build`})]}),(0,H.jsx)(W,{asChild:!0,variant:`outline`,size:`sm`,className:`gap-2`,children:(0,H.jsxs)(`a`,{href:UI(VI),target:`_blank`,rel:`noopener noreferrer`,"data-testid":`settings-release-link`,children:[(0,H.jsx)(k,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Release notes`})]})})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[e?(0,H.jsx)(fe,{className:`size-4 text-primary`}):(0,H.jsx)(ne,{className:`size-4 text-muted-foreground`}),`Audio Feedback`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Configure sound effects for workout timers, interval countdowns, and completion cues.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`sound-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Workout Sound Effects`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Play countdown beeps, interval alerts, and workout finish chimes`})]}),(0,H.jsx)(E1,{id:`sound-switch`,"data-testid":`sound-toggle`,checked:e,onChange:t})]}),(0,H.jsxs)(`div`,{className:`pt-3 border-t border-border/50 flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Test audio output device`}),(0,H.jsxs)(W,{variant:`outline`,size:`sm`,onClick:n,disabled:!e,"data-testid":`play-test-sound-btn`,className:`gap-2`,children:[(0,H.jsx)(fe,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Play Test Chime`})]})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(tr,{className:`size-4 text-primary`}),`Developer Diagnostics`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Logging and runtime inspection tools for Whiteboard scripts and execution trees.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`debug-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Debug Mode`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Output verbose AST compilation and runtime execution traces to browser console`})]}),(0,H.jsx)(E1,{id:`debug-switch`,"data-testid":`debug-mode-toggle`,checked:r,onChange:i})]})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,"data-testid":`settings-telemetry`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,H.jsx)(S,{className:`size-4 text-primary`}),`Anonymous Telemetry`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Anonymous usage telemetry is internal to Wod Wiki only. It helps us improve timer accuracy, workout execution, and query reliability. Your data will never be sold or shared with third parties.`})]}),(0,H.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,H.jsx)(`label`,{htmlFor:`telemetry-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Share Anonymous Usage Statistics`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends anonymous feature usage events. Turn off to opt out at any time.`})]}),(0,H.jsx)(E1,{id:`telemetry-switch`,"data-testid":`telemetry-toggle`,checked:a,onChange:o})]})})]}),(0,H.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`h2`,{className:`text-base font-semibold text-destructive flex items-center gap-2`,children:[(0,H.jsx)(Ze,{className:`size-4 text-destructive`}),`Data & Cache (Danger Zone)`]}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Manage your local database storage and reset client state.`})]}),(0,H.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 p-4 sm:p-5 space-y-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`div`,{className:`font-semibold text-sm text-foreground`,children:`Reset & Clear Cache`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:(0,H.jsxs)(H.Fragment,{children:[`Wipes ALL data stored in `,p,`: notes, workouts, custom efforts, recorded results, and attachments, plus this browser's localStorage preferences. Your separate IndexedDB copy is kept. Bundled core content re-imports automatically on the next launch; community and custom libraries must be re-synced from Settings > Sync. Your connection settings are preserved.`]})})]}),(0,H.jsx)(`div`,{children:(0,H.jsxs)(W,{variant:`destructive`,size:`sm`,onClick:()=>c(!0),"data-testid":`reset-cache-button`,className:`gap-2`,children:[(0,H.jsx)(Dn,{className:`size-4`}),(0,H.jsx)(`span`,{children:`Reset & Clear Cache`})]})})]})]}),s&&(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-150`,onClick:e=>{e.target===e.currentTarget&&!l&&c(!1)},"data-testid":`reset-confirmation-modal`,children:(0,H.jsxs)(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl flex flex-col gap-4`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`reset-modal-title`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 text-destructive font-semibold text-base`,id:`reset-modal-title`,children:[(0,H.jsx)(Ze,{className:`size-5`}),`Reset All Application Data?`]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:(0,H.jsxs)(H.Fragment,{children:[`This permanently deletes every note, result, cached effort, and local setting stored in `,p,`. It cannot be undone.`]})}),d&&(0,H.jsxs)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`reset-error`,children:[`Reset failed: `,d,` — your data and connection were left untouched; try again.`]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-2`,children:[(0,H.jsx)(W,{variant:`outline`,onClick:()=>c(!1),disabled:l,children:`Cancel`}),(0,H.jsx)(W,{variant:`destructive`,onClick:async()=>{u(!0),f(null);try{await $Y(),window.location.reload()}catch(e){f(e instanceof Error?e.message:String(e)),u(!1)}},disabled:l,"data-testid":`confirm-reset-button`,className:`gap-2`,children:l?(0,H.jsx)(`span`,{children:`Resetting…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Dn,{className:`size-4`}),(0,H.jsx)(`span`,{children:`Yes, Reset Everything`})]})})]})]})})]})}function Y1(){let[e,t]=(0,V.useState)([]),[n,r]=(0,V.useState)([]),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(``),[c,l]=(0,V.useState)(`#3b82f6`),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),[m,h]=(0,V.useState)(``),[g,_]=(0,V.useState)(``),[v,y]=(0,V.useState)(null),[b,x]=(0,V.useState)(``),[S,C]=(0,V.useState)(null),w=(0,V.useCallback)(async()=>{try{let[e,n]=await Promise.all([X.getAllTagTypes(),X.getAllTags()]);t(e),r(n)}catch{}},[]);(0,V.useEffect)(()=>{w()},[w]);let T=async t=>{t.preventDefault();let n=i.trim().toLowerCase().replace(/[^a-z0-9_-]/g,`-`),r=o.trim();if(!n||!r){C(`Both type name and display label are required`);return}if(e.some(e=>e.name.toLowerCase()===n)){C(`Tag type "${n}" already exists`);return}C(null);let l={id:typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,name:n,label:r,color:c,createdAt:Date.now()};await X.putTagType(l),a(``),s(``),await w()},E=async e=>{if(n.some(t=>t.type?.toLowerCase()===e.name.toLowerCase())){C(`Cannot delete tag type "${e.label}" while tags are assigned to it`);return}C(null),await X.deleteTagType(e.id),await w()},D=async e=>{e.preventDefault();let t=u.trim();if(!t)return;let r=n.find(e=>e.label.toLowerCase()===t.toLowerCase());if(r)f&&r.type!==f&&await X.updateTagType(r.id,f);else{let e={id:typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,label:t,type:f||void 0,createdAt:Date.now()};await X.putTag(e)}d(``),await w()},O=async(e,t)=>{await X.updateTagType(e,t===``?void 0:t),await w()},k=async e=>{await X.deleteTag(e),await w()},A=async e=>{let t=b.trim();if(y(null),!t)return;let r=n.find(t=>t.id===e);!r||r.label===t||(await X.putTag({...r,label:t}),await w())},M=n.filter(t=>!t.type||!e.some(e=>e.name.toLowerCase()===t.type?.toLowerCase()));return(0,H.jsxs)(`div`,{className:`space-y-8`,children:[(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tag Types`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Define classification dimensions for tags. Note frontmatter properties matching a type name will automatically provide typeahead suggestions.`})]}),(0,H.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,H.jsxs)(`form`,{onSubmit:T,className:`flex flex-wrap items-end gap-3`,children:[(0,H.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Type Name`}),(0,H.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,placeholder:`Type name (e.g. discipline)`,value:i,onChange:e=>a(e.target.value)})]}),(0,H.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Label`}),(0,H.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`,placeholder:`Display label (e.g. Discipline)`,value:o,onChange:e=>s(e.target.value)})]}),(0,H.jsxs)(`div`,{className:`w-24`,children:[(0,H.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Color`}),(0,H.jsx)(`input`,{type:`color`,className:`w-full h-9 p-1 rounded-md border border-input bg-background cursor-pointer`,value:c,onChange:e=>l(e.target.value)})]}),(0,H.jsxs)(W,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,H.jsx)(Kt,{className:`size-3.5 mr-1`}),` Add Type`]})]}),S&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,children:S}),(0,H.jsxs)(`div`,{className:`border-t border-border pt-3`,children:[(0,H.jsx)(`h3`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2`,children:`Registered Types`}),e.length===0?(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No custom tag types created yet.`}):(0,H.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2`,children:e.map(e=>{let t=n.filter(t=>t.type?.toLowerCase()===e.name.toLowerCase()).length;return(0,H.jsxs)(`div`,{className:`flex items-center justify-between p-2.5 rounded-lg border border-border/70 bg-background/50 text-xs`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,H.jsx)(`span`,{className:`size-2.5 rounded-full shrink-0`,style:{backgroundColor:e.color||`#3b82f6`}}),(0,H.jsx)(`span`,{className:`font-semibold truncate`,children:e.label}),(0,H.jsxs)(`span`,{className:`text-muted-foreground font-mono text-[11px] truncate`,children:[`(`,e.name,`)`]}),(0,H.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.2 text-[10px] text-muted-foreground`,children:t})]}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete tag type ${e.label}`,disabled:t>0,title:t>0?`Cannot delete type while ${t} tag(s) are assigned`:`Delete unused tag type`,className:U(`p-1 rounded transition`,t>0?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground hover:text-destructive cursor-pointer`),onClick:()=>E(e),children:(0,H.jsx)(j,{className:`size-3.5`})})]},e.id)})})]})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsx)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3`,children:(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tags Table`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Filter, search, edit, reassign, or delete stored tags.`})]})}),(0,H.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsxs)(`div`,{className:`relative flex-1 min-w-[200px]`,children:[(0,H.jsx)(Xn,{className:`absolute left-2.5 top-2.5 size-3.5 text-muted-foreground`}),(0,H.jsx)(`input`,{"aria-label":`Filter tags`,className:`w-full h-9 rounded-md border border-input bg-background pl-8 pr-3 text-xs outline-none focus:border-primary`,placeholder:`Filter tags by label…`,value:m,onChange:e=>h(e.target.value)})]}),(0,H.jsx)(`div`,{className:`w-48`,children:(0,H.jsxs)(`select`,{"aria-label":`Filter by type`,className:`w-full h-9 rounded-md border border-input bg-background px-2.5 text-xs outline-none focus:border-primary`,value:g,onChange:e=>_(e.target.value),children:[(0,H.jsxs)(`option`,{value:``,children:[`All Types (`,n.length,`)`]}),(0,H.jsxs)(`option`,{value:`__untyped__`,children:[`Untyped / General (`,M.length,`)`]}),e.map(e=>{let t=n.filter(t=>t.type?.toLowerCase()===e.name.toLowerCase()).length;return(0,H.jsxs)(`option`,{value:e.name,children:[e.label,` (`,t,`)`]},e.id)})]})}),(0,H.jsxs)(`form`,{onSubmit:D,className:`flex items-center gap-2`,children:[(0,H.jsx)(`input`,{className:`h-9 w-36 sm:w-44 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,placeholder:`New tag…`,value:u,onChange:e=>d(e.target.value)}),(0,H.jsxs)(`select`,{className:`h-9 w-28 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,value:f,onChange:e=>p(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`Untyped`}),e.map(e=>(0,H.jsx)(`option`,{value:e.name,children:e.label},e.id))]}),(0,H.jsxs)(W,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,H.jsx)(Kt,{className:`size-3.5 mr-1`}),` Add`]})]})]}),(0,H.jsx)(`div`,{className:`border border-border rounded-lg overflow-hidden`,children:(0,H.jsx)(`div`,{className:`overflow-x-auto`,children:(0,H.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,H.jsx)(`thead`,{className:`bg-muted/50 border-b border-border`,children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Tag Label`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Type`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium`,children:`Created`}),(0,H.jsx)(`th`,{className:`px-4 py-2.5 font-medium text-right`,children:`Actions`})]})}),(0,H.jsx)(`tbody`,{className:`divide-y divide-border`,children:n.filter(t=>m&&!t.label.toLowerCase().includes(m.toLowerCase().trim())?!1:g===`__untyped__`?!t.type||!e.some(e=>e.name.toLowerCase()===t.type?.toLowerCase()):!g||t.type?.toLowerCase()===g.toLowerCase()).map(t=>{let n=e.find(e=>e.name.toLowerCase()===t.type?.toLowerCase()),r=v===t.id;return(0,H.jsxs)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:[(0,H.jsx)(`td`,{className:`px-4 py-2 font-mono`,children:r?(0,H.jsx)(`input`,{autoFocus:!0,className:`h-7 w-full max-w-[200px] rounded border border-primary bg-background px-2 font-mono text-xs outline-none`,value:b,onChange:e=>x(e.target.value),onKeyDown:async e=>{e.key===`Enter`?await A(t.id):e.key===`Escape`&&y(null)},onBlur:()=>A(t.id)}):(0,H.jsx)(`button`,{type:`button`,className:`font-mono text-foreground hover:underline text-left`,title:`Click to rename`,onClick:()=>{y(t.id),x(t.label)},children:t.label})}),(0,H.jsx)(`td`,{className:`px-4 py-2`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[n&&(0,H.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:n.color||`#3b82f6`}}),(0,H.jsxs)(`select`,{"aria-label":`Type for ${t.label}`,className:`h-7 rounded border border-input bg-background px-2 text-xs outline-none cursor-pointer focus:border-primary`,value:t.type??``,onChange:e=>O(t.id,e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`Untyped`}),e.map(e=>(0,H.jsx)(`option`,{value:e.name,children:e.label},e.id))]})]})}),(0,H.jsx)(`td`,{className:`px-4 py-2 text-muted-foreground text-[11px]`,children:t.createdAt?new Date(t.createdAt).toLocaleDateString():`—`}),(0,H.jsx)(`td`,{className:`px-4 py-2 text-right`,children:(0,H.jsx)(`button`,{type:`button`,"aria-label":`Delete tag ${t.label}`,className:`text-muted-foreground hover:text-destructive p-1 rounded transition`,onClick:()=>k(t.id),children:(0,H.jsx)(j,{className:`size-3.5`})})})]},t.id)})})]})})})]})]})]})}var X1=`dashboard-title`;function Z1(){let{slug:e}=zn(),t=Sn(),[n]=jX(),{unit:r}=jx(),i=Date.now()-n*7*864e5,a=Date.now(),[o,s]=(0,V.useState)(0),[c,l]=(0,V.useState)(null);(0,V.useEffect)(()=>{let e=!1;return X.countEvents().then(t=>{e||l(t>0)}),()=>{e=!0}},[o]);let{source:u,loading:d}=Ij(e,o),f=(0,V.useMemo)(()=>{if(!u?.rawContent)return null;let{meta:e,sections:t}=u_(u.rawContent);return{doc:i_(t,e),sections:t}},[u]),p=f?.doc??null,{setL3Items:m,registerScrollFn:h}=hA(),g=(0,V.useMemo)(()=>{if(!f)return{headings:[],items:[]};let{doc:e,sections:t}=f,n=new Set;t.forEach((e,r)=>{if(e.type!==`query`)return;let i=t[r-1];if(i?.type===`markdown`&&i.subtype===`paragraph`){let e=t[r-2];e?.type===`markdown`&&e.subtype===`heading`&&n.add(r-2)}else i?.type===`markdown`&&i.subtype===`heading`&&n.add(r-1)});let r=[],i=[];e.title&&i.push({id:X1,label:e.title,level:3,action:{type:`scroll`,sectionId:X1}});let a=0;return t.forEach((t,o)=>{if(t.type===`markdown`&&t.subtype===`heading`){if(n.has(o)||/^#\s/.test(t.content))return;let e=`note-h${o}`,s=t.content.replace(/^#+\s*/,``);r.push({id:e,level:/^#+/.exec(t.content)?.[0].length??2,text:s,beforeWidget:a}),i.push({id:e,label:s,level:3,action:{type:`scroll`,sectionId:e}});return}if(t.type!==`query`)return;let s=e.widgets[a];if(!s)return;a++;let c=`widget-${s.key}`;i.push({id:c,label:s.title||s.body,level:3,action:{type:`scroll`,sectionId:c}})}),{headings:r,items:i}},[f]),_=g.items;(0,V.useEffect)(()=>(m(_),()=>m([])),[_,m]),(0,V.useEffect)(()=>(h(e=>{let t=globalThis.document.getElementById(e);t&&(window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`}),typeof t.animate==`function`&&t.animate([{boxShadow:`0 0 0 3px hsl(var(--primary))`},{boxShadow:`0 0 0 3px transparent`}],{duration:1500,easing:`ease-out`}))}),()=>h(e=>{let t=globalThis.document.getElementById(e);t&&window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`})})),[h]);let[v,y]=(0,V.useState)(!1),[b,x]=(0,V.useState)(null),[S,C]=(0,V.useState)(null),w=(0,V.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await Kj.getById(u.noteId);if(n.rawContent!==e)throw s(e=>e+1),Error(`The dashboard changed elsewhere — this edit was not saved.`);let r=t(n.rawContent);if(r==null)throw s(e=>e+1),Error(`The widget changed on disk — this edit was not saved.`);await Kj.update(n,typeof r==`string`?r:r.note,typeof r==`string`?void 0:r),s(e=>e+1)},[u]),T=(0,V.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await Kj.getById(u.noteId),{meta:r,body:i}=Sb(n.rawContent),a=`---\n${Eb($g(r,e,t))}\n---\n${i}`;await Kj.update(n,a),s(e=>e+1)},[u]),E=(0,V.useCallback)((e,t)=>{C(null),w(e,e=>{let n=t(e);if(!n.ok){let e=n.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return n}).catch(e=>{C(e instanceof Error?e.message:String(e))})},[w]),D=(0,V.useCallback)(async e=>{if(!(!b||b.mode===`inspect`)){if(b.mode===`add`)await w(b.expectedRaw,t=>b_(t,e));else{let t=b.widget;await w(b.expectedRaw,n=>{let r=C_(n,t.key,t.body,e);if(!r.ok){let e=r.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return r})}}},[b,w]),O=(0,V.useCallback)(async()=>{!u||u.editable||(await Jj.cloneDashboard(u.slug,u.rawContent,u.title),s(e=>e+1))},[u]),k=u!=null&&u.slug===e;if(d&&!k)return(0,H.jsx)(`div`,{className:`p-8 text-sm text-muted-foreground`,children:`Loading dashboard…`});if(!k||!u)return(0,H.jsxs)(`div`,{className:`p-8`,"data-testid":`dashboard-not-found`,children:[(0,H.jsx)(`h1`,{className:`text-lg font-bold text-foreground mb-2`,children:`Dashboard not found`}),(0,H.jsxs)(`p`,{className:`text-sm text-muted-foreground mb-4`,children:[`No dashboard named `,(0,H.jsx)(`code`,{children:e}),`. It may have been removed.`]}),(0,H.jsx)(`button`,{onClick:()=>t(`/dashboard`),className:`px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90`,children:`Back to explorer`})]});let A=u.editable;return(0,H.jsxs)(`div`,{className:`min-h-screen bg-background flex flex-col`,children:[(0,H.jsx)($I,{id:X1,title:p?.title||u.title,subtitle:A?`Editable dashboard note.`:`Prebuilt — read-only until cloned to your vault.`,actions:(0,H.jsxs)(nR,{label:`Dashboard actions`,primary:A?(0,H.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-edit-toggle`,"aria-pressed":v,onClick:()=>y(e=>!e),className:`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors ${v?`bg-primary text-primary-foreground`:`border border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,H.jsx)(ut,{size:12}),` `,v?`Done`:`Edit`]}):void 0,children:[(0,H.jsx)(Sx,{}),(0,H.jsx)(Nx,{})]})}),(0,H.jsxs)(`div`,{className:`max-w-[1500px] w-full mx-auto p-4 md:p-6 lg:p-8 flex-1`,children:[S&&(0,H.jsxs)(`div`,{role:`alert`,"data-testid":`dashboard-action-error`,className:`mb-4 flex items-center justify-between rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2 text-xs text-destructive`,children:[(0,H.jsx)(`span`,{children:S}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:()=>C(null),className:`font-medium hover:opacity-70 transition-opacity`,children:`×`})]}),!A&&(0,H.jsxs)(`div`,{className:`mb-4 flex items-center justify-between rounded-lg border border-primary/30 bg-primary/5 px-4 py-2 text-xs`,children:[(0,H.jsx)(`span`,{className:`text-foreground`,children:`This is a read-only prebuilt. Clone it to edit widgets and tokens.`}),(0,H.jsx)(`button`,{type:`button`,"data-testid":`clone-dashboard`,onClick:O,className:`font-medium text-primary hover:text-primary/80 transition-colors`,children:`Clone to vault`})]}),A&&v&&(0,H.jsxs)(`button`,{type:`button`,"data-testid":`add-widget`,onClick:()=>x({mode:`add`,expectedRaw:u.rawContent}),className:`mb-4 flex items-center gap-1.5 rounded-lg border border-dashed border-primary/50 px-4 py-2 text-xs font-semibold text-primary hover:bg-primary/5 transition-colors`,children:[(0,H.jsx)(Kt,{size:13}),` Add widget`]}),c===!1?(0,H.jsx)(_1,{layout:`card`,refreshKey:o,onChanged:()=>s(e=>e+1)}):(0,H.jsx)(`div`,{className:`mb-4`,children:(0,H.jsx)(_1,{layout:`banner`,refreshKey:o,onChanged:()=>s(e=>e+1)})}),p&&(0,H.jsx)(xx,{document:p,headings:g.headings,executor:XF,onTokenChange:A?T:void 0,editMode:A&&v,onEditWidget:A?e=>x({mode:`edit`,widget:e,expectedRaw:u.rawContent}):void 0,onDuplicateWidget:A?e=>E(u.rawContent,t=>w_(t,e.key,e.body)):void 0,onRemoveWidget:A?e=>E(u.rawContent,t=>T_(t,e.key,e.body)):void 0,onMoveWidget:A?(e,t)=>E(u.rawContent,n=>E_(n,e.key,e.body,t)):void 0,onResizeWidget:A?(e,t)=>E(u.rawContent,n=>D_(n,e.key,e.body,t)):void 0,onInspectWidget:A?void 0:e=>x({mode:`inspect`,widget:e,expectedRaw:u.rawContent}),onOpenInExplorer:(e,n)=>t(aj({q:n})),rangeStart:i,rangeEnd:a,preferredUnit:r})]}),(0,H.jsx)(FX,{open:b!==null,onClose:()=>x(null),mode:b?.mode??`add`,initialWql:b&&b.mode!==`add`?b.widget.body:`sum:totalVolume{}`,initial:b&&b.mode!==`add`?{title:b.widget.title,question:b.widget.question,type:b.widget.type,spanCols:b.widget.spanCols,spanFull:b.widget.spanFull,attributes:b.widget.attributes}:void 0,executor:XF,rangeStart:i,rangeEnd:a,preferredUnit:r,tokenValues:p?Qg(p.tokens):void 0,onApply:b?.mode===`inspect`?void 0:D,footerExtra:b?.mode===`inspect`?(0,H.jsx)(`button`,{type:`button`,"data-testid":`inspect-clone`,onClick:()=>{O().then(()=>{x(null),y(!0)})},className:`px-3 py-1.5 text-xs font-medium text-primary hover:text-primary/80 rounded-lg border border-primary/40 hover:bg-primary/10 transition-colors`,children:`Clone to vault to edit`}):void 0})]})}function Q1({sessionId:e}){let[t,n]=(0,V.useState)(null),[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(``);return(0,V.useEffect)(()=>{let t=!1;return n(null),i(null),(async()=>{let r=await Nj.getSessionById?.(e);if(!r)throw Error(`Session not found.`);let i=await Nj.getBlockRevision(r.noteId,r.blockId,r.blockVersion);if(!i)throw Error(`The pinned saved workout is unavailable.`);t||n({session:r,revision:i})})().catch(e=>{t||i(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]),(0,H.jsxs)(`section`,{"aria-label":`Pinned workout source`,className:`space-y-3 border-b p-4`,children:[(0,H.jsx)(`h2`,{className:`font-semibold`,children:`Saved workout used by this session`}),r&&(0,H.jsx)(`p`,{role:`alert`,children:r}),t?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`p`,{className:`break-all text-sm`,children:[`Block `,t.session.blockId,` · v`,t.revision.version,` · `,t.revision.dialect,t.revision.sport?` · ${t.revision.sport}`:``]}),(0,H.jsx)(`pre`,{className:`max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-3 text-xs`,children:t.revision.rawContent}),(0,H.jsx)(`button`,{type:`button`,disabled:a,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:async()=>{o(!0),i(null);try{await new Mj().rederiveResultAnalytics(e),c(`Analytics replayed from the pinned saved workout. Reload the results to view them.`)}catch(e){i(e instanceof Error?e.message:String(e))}finally{o(!1)}},children:a?`Replaying…`:`Replay saved analytics`}),(0,H.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:s}),(0,H.jsx)(qP,{noteId:t.session.noteId})]}):r?null:(0,H.jsx)(`p`,{role:`status`,children:`Loading saved workout…`})]})}function $1({searchHandlerRef:e}){let t=Sn(),n=mt(),{theme:r}=ji(),i=sD()??vR,a=_R(),o=jP(),s=PR(),c=NR(),{workout:l,nav:u}=s,[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)(`blank`),h=(0,V.useCallback)(e=>{m(e?.mode??`blank`),f(!0)},[]),g=(0,V.useMemo)(()=>/^\/journal\/(\d{4}-\d{2}-\d{2})\/?$/.exec(n.pathname)?.[1],[n.pathname]),_=(0,V.useCallback)(e=>{t(`${qA(e.id)}?edit=1`)},[t]),{tree:v,navState:y,setL3Items:b,setSecondarySpec:x,registerCreateJournal:S}=hA(),C=y?.activeL1Id??null,w=(v??[]).find(e=>e?.id===C)??null,T=s.shell.title??l.name,E=(0,V.useMemo)(()=>s.page===`library`?GM(VA(n.pathname)):void 0,[s.page,n.pathname]),D=s.shell.secondary;(0,V.useEffect)(()=>(x(D),()=>x(void 0)),[D,x]),(0,V.useEffect)(()=>S(h),[S,h]),(0,V.useEffect)(()=>{let e=new URLSearchParams(n.search);if(e.get(`create`)===`1`||e.get(`new`)===`1`){let r=e.get(`mode`)===`source`?`source`:`blank`;h({mode:r}),e.delete(`create`),e.delete(`new`),e.delete(`mode`);let i=e.toString()?`?${e.toString()}`:``;t(`${n.pathname}${i}`,{replace:!0})}},[n.pathname,n.search,h,t]),(0,V.useEffect)(()=>{if(!(!s.shell.withIndex||u.length===0))return b(Gz(u)),()=>b([])},[s.shell.withIndex,u,b]);let O=(0,V.useRef)(()=>null),k=(0,V.useCallback)(e=>(O.current=e,()=>{O.current===e&&(O.current=()=>null)}),[]),A=(0,V.useCallback)(()=>{UR.getState().open({wql:{initialQuery:O.current()??Fz(),execute:Lz,preferredChoices:Iz()},sources:[Mz(),Pz(dz(o)),Pz(iz())]}).then(e=>{e.dismissed||Rz(e.item,t)})},[t,o]);(0,V.useEffect)(()=>{e.current=A},[A,e]),(0,V.useEffect)(()=>{let e=e=>{e.key===`/`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.stopPropagation(),A())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[A]);let[j,M]=(0,V.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches),{handleViewCreated:N,scrollToSection:P}=Kz(u);(0,V.useEffect)(()=>{if(r!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>M(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let F=(0,V.useMemo)(()=>r===`system`?j?`vs-dark`:`vs`:r===`dark`?`vs-dark`:`vs`,[r,j]),I={feedDetail:()=>(0,H.jsx)(HJ,{feedSlug:decodeURIComponent(s.feedDetailMatch)}),feedItem:()=>(0,H.jsx)(kY,{feedSlug:decodeURIComponent(s.feedItemMatch[0]),feedDate:decodeURIComponent(s.feedItemMatch[1]),feedItem:decodeURIComponent(s.feedItemMatch[2]),theme:F,onViewCreated:N,onScrollToSection:P}),effortDetail:()=>(0,H.jsx)(g$,{}),equipmentDetail:()=>(0,H.jsx)(x$,{}),analyticsExplorer:()=>(0,H.jsx)(T1,{actions:(0,H.jsx)(OY,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardExplorer:()=>(0,H.jsx)(T1,{actions:(0,H.jsx)(OY,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardView:()=>(0,H.jsx)(Z1,{}),canvas:()=>s.canvasPage.route===`/`?(0,H.jsx)(ZX,{wodFiles:i,theme:F}):s.canvasPage.scroll?(0,H.jsx)(NJ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}):(0,H.jsx)(hJ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}),playground:()=>(0,H.jsx)(i$,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.effectivePlaygroundId),journalEntry:()=>(0,H.jsx)(HQ,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.journalEntryId),note:()=>(0,H.jsx)(T$,{noteId:s.noteById,theme:F},s.noteById),collectionDate:()=>(0,H.jsx)(k$,{slug:s.collectionDate.slug,date:s.collectionDate.date,theme:F},`${s.collectionDate.slug}/${s.collectionDate.date}`),workout:()=>(0,H.jsx)(a$,{category:s.workout.category,name:s.workout.name,mdContent:s.workout.content,theme:F,onViewCreated:N},`${s.workout.category}/${s.workout.name}`),library:()=>{let e=E??GM(VA(n.pathname));return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(e0,{pathname:n.pathname}),(0,H.jsx)(FQ,{profile:e,registerStreamDraft:k,actions:(0,H.jsx)(OY,{mode:`collection-readonly`,currentWorkout:l,index:[]})},e.route)]})},settings:()=>(0,H.jsx)(G1,{})},ee=s.page===`canvas`?s.canvasPage?.route:void 0,te=ee===`/`||!!ee?.startsWith(`/guide/`),ne=s.page===`canvas`&&s.canvasPage?(0,H.jsx)(H.Fragment,{children:s.canvasPage.quests.length>0&&(0,H.jsx)(IQ,{pageRoute:s.canvasPage.route,quests:s.canvasPage.quests,challengeSectionMap:rP(s.canvasPage),onScrollToSection:P})}):void 0;return(0,H.jsxs)(dR,{navbar:(0,H.jsxs)(NP,{children:[(0,H.jsxs)(`nav`,{"aria-label":`Breadcrumb`,className:`flex items-center gap-1.5 min-w-0 shrink-2 truncate text-sm`,children:[w&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>w?.action?.type===`route`&&t(w.action.to),className:`shrink-0 text-muted-foreground hover:text-foreground transition-colors`,children:w.label}),w&&!!T&&T.toLowerCase()!==w.label.toLowerCase()&&(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/50 shrink-0`,children:`›`}),T&&T.toLowerCase()!==w?.label.toLowerCase()&&(0,H.jsx)(`span`,{className:`text-sm font-semibold text-zinc-950 dark:text-white truncate`,children:T}),ne]}),(0,H.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,H.jsx)(IR,{}),(0,H.jsx)(iR,{}),(0,H.jsx)(YG,{})]})]}),sidebar:(0,H.jsx)(BI,{navSpec:s.shell.nav}),hideDesktopSidebar:te,secondary:D,pageAction:l.content===``?void 0:(0,H.jsx)(CY,{currentWorkout:l}),onSearch:A,onCreate:h,children:[(0,H.jsx)(xz,{open:d,onOpenChange:f,defaultDate:g,defaultMode:p,onCreated:_}),(0,H.jsx)(`div`,{className:`flex flex-col h-full min-h-[calc(100vh-theme(spacing.20))]`,children:(0,H.jsx)(`div`,{className:`flex-1 flex flex-col min-h-0`,children:(e=>{if(s.shell.wrap===`bare`)return e;let t=s.shell.subheader===`filter-collection-workouts`?(0,H.jsx)(ZK,{placeholder:`Filter notebook notes… Press / to start filtering`}):void 0;return(0,H.jsx)(tL,{title:s.shell.title,titleAccessory:ne,subheader:t,index:s.shell.withIndex?u:void 0,actions:s.shell.actionsMode?(0,H.jsx)(OY,{mode:s.shell.actionsMode,currentWorkout:l,index:u}):void 0,children:e})})(I[s.page]())})}),(0,H.jsx)(nz,{}),(0,H.jsx)(VR,{})]})}function e0({pathname:e}){let t=/^\/results\/([^/]+)\/?$/.exec(e);return t?(0,H.jsx)(Q1,{sessionId:decodeURIComponent(t[1])}):null}function t0(){let{name:e}=zn();return(0,H.jsx)(_n,{to:WA(e),replace:!0})}function n0(){let{category:e,name:t}=zn();return(0,H.jsx)(_n,{to:ZA(e,t),replace:!0})}function r0(){let{slug:e,target:t}=zn(),{search:n}=mt();return t==null?(0,H.jsx)(_n,{to:{pathname:XA(e),search:n},replace:!0}):SR(decodeURIComponent(t))?(0,H.jsx)(_n,{to:{pathname:qA(decodeURIComponent(t)),search:n},replace:!0}):(0,H.jsx)(_n,{to:{pathname:ZA(e,decodeURIComponent(t)),search:n},replace:!0})}function i0(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/feeds`,search:e},replace:!0})}function a0(){let{slug:e}=zn();return(0,H.jsx)(_n,{to:cj(e),replace:!0})}function o0(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/sessions`,search:e},replace:!0})}function s0(){return(0,H.jsx)(_n,{to:`/sessions?q=%3Asegment%7B%7D%20last%208w`,replace:!0})}function c0(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/dashboards`,search:e},replace:!0})}function l0(){let{runtimeId:e}=zn();return(0,H.jsx)(_n,{to:QA(e),replace:!0})}function u0(){let{runtimeId:e,noteId:t,resultId:n}=zn(),r=n??e;return r?(0,H.jsx)(_n,{to:ej(r),replace:!0}):t?(0,H.jsx)(_n,{to:`/sessions?q=${encodeURIComponent(`:session{note:${t}}`)}`,replace:!0}):(0,H.jsx)(_n,{to:`/sessions`,replace:!0})}function d0(){let e=mt().search,t=e&&e.startsWith(`?`)?`${e}&mode=plan`:`?mode=plan`;return(0,H.jsx)(_n,{to:`/journal${t}`,replace:!0})}function f0(){let{search:e}=mt();return(0,H.jsx)(_n,{to:{pathname:`/dashboards`,search:e},replace:!0})}var p0=`G-PROD-ID`,m0=!1;function h0(){if(m0||typeof document>`u`)return;m0=!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=${p0}`,document.head.appendChild(e),window.gtag(`js`,new Date),window.gtag(`config`,p0,{send_page_view:!1})}function g0(e,t){typeof window>`u`||!oH.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})}oH.setForwarder(e=>{window.gtag?.(`event`,e.name,e.payload??{})}),oH.consent?h0():oH.subscribeConsent(e=>{e&&h0()});function _0(){let e=mt();return(0,V.useEffect)(()=>{let t=e.pathname;if(!t.startsWith(`/effort/`)&&!t.startsWith(`/e/`)&&!t.startsWith(`/playground/`)&&!t.startsWith(`/equipment/`)){let e=`Wod.Wiki`;t.startsWith(`/journal`)?e=`Wod.Wiki - Journal`:t.startsWith(`/catalogs`)?e=`Wod.Wiki - Notebooks`:t.startsWith(`/feeds`)||t.startsWith(`/feed`)||t.startsWith(`/collections`)||t.startsWith(`/c/`)?e=`Wod.Wiki - Notes`:t.startsWith(`/efforts`)?e=`Wod.Wiki - Efforts`:t.startsWith(`/equipment`)?e=`Wod.Wiki - Equipment`:t.startsWith(`/sessions`)||t.startsWith(`/session/`)||t.startsWith(`/results`)?e=`Wod.Wiki - Sessions`:t.startsWith(`/dashboards`)||t===`/dashboard`||t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)?e=`Wod.Wiki - Dashboards`:t.startsWith(`/playgrounds`)?e=`Wod.Wiki - Playgrounds`:t.startsWith(`/syntax`)?e=`Wod.Wiki - Syntax`:t.startsWith(`/analytics`)&&(e=`Wod.Wiki - Analytics`),document.title=e}let n=setTimeout(()=>{g0(document.title,e.pathname+e.search)},0);return()=>clearTimeout(n)},[e.pathname,e.search]),null}function v0(e,t){let n=e.match(RegExp(`^${t}:\\s*"([^"]+)"`,`m`));if(!n?.[1])throw Error(`Guide example is missing frontmatter field: ${t}`);return n[1]}function y0(e){let t=e.match(/```time\n([\s\S]*?)\n```/);if(!t)throw Error("Guide example is missing a ```time fenced block.");return t[1]}function b0(e,t){let n=v0(e,`title`),r=v0(e,`subtitle`),i=y0(e);return{title:n,subtitle:r,docsPath:t,workout:i,storyContent:[`# `+n,``,r,``,"```time",i,"```"].join(`
182
+ `)}}var x0={coreRules:{path:`markdown/canvas/syntax/core-rules.md`,docsPath:`/guide/start?h=first-workout`},measurements:{path:`markdown/canvas/syntax/measurements.md`,docsPath:`/guide/start?h=measurements`},timerModifiers:{path:`markdown/canvas/syntax/timer-modifiers.md`,docsPath:`/guide/protocols?h=countdown-countup`},simpleRounds:{path:`markdown/canvas/syntax/groups-1.md`,docsPath:`/guide/structure?h=rounds`},repSchemes:{path:`markdown/canvas/syntax/groups-2.md`,docsPath:`/guide/structure?h=rep-schemes`},timersAndRest:{path:`markdown/canvas/syntax/timers-rest.md`,docsPath:`/guide/protocols?h=required-rest`},classicAmrap:{path:`markdown/canvas/syntax/classic-amrap.md`,docsPath:`/guide/protocols?h=amrap`},basicEmom:{path:`markdown/canvas/syntax/basic-emom.md`,docsPath:`/guide/protocols?h=emom`},standardTabata:{path:`markdown/canvas/syntax/protocols-4.md`,docsPath:`/guide/protocols?h=tabata-intervals`},mixedSections:{path:`markdown/canvas/syntax/mixed-sections.md`,docsPath:`/guide/structure?h=named-sections`},complexNestedProtocols:{path:`markdown/canvas/syntax/complex-nested-protocols.md`,docsPath:`/guide/sessions?h=nested`}};function S0(e){let t={};for(let[n,{path:r,docsPath:i}]of Object.entries(x0)){let a=e[r];if(!a){t[n]=void 0;continue}try{t[n]=b0(a,i)}catch{t[n]=void 0}}return t}function C0({actionsSlot:e,heroSlot:t,children:n,className:r}){return(0,H.jsxs)(`main`,{className:U(`mx-auto w-full max-w-7xl px-6 py-10 sm:px-8 lg:px-12 lg:py-14`,r),children:[e&&(0,H.jsx)(`div`,{className:`mb-6 flex justify-end`,children:e}),t,n]})}var w0={headline:`Build and preview widget-driven workout pages.`,subtitle:`Phase 2.2 integrates the attention, code-example, and syntax-group widgets into one interactive playground surface.`,pillars:[{icon:(0,H.jsx)(vn,{className:`size-4`,"aria-hidden":`true`}),label:`Attention widget`,description:`High-signal hero block with actionable CTAs.`},{icon:(0,H.jsx)(yt,{className:`size-4`,"aria-hidden":`true`}),label:`Code example widget`,description:`Editable CodeMirror sample with runnable workout output.`},{icon:(0,H.jsx)(s,{className:`size-4`,"aria-hidden":`true`}),label:`Syntax group widget`,description:`Grouped syntax cards linked to docs.`}],actions:[{label:`Jump to workout`,action:`scroll-to-workout`,variant:`primary`},{label:`Open search`,action:`open-search`,variant:`secondary`}]};function T0(){let e=Sn(),{theme:t,setTheme:n}=ji(),r=(0,V.useRef)(null),i=sD(),a=(0,V.useMemo)(()=>i?S0(i):null,[i]),o=(0,V.useMemo)(()=>(a?.classicAmrap?.workout??`20:00 AMRAP
171
183
  5 Pullups
172
184
  10 Pushups
173
185
  15 Air Squats`).split(`
@@ -175,8 +187,8 @@ Timer 12:00
175
187
  10 Air Squats`,docsPath:e?.docsPath??`/guide/structure?h=rounds`},{category:`Timing`,icon:`⏱️`,title:t?.title??`Timers And Rest`,description:t?.subtitle??`Timed windows with rest periods.`,example:t?.workout??`10:00
176
188
  5 Burpees
177
189
  rest 1:00`,docsPath:t?.docsPath??`/guide/protocols?h=required-rest`},{category:`Structure`,icon:`🏋️`,title:`Rep Schemes`,description:n?.subtitle??`Rep counts per movement.`,example:n?.workout??`21-15-9
178
- Thrusters`,docsPath:n?.docsPath??`/guide/structure?h=rep-schemes`}]},[a]),l=(0,V.useMemo)(()=>t===`dark`||t!==`light`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches,[t]),u=jP(),d=(0,V.useCallback)(async()=>{let t=await UR.getState().open({wql:{initialQuery:Fz(),execute:Lz,preferredChoices:Iz()},sources:[Mz(),Pz(dz(u))]});t.dismissed||Rz(t.item,e)},[e,u]),f=(0,V.useCallback)(e=>{if(e===`scroll-to-workout`){r.current?.scrollIntoView({behavior:`smooth`,block:`start`});return}e===`open-search`&&d()},[d]),p=(0,V.useCallback)(async t=>{let n=await iH([`# Playground Widget Example`,``,"```time",t,"```",``,`[▶ Run Workout]{.button action=start-workout}`,``].join(`
179
- `));e(WA(n))},[e]),m=(0,V.useCallback)(t=>{if(/^https?:\/\//i.test(t)){window.open(t,`_blank`,`noopener,noreferrer`);return}e(t)},[e]);return(0,H.jsxs)(f0,{actionsSlot:(0,H.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,H.jsx)(et,{className:`size-4 text-zinc-500`,"aria-hidden":`true`}),(0,H.jsx)(h1,{checked:l,onChange:e=>n(e?`dark`:`light`),"aria-label":`Toggle dark mode`}),(0,H.jsx)(ir,{className:`size-4 text-zinc-500`,"aria-hidden":`true`})]}),heroSlot:(0,H.jsx)(NQ,{config:p0,onAction:f}),children:[(0,H.jsxs)(`section`,{ref:r,id:`workout-widget-surface`,className:`mt-8 grid grid-cols-1 gap-4 xl:grid-cols-3`,children:[(0,H.jsx)(`div`,{className:`xl:col-span-2`,children:(0,H.jsx)(PQ,{config:s,isDarkMode:l,onRun:p})}),(0,H.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,H.jsx)(FQ,{config:e,onOpenDocs:m},e.title))})]}),(0,H.jsx)(ZY,{})]})}function h0({activeIndex:e,onCommand:t,captions:n}){return(0,H.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`tour-captions`,children:n.map((n,r)=>(0,H.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,H.jsx)(g0,{cap:n,onCommand:t})},n.id))})}function g0({cap:e,onCommand:t}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`h3`,{className:`mb-3.5 xl:mb-5 text-[clamp(22px,2vw,32px)] font-extrabold leading-[1.12] tracking-[-0.03em]`,children:[(0,H.jsx)(`span`,{className:`mr-2 align-[0.2em] font-mono text-[0.5em] font-semibold tracking-[0.08em] text-muted-foreground/50`,children:e.num}),e.title]}),(0,H.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,H.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,H.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,H.jsx)(`span`,{children:e})]},t))}),e.foot&&(0,H.jsx)(`div`,{className:`mt-4 xl:mt-6 border-t border-border pt-3 xl:pt-4 font-mono text-[10px] xl:text-[11px] tracking-[0.06em] text-muted-foreground/60`,children:e.foot}),e.extra&&(0,H.jsx)(`div`,{className:`mt-3`,children:e.extra}),e.commands&&e.commands.length>0&&t&&(0,H.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,H.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,H.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,H.jsx)(Wn,{to:e.href,onClick:()=>YV.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 _0({visible:e,children:t}){return(0,H.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 v0=(0,V.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,V.useRef)(null),f=(0,V.useRef)(null),[p,m]=(0,V.useState)(null),h=(0,V.useCallback)(e=>{f.current=e,m(e)},[]),{slice:g,subscribe:_,resync:v,runwayReached:y}=MK(d,!1,r,e),b=b0(d);(0,V.useEffect)(()=>{o?.(b)},[b,o]),(0,V.useEffect)(()=>{s?.(y)},[y,s]);let[x,S]=(0,V.useState)(!1),C=y0(d);(0,V.useEffect)(()=>{(C||y)&&S(!0)},[C,y]);let w=g.stage?.screen??`editor`,T=(0,V.useRef)(null);return(0,V.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,V.useImperativeHandle)(u,()=>({scrollToStage:e=>{let t=d.current,n=r.find(t=>t.id===e);!t||!n||jK(t,Math.min(n.range[0]+.02,n.range[1]-.005))},subscribe:_,resync:v}),[r,_,v]),(0,H.jsxs)(`section`,{id:`tour-section-${e}`,"data-testid":`tour-section-${e}`,children:[n,(0,H.jsx)(kK,{trackRef:d,height:t,stages:r,activeIndex:g.index,segmentId:e,testId:`tour-runway`,pane:(0,H.jsx)(`div`,{ref:h,className:`absolute inset-0 flex flex-col justify-center`,children:(0,H.jsxs)(AY,{children:[(0,H.jsx)(NY,{ringKey:`editor.window`,el:p}),(0,H.jsx)(CH,{title:LY[w],className:`relative h-full max-h-[760px]`,children:(0,H.jsx)(OK,{gateId:`${e}-pane`,segmentId:e,className:`relative h-full`,children:l&&(0,H.jsx)(_0,{visible:w===`editor`,children:(0,H.jsx)(QY,{doc:l.doc,onDocChange:l.onDocChange,onBlocksChange:l.onBlocksChange,onRun:l.onRun,theme:l.theme,withRingTargets:!0})})})}),(0,H.jsx)(PY,{target:g.ring?.key?{key:g.ring.key}:null,accent:g.stage.accent??IY.editor,canvasRef:f})]})}),captions:(0,H.jsx)(h0,{activeIndex:g.index,captions:i,onCommand:c})})]})});function y0(e){let[t,n]=(0,V.useState)(!1);return(0,V.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 b0(e){let[t,n]=(0,V.useState)(()=>typeof IntersectionObserver>`u`);return(0,V.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 x0={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`},S0={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`]}},C0=[{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 w0({chapters:e=[],allQuests:t=[],theme:n,wodFiles:r={},onRun:i}){let a=(0,V.useMemo)(()=>{let t=(e??[]).filter(e=>e.id!==`home-tour`);return t.length>0?t:C0},[e]),o=bH(`(prefers-reduced-motion: reduce)`),{markComplete:s}=_H(`/`,t),{chapters:c}=AX(a),[l,u]=(0,V.useState)(()=>a[0]?.id??`basics`),[d,f]=(0,V.useState)(``),p=(0,V.useRef)([]),m=(0,V.useRef)(l);m.current=l;let h=(0,V.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,BL(x0[e.id]??``,r)])),[a,r]);(0,V.useEffect)(()=>{p.current=[],f(h[l]??``)},[l,h]);let g=(0,V.useCallback)(e=>{p.current=e},[]),_=(0,V.useCallback)(()=>{let e=m.current;s(`${e}-run`),i?.(e,p.current[0]??null,d)},[d,s,i]),v=(0,V.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,V.useMemo)(()=>Object.fromEntries(c.map(e=>[e.chapter.id,e])),[c]),b=(0,V.useMemo)(()=>a.map((e,t)=>{let n=S0[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,H.jsx)(`span`,{"data-testid":`chapter-picker-progress-${e.id}`,className:U(`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:RY[e.id]??`/guide/start`,event:XV.chapterGuideClicked,data:{chapter:e.id},testId:`chapter-picker-guide-${e.id}`}]}}),[a,y]);return(0,H.jsxs)(`section`,{id:`tour-chapter-picker`,"data-testid":`tour-chapter-picker`,className:`flex flex-col`,children:[(0,H.jsx)(UY,{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,H.jsx)(T0,{chapters:a,selectedId:l,onSelect:u,doc:d,onDocChange:f,theme:n,onBlocksChange:g,onRun:_,progressByChapter:y}):(0,H.jsx)(v0,{id:`learn`,heightVh:`600vh`,stages:v,captions:b,onActiveStageChange:u,editor:{doc:d,theme:n,onDocChange:f,onBlocksChange:g,onRun:_}})]})}function T0({chapters:e,selectedId:t,onSelect:n,doc:r,onDocChange:i,theme:a,onBlocksChange:o,onRun:s,progressByChapter:c}){return(0,H.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,H.jsxs)(`div`,{className:`flex flex-col gap-10 lg:flex-row lg:items-start lg:gap-12 xl:gap-16`,children:[(0,H.jsx)(`div`,{className:`w-full lg:w-[58%] xl:w-[60%] lg:sticky lg:top-[110px] z-10 flex-none`,children:(0,H.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,H.jsx)(CH,{title:RY[t]?.split(`/`).pop()??`example.md`,subtitle:`Lesson: ${e.find(e=>e.id===t)?.title??t}`,className:`h-full`,children:(0,H.jsx)(QY,{doc:r,onDocChange:i,onBlocksChange:o,onRun:s,theme:a,withRingTargets:!1})})})}),(0,H.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=Eq(e.badge),o=e.id===t,s=S0[e.id];return(0,H.jsxs)(`div`,{"data-testid":`chapter-picker-row-${e.id}`,className:U(`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,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsxs)(`span`,{className:`font-mono text-xs font-bold uppercase tracking-wider text-primary`,children:[`Chapter 0`,r+1]}),a&&(0,H.jsx)(a,{className:`size-4 text-primary`})]}),(0,H.jsx)(`span`,{className:U(`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,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground sm:text-3xl`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-3 text-sm sm:text-base leading-relaxed text-muted-foreground`,children:s?.summary??e.title}),s?.bullets&&(0,H.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,H.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,H.jsx)(`span`,{children:e})]},t))})]}),(0,H.jsxs)(`div`,{className:`mt-6 flex flex-wrap items-center gap-3 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e.id),"data-testid":`chapter-picker-select-${e.id}`,"aria-pressed":o,className:U(`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,H.jsx)(Ht,{className:`size-3.5 fill-current`}),(0,H.jsx)(`span`,{children:o?`Loaded in editor`:`Load example`})]}),(0,H.jsxs)(Wn,{to:RY[e.id]??`/guide/start`,"data-testid":`chapter-picker-guide-${e.id}`,"aria-label":`Read guide for ${e.title}`,onClick:()=>YV.record(XV.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,H.jsx)(Ie,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Read guide →`})]})]})]},e.id)})})]})})}function E0({chapters:e}){let t=()=>YV.record(XV.lessonStarted),n=()=>YV.record(XV.cheatsheetOpened),{chapters:r}=AX(e),i=r.filter(e=>e.chapter.id!==`home-tour`);return(0,H.jsxs)(`section`,{"data-testid":`tour-learn`,className:`mx-auto max-w-5xl px-6 py-16 border-b border-border/60`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-bold tracking-tight`,children:`Learn the Language`}),(0,H.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,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsx)(Wn,{to:`/guide/start`,onClick:t,className:`inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90`,children:`Start Lesson 1`}),(0,H.jsx)(Wn,{to:`/guide/start?h=reference`,onClick:n,className:`text-sm font-semibold text-primary underline-offset-2 hover:underline`,children:`Cheat sheet →`})]})]}),(0,H.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=RY[e.id]??`/guide/start`,a=Eq(e.badge);return(0,H.jsxs)(Wn,{to:i,"data-testid":`learn-progress-chip-${e.id}`,className:U(`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,H.jsx)(a,{className:`size-3.5 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`text-[12px] font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`span`,{className:U(`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 D0=E0;function O0(){let e=sD()??vR,{theme:t}=ji(),[n,r]=(0,V.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches);(0,V.useEffect)(()=>{if(t!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=e=>r(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[t]);let i=(0,V.useMemo)(()=>t===`system`?n?`vs-dark`:`vs`:t===`dark`?`vs-dark`:`vs`,[t,n]),a=MP(`/`),o=jP(),s=a?.chapters??[],c=a?.quests??[],l=(0,V.useMemo)(()=>{let e={};for(let{page:t}of o)for(let n of t.quests)e[n.id]=n.label;return e},[o]),u=ZV()?.track,{start:d,finalize:f,end:p}=sH(),[m,h]=(0,V.useState)(null),[g,_]=(0,V.useState)(0),[v,y]=(0,V.useState)(!1),b=(0,V.useCallback)(()=>{h(null),y(!1)},[]),x=(0,V.useCallback)(async(e,t,n)=>{if(t){u?.(XV.chapterExampleRun,{chapter:e}),h(t),_(e=>e+1),y(!0);try{await d(n,t,{pageTitle:`Syntax`,sectionTitle:`Chapter ${e}`})}catch(e){console.error(`[SyntaxView] failed to persist playground run note:`,e),b(),Z({title:`Could not start workout`,variant:`destructive`})}}},[b,d,u]),S=(0,V.useCallback)(async(e,t)=>{try{(t.logs??[]).length===0?await p():await f(t,t.completed)}catch(e){console.error(`[SyntaxView] failed to save session:`,e),Z({title:`Session not saved`,variant:`destructive`})}finally{b()}},[b,p,f]);return(0,H.jsx)(AY,{children:(0,H.jsxs)(`div`,{"data-testid":`syntax-view`,children:[(0,H.jsx)(UY,{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,H.jsx)(w0,{wodFiles:e,chapters:s,allQuests:c,theme:i,onRun:x}),(0,H.jsx)(D0,{quests:c,chapters:s,questLabels:l}),(0,H.jsx)(Pq,{}),(0,H.jsx)(VY,{}),m&&v&&(0,H.jsx)(BG,{block:m,autoStart:!0,onClose:b,onCompleteWorkout:S},g)]})})}function k0(){let e=Sn();return(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,H.jsx)(Ve,{className:`w-8 h-8 text-muted-foreground`})}),(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Page not found`}),(0,H.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`The page you are looking for does not exist or has been moved.`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>e(`/`),className:`inline-flex items-center gap-2 px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors`,children:[(0,H.jsx)(T,{className:`w-4 h-4`}),`Go home`]})]})}var $=(e=0,t=0,n=0,r=0,i=0)=>[e,t,n,r,i],A0=(e,t)=>e.map((e,n)=>e+t[n]),j0=(e,t)=>e.map((e,n)=>e-t[n]),M0=(e,t)=>e.every((e,n)=>e===t[n]),N0=$(),P0=[`length`,`mass`,`time`,`count`,`energy`];function F0(e){if(M0(e,N0))return`dimensionless`;let t=[];return e.forEach((e,n)=>{e!==0&&t.push(`${P0[n]}${e===1?``:`^`+e}`)}),t.join(` · `)}var I0={m:{dim:$(1),toBase:1},km:{dim:$(1),toBase:1e3},mi:{dim:$(1),toBase:1609.34},kg:{dim:$(0,1),toBase:1},lb:{dim:$(0,1),toBase:.4536},ms:{dim:$(0,0,1),toBase:.001},s:{dim:$(0,0,1),toBase:1},min:{dim:$(0,0,1),toBase:60},h:{dim:$(0,0,1),toBase:3600},reps:{dim:$(0,0,0,1),toBase:1},cal:{dim:$(0,0,0,0,1),toBase:1},MET:{dim:N0,toBase:1},pts:{dim:N0,toBase:1},AU:{dim:N0,toBase:1},ratio:{dim:N0,toBase:1},"MET-min":{dim:$(0,0,1),toBase:60},"reps/min":{dim:j0($(0,0,0,1),$(0,0,1)),toBase:1/60},"m/s":{dim:j0($(1),$(0,0,1)),toBase:1},"min/km":{dim:j0($(0,0,1),$(1)),toBase:60/1e3},"sec/km":{dim:j0($(0,0,1),$(1)),toBase:1/1e3},"min/mi":{dim:j0($(0,0,1),$(1)),toBase:60/1609.34},"km/h":{dim:j0($(1),$(0,0,1)),toBase:1e3/3600},"kg/s":{dim:j0(A0($(0,1),$(0,0,0,1)),$(0,0,1)),toBase:1},"lb/s":{dim:j0(A0($(0,1),$(0,0,0,1)),$(0,0,1)),toBase:.4536}},L0=[{dim:j0($(0,0,1),$(1)),name:`pace`,units:[`min/km`,`sec/km`,`min/mi`]},{dim:j0($(1),$(0,0,1)),name:`speed`,units:[`m/s`,`km/h`]},{dim:A0($(0,1),$(0,0,0,1)),name:`volume`,units:[`kg`,`lb`]},{dim:j0(A0($(0,1),$(0,0,0,1)),$(0,0,1)),name:`power`,units:[`kg/s`,`lb/s`]},{dim:$(0,0,1),name:`time`,units:[`min`,`s`,`MET-min`]},{dim:$(0,0,0,1),name:`count`,units:[`reps`]},{dim:$(1),name:`length`,units:[`m`,`km`,`mi`]},{dim:$(0,1),name:`mass`,units:[`kg`,`lb`]},{dim:N0,name:`dimensionless`,units:[`pts`,`AU`,`MET`]}],R0=e=>L0.find(t=>M0(t.dim,e)),z0=(e,t=N0)=>({v:e,dim:t}),B0={thruster:{met:6,discipline:`strength`,disciplineFactor:1.2,intensityTier:`high`,resolvedFrom:`bundled`},"pull-up":{met:5,discipline:`gymnastics`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`},run:{met:9.8,discipline:`running`,disciplineFactor:1,intensityTier:`high`,resolvedFrom:`bundled`},squat:{met:5,discipline:`strength`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`}},V0={met:$(0,0,0,0,0),disciplineFactor:N0},H0={easy:3,moderate:5,hard:7,"all-out":10,max:10},U0={effort:{fields:[`met`,`discipline`,`disciplineFactor`,`intensityTier`,`resolvedFrom`],get:(e,t)=>{let n=B0[e];if(!n)return t===`resolvedFrom`?z0(NaN):void 0;let r=n[t];return typeof r==`number`?{v:r,dim:V0[t]??N0}:void 0}},"rpe-labels":{fields:[`rpe`],get:e=>H0[e]===void 0?void 0:z0(H0[e])}},W0={min:e=>z0(Math.min(...e.map(e=>e.v)),e[0]?.dim??N0),max:e=>z0(Math.max(...e.map(e=>e.v)),e[0]?.dim??N0),abs:e=>z0(Math.abs(e[0].v),e[0].dim),round:e=>z0(e.length>1?+e[0].v.toFixed(e[1].v):Math.round(e[0].v),e[0].dim),floor:e=>z0(Math.floor(e[0].v),e[0].dim),ceil:e=>z0(Math.ceil(e[0].v),e[0].dim),clamp:e=>z0(Math.min(Math.max(e[0].v,e[1].v),e[2].v),e[0].dim),convert:e=>{let t=e[1].unit??``,n=I0[t];if(!n||!M0(n.dim,e[0].dim))throw Error(`convert: ${t} dimension ≠ value dimension`);return{v:e[0].v/n.toBase,dim:e[0].dim}}},G0=Object.keys(W0).concat([`has`,`lookup`]);function K0(e){let t=[],n=/\s*("(?:[^"]*)"|\d+\.?\d*|[a-zA-Z_][\w.-]*(?::[\w.:*!|,-]+(?:\{[^}]*\})?(?:\s+by\s+\{[^}]*\})?)?|[-+*/(),<>!=]=?|>=|<=|==)/y,r,i=0;for(;i<e.length;){if(n.lastIndex=i,r=n.exec(e),!r||r.index!==i){/\S/.test(e[i])&&t.push({t:`err`,s:e[i]}),i+=1;continue}i=n.lastIndex;let a=r[1];/^".*"$/.test(a)?t.push({t:`str`,s:a.slice(1,-1)}):/^\d/.test(a)?t.push({t:`num`,s:a}):/^[-+*/(),]$/.test(a)||[`>=`,`<=`,`==`,`!=`,`>`,`<`,`=`].includes(a)?t.push({t:`op`,s:a}):t.push({t:`id`,s:a})}return t}function q0(e){let t=0,n=()=>e[t];function r(i){let a,o=e[t++];if(!o)throw Error(`unexpected end`);if(o.t===`num`)a={k:`num`,v:parseFloat(o.s)};else if(o.t===`str`)a={k:`str`,s:o.s};else if(o.s===`-`)a={k:`neg`,e:r(70)};else if(o.s===`(`){if(a=r(0),n()?.s!==`)`)throw Error(`missing )`);t++}else if(o.t===`id`){if(n()?.s===`(`){t++;let e=[];if(n()?.s!==`)`)for(;;){if(e.push(r(0)),n()?.s===`,`){t++;continue}break}if(n()?.s!==`)`)throw Error(`missing )`);t++,a={k:`call`,f:o.s,args:e}}else a={k:`id`,s:o.s}}else throw Error(`unexpected "${o.s}"`);for(;;){let e=n()?.s,o=e===`*`||e===`/`?60:e===`+`||e===`-`?50:[`<`,`<=`,`>`,`>=`,`==`,`!=`].includes(e)?40:e===`and`?30:e===`or`?20:0;if(!o||o<i)break;t++;let s=r(o+1);a={k:`bin`,op:e,l:a,r:s}}return a}let i=r(0);if(t<e.length)throw Error(`trailing "${e[t].s}"`);return i}function J0(e,t,n){switch(e.k){case`num`:return z0(e.v);case`str`:return{v:NaN,dim:N0,unit:e.s};case`neg`:{let r=J0(e.e,t,n);return z0(-r.v,r.dim)}case`id`:{if(/^(sum|avg|max|min|count|last):/.test(e.s)){let t=n(e.s);if(!t)throw Error(`no data for ${e.s}`);return t}let r=t[e.s];if(r===void 0)throw Error(`unknown or absent: ${e.s}`);return r}case`bin`:{if(e.op===`and`)return z0(J0(e.l,t,n).v&&J0(e.r,t,n).v?1:0);if(e.op===`or`)return z0(J0(e.l,t,n).v||J0(e.r,t,n).v?1:0);let r=J0(e.l,t,n),i=J0(e.r,t,n);switch(e.op){case`+`:if(!M0(r.dim,i.dim))throw Error(`+ : ${F0(r.dim)} vs ${F0(i.dim)}`);return z0(r.v+i.v,r.dim);case`-`:if(!M0(r.dim,i.dim))throw Error(`- : ${F0(r.dim)} vs ${F0(i.dim)}`);return z0(r.v-i.v,r.dim);case`*`:return z0(r.v*i.v,A0(r.dim,i.dim));case`/`:return z0(r.v/i.v,j0(r.dim,i.dim));case`<`:return z0(+(r.v<i.v));case`<=`:return z0(+(r.v<=i.v));case`>`:return z0(+(r.v>i.v));case`>=`:return z0(+(r.v>=i.v));case`==`:return z0(+(r.v===i.v));case`!=`:return z0(r.v===i.v?0:1)}throw Error(e.op)}case`call`:{if(e.f===`has`){let r=e.args[0];return r.k===`id`?z0(t[r.s]!==void 0||/^(sum|avg|max|min|count|last):/.test(r.s)&&n(r.s)!==void 0?1:0):z0(0)}if(e.f===`lookup`){let[n,r,i]=e.args,a=n.k===`str`?n.s:``,o=r.k===`str`?r.s:r.k===`id`?String(t[r.s]?.v??r.s):``,s=i.k===`str`?i.s:``,c=U0[a];if(!c)throw Error(`unknown table "${a}"`);if(!c.fields.includes(s))throw Error(`table "${a}" has no field "${s}"`);if(a===`effort`&&s===`resolvedFrom`)return z0(+!!B0[o]);let l=c.get(o,s);if(!l)throw Error(`lookup miss: ${a}/${o}/${s}`);return l}let r=W0[e.f];if(!r)throw Error(`unknown function ${e.f}`);return r(e.args.map((r,i)=>e.f===`convert`&&i>0&&r.k===`id`?{v:NaN,dim:N0,unit:r.s}:J0(r,t,n)))}}}var Y0=[{effort:`thruster`,label:`hard`,reps:21,resistanceKg:43,elapsedMs:95e3},{effort:`pull-up`,reps:21,elapsedMs:6e4},{effort:`thruster`,reps:15,resistanceKg:43,elapsedMs:7e4},{effort:`pull-up`,reps:15,elapsedMs:5e4},{effort:`sled-push`,reps:9,resistanceKg:43,elapsedMs:45e3},{effort:`pull-up`,reps:9,elapsedMs:3e4}],X0=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function Z0(e){let t=B0[e.effort]?.met??4,n=!B0[e.effort];return{segmentVolume:e.reps&&e.resistanceKg?z0(e.reps*e.resistanceKg,A0($(0,1),$(0,0,0,1))):void 0,metMinutes:z0(t*(e.elapsedMs/6e4),$(0,0,1)),metMinutesEstimated:n?z0(1):void 0,effortRpe:e.label?z0(H0[e.label]??0):void 0}}function Q0(e){let t={name:``,exprSrc:``,alternates:[],library:!1,bindings:[]};try{let n=e.trim(),r=/\s+when\s+/.exec(n);r&&(t.whenSrc=n.slice(r.index+r[0].length).trim(),n=n.slice(0,r.index));let i=/\s+where\s+/.exec(n);if(i){let e=n.slice(i.index+i[0].length).trim();n=n.slice(0,i.index);for(let n of e.split(/,\s*(?=[a-zA-Z_][\w]*\s*=)/)){let e=n.indexOf(`=`);e>0&&t.bindings.push({name:n.slice(0,e).trim(),src:n.slice(e+1).trim()})}}let a=/\s*->\s*/.exec(n);a&&(t.unit=n.slice(a.index+a[0].length).trim().replace(/\s+(key|grouped).*$/,``),n=n.slice(0,a.index)),/\(library\)/.test(n)&&(t.library=!0,n=n.replace(`(library)`,``));let o=n.indexOf(`=`);if(o<0)throw Error(`expected name = expression`);t.name=n.slice(0,o).trim();let s=n.slice(o+1).trim().split(`|`).map(e=>e.trim());return t.exprSrc=s[0],t.alternates=s.slice(1).map(e=>({src:e.replace(/\s*estimated\s*$/,``),estimated:/\bestimated\b/.test(e)})),t}catch(e){return t.error=e instanceof Error?e.message:String(e),t}}function $0(e,t,n,r){let i=Z0(e);return{elapsed:z0(e.elapsedMs/1e3,$(0,0,1)),reps:e.reps===void 0?void 0:z0(e.reps,$(0,0,0,1)),resistance:e.resistanceKg===void 0?void 0:z0(e.resistanceKg,$(0,1)),distance:e.distanceM===void 0?void 0:z0(e.distanceM,$(1)),effort:z0(NaN),effortLabel:e.label?z0(NaN):void 0,segmentVolume:i.segmentVolume,metMinutes:i.metMinutes,effortRpe:i.effortRpe,sessionRpe:n===void 0?void 0:z0(n),"profile.vo2max":r===void 0?void 0:z0(r),...t}}var e2=e=>e.effort;function t2(e,t,n,r){let i=Q0(e),a=[];if(i.error)return{calc:i,diagnostics:[i.error]};let o={calc:i,diagnostics:a},s=e=>e instanceof Error?e.message:String(e);if(t!==`store`){try{q0(K0(i.exprSrc))}catch(e){a.push(`expression: ${s(e)}`)}for(let e of i.bindings)for(let t of e.src.split(`|`))try{q0(K0(t.replace(/\s*estimated\s*$/,``)))}catch(t){a.push(`${e.name}: ${s(t)}`)}if(i.whenSrc)try{q0(K0(i.whenSrc))}catch(e){a.push(`when: ${s(e)}`)}}let c=Y0,l=(e,t=c.length)=>{let i=/^(sum|avg|max|min|count|last):([\w.]+)/.exec(e);if(!i)return;let[,a,o]=i,s=c.slice(0,t),l=[];for(let e of s){let t=$0(e,{},n,r)[o];t!==void 0&&!Number.isNaN(t.v)&&l.push(t)}if(o===`sessionLoad`&&e.includes(`by {day}`))return z0(NaN);if(!l.length)return;let u=l[0].dim,d=l.map(e=>e.v);if(a===`sum`)return z0(d.reduce((e,t)=>e+t,0),u);if(a===`avg`)return z0(d.reduce((e,t)=>e+t,0)/d.length,u);if(a===`max`)return z0(Math.max(...d),u);if(a===`min`)return z0(Math.min(...d),u);if(a===`count`)return z0(d.length,$(0,0,0,1));if(a===`last`)return l[l.length-1]},u=(e,t,n)=>{let r={...t};for(let e of i.bindings){let t=e.src.split(`|`).map(e=>e.replace(/\s*estimated\s*$/,``).trim()),i;for(let e of t)try{i=d(e,r,n);break}catch{}if(i===void 0)throw Error(`${e.name}: no applicable variant`);r[e.name]=i}return d(e,r,n)},d=(e,t,n)=>J0(q0(K0(e)),t,e=>l(e,n));try{if(t===`segment`){let e=[],t;c.forEach((a,o)=>{try{let s=$0(a,{},n,r);if(s.effort=void 0,i.whenSrc&&!d(i.whenSrc,s,o+1).v){e.push(null);return}let c=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${e2(a)}",`).replace(/lookup\("rpe-labels",\s*effortLabel\s*,/g,`lookup("rpe-labels", "${a.label??``}",`),l=u(c,s,o+1);t||=l.dim;let f=i.unit&&i.unit!==`auto`?` ${i.unit}`:t?` [${F0(l.dim)}]`:``;e.push(`${Math.round(l.v*100)/100}${f}`)}catch(t){e.push(`∅ ${s(t)}`)}}),o.perSegment=e,o.dim=t}else if(t===`workout`){let e=[],t;for(let a=1;a<=c.length;a++)try{let s=c[a-1],l=$0(s,{"session.duration":z0(c.slice(0,a).reduce((e,t)=>e+t.elapsedMs,0)/1e3,$(0,0,1))},n,r);if(i.whenSrc&&!d(i.whenSrc,l,a).v){e.push(null);continue}let f=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${e2(s)}",`),p,m=`primary`;try{p=u(f,l,a)}catch(e){for(let e of i.alternates)try{p=u(e.src,l,a),m=e.estimated?`estimated`:`alternate`;break}catch{}if(p===void 0)throw e}t=p.dim,e.push(`${Math.round(p.v*100)/100}${i.unit&&i.unit!==`auto`?` `+i.unit:``}${m===`estimated`?` (est.)`:``}`),o.variantUsed=m}catch(t){e.push(`∅ ${s(t)}`)}o.running=e,o.dim=t}else{let e=X0,t=(e,t,n)=>e.map((r,i)=>i+1>=t?n(e.slice(i+1-t,i+1)):NaN),n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=e=>{let t=n(e);return Math.sqrt(n(e.map(e=>(e-t)**2)))},a=i.name,s=[];if(a.includes(`acwr`)){let r=t(e,7,n),i=t(e,28,n);s=e.map((e,t)=>r[t]/i[t])}else if(a.includes(`monotony`)){let i=t(e,7,n),a=t(e,7,r);s=e.map((e,t)=>i[t]/a[t])}else if(a.includes(`strain`)){let i=t(e,7,n),a=t(e,7,r),o=t(e,7,e=>e.reduce((e,t)=>e+t,0));s=e.map((e,t)=>i[t]/a[t]*o[t])}else s=t(e,7,n);o.perSegment=s.slice(-7).map(e=>Number.isNaN(e)?null:String(Math.round(e*100)/100)),o.dim=N0}}catch(e){a.push(s(e))}if(o.dim&&i.unit&&i.unit!==`auto`){let e=I0[i.unit];e?!M0(e.dim,o.dim)&&!M0(e.dim,N0)&&a.push(`unit "${i.unit}" is ${F0(e.dim)} but expression computes ${F0(o.dim)}`):a.push(`unknown unit "${i.unit}"`)}return o}function n2(e,t){let n=/([a-zA-Z_][\w.:-]*|"[\w-]*|)$/.exec(e)[1],r=e.length-n.length,i=e.slice(0,r),a=[],o=(e,t,n)=>a.push({label:e,insert:t,detail:n}),s=/lookup\("([\w-]*)",?\s*("[\w-]*",?\s*)?"?([\w-]*)$/.exec(e);if(s){if(s[2]===void 0&&!e.endsWith(`"`))U0&&Object.keys(U0).forEach(e=>o(e,`"${e}"`,`lookup table`));else{let t=s[1];(e.split(`"`).length<=5&&s[3]!==void 0||/,\s*"[\w-]*$/.test(e))&&(U0[t]?.fields??[]).forEach(e=>o(e,`"${e}"`,`${t} field`)),t===`effort`&&/,\s*$/.test(e)&&Object.keys(B0).concat([`effort`]).forEach(e=>o(e,e===`effort`?`effort`:`"${e}"`,`key`))}return{items:a.filter(e=>e.label.startsWith(n.replace(/"/g,``))),from:r}}return/^(sum|avg|max|min|count|last):[\w.]*$/.test(n)?((t===`segment`?[]:[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`,`sessionLoad`]).forEach(e=>o(e,e,`metric key`)),{items:a.filter(e=>e.label.startsWith(n.split(`:`)[1]??``)),from:r+n.indexOf(`:`)+1}):/->\s*[\w/]*$/.test(i+n)?(Object.keys(I0).forEach(e=>o(e,e,`unit`)),{items:a.filter(e=>e.label.startsWith(n)),from:r}):((t===`segment`?[`elapsed`,`reps`,`resistance`,`distance`,`effort`,`effortLabel`,`segmentVolume`,`metMinutes`,`effortRpe`,`sessionRpe`]:[`sessionRpe`,`session.duration`,`profile.vo2max`]).forEach(e=>o(e,e,t===`segment`?`segment metric / context`:`context node`)),G0.forEach(e=>o(`${e}()`,`${e}()`,`function`)),[`sum:`,`avg:`,`max:`,`count:`,`last:`].forEach(e=>o(`${e}{}`,e,`WQL atom`)),i.includes(`=`)&&o(`estimated`,`estimated`,`variant origin`),[`when `,`-> `,`where `,`| `,` key `,`(library)`].forEach(e=>o(e.trim(),e,`clause`)),{items:a.filter(e=>e.label.startsWith(n)).slice(0,9),from:r})}var r2={background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:8,padding:12},i2={fontFamily:`ui-monospace, monospace`,fontSize:13};function a2({r:e}){let t=R0(e.dim??N0);return(0,H.jsxs)(`div`,{style:{marginTop:8,fontSize:12},children:[e.dim&&(0,H.jsxs)(`div`,{style:{color:`#a1a1aa`,marginBottom:4},children:[`computes `,(0,H.jsx)(`b`,{style:{color:`#e4e4e7`},children:F0(e.dim)}),t&&t.name!==`dimensionless`&&(0,H.jsxs)(H.Fragment,{children:[` → `,(0,H.jsx)(`span`,{style:{color:`#c084fc`},children:t.name}),` — units: `,t.units.map(t=>(0,H.jsx)(o2,{u:t,active:e.calc.unit===t},t))]})]}),e.diagnostics.map((e,t)=>(0,H.jsxs)(`div`,{style:{color:`#f87171`},children:[`⚠ `,e]},t)),!e.diagnostics.length&&(0,H.jsxs)(`div`,{style:{color:`#34d399`},children:[`✓ valid`,e.variantUsed===`estimated`?` — estimated variant in use`:``]})]})}var o2=({u:e,active:t})=>(0,H.jsx)(`span`,{style:{border:`1px solid ${t?`#c084fc`:`#52525b`}`,borderRadius:4,padding:`0 5px`,marginRight:4,color:t?`#c084fc`:`#a1a1aa`},children:e});function s2({r:e,scope:t,sessionRpe:n,vo2max:r}){return(0,H.jsxs)(`div`,{style:{...r2,minWidth:320},children:[(0,H.jsxs)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:6},children:[`LIVE PREVIEW — `,t===`store`?`last 7 of 28 days (fixture)`:`Fran, 2026-07-28 (fixture)${r?` · VO₂max ${r}`:` · VO₂max unknown`}${n?` · sRPE ${n}`:``}`]}),t===`segment`&&Y0.map((t,n)=>(0,H.jsxs)(`div`,{style:{...i2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[t.effort,t.reps?` ×${t.reps}`:``,t.resistanceKg?` ${t.resistanceKg}kg`:``]}),(0,H.jsx)(`span`,{style:{color:e.perSegment?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.perSegment?.[n]??`—`})]},n)),t===`workout`&&Y0.map((t,n)=>(0,H.jsxs)(`div`,{style:{...i2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[`after line `,n+1]}),(0,H.jsx)(`span`,{style:{color:e.running?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.running?.[n]??`—`})]},n)),t===`store`&&(e.perSegment??[]).map((e,t)=>(0,H.jsxs)(`div`,{style:{...i2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[`D-`,6-t]}),(0,H.jsx)(`span`,{style:{color:`#7dd3fc`},children:e??`—`})]},t))]})}function c2({scope:e,onSrc:t}){let[n,r]=(0,V.useState)(`power`),[i,a]=(0,V.useState)(`reps * resistance / convert(elapsed, s)`),[o,s]=(0,V.useState)(`kg/s`),[c,l]=(0,V.useState)(`has(reps) and has(resistance) and elapsed > 0`),[u,d]=(0,V.useState)(null),f=`${n} = ${i}${o?` -> ${o}`:``}${c?` when ${c}`:``}`,p=(0,V.useMemo)(()=>t2(f,e,void 0,void 0),[f,e]);(0,V.useEffect)(()=>t(f),[f]);let m=[{id:`name`,label:`name`,value:n,set:r,hint:`calc id`},{id:`expr`,label:`=`,value:i,set:a,hint:`expression — metrics, lookups, functions`},{id:`unit`,label:`->`,value:o,set:s,hint:`output unit (auto allowed)`},{id:`when`,label:`when`,value:c,set:l,hint:`applicability predicate`}];return(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{style:{display:`flex`,gap:6,flexWrap:`wrap`,alignItems:`center`},children:m.map(e=>(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4},children:[(0,H.jsx)(`span`,{style:{color:`#71717a`,fontSize:12},children:e.label}),(0,H.jsx)(`button`,{onClick:()=>d(u===e.id?null:e.id),style:{...i2,fontSize:12,background:u===e.id?`#3b0764`:`#27272a`,border:`1px solid ${u===e.id?`#c084fc`:`#3f3f46`}`,borderRadius:6,color:`#e4e4e7`,padding:`4px 10px`,cursor:`pointer`,maxWidth:340,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.value||(0,H.jsx)(`span`,{style:{color:`#52525b`},children:`∅`})})]},e.id))}),u&&(0,H.jsxs)(`div`,{style:{...r2,marginTop:8},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:4},children:m.find(e=>e.id===u)?.hint}),(0,H.jsx)(`input`,{autoFocus:!0,value:m.find(e=>e.id===u).value,onChange:e=>m.find(e=>e.id===u).set(e.target.value),style:{...i2,width:`100%`,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`4px 8px`,outline:`none`}}),(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:n2(m.find(e=>e.id===u).value,e).items.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>m.find(e=>e.id===u).set(e.insert),style:{...i2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e.label},t))})]}),(0,H.jsx)(`div`,{style:{...i2,marginTop:8,color:`#52525b`,fontSize:12},children:f}),(0,H.jsx)(a2,{r:p})]})}function l2({scope:e,onSrc:t}){let[n,r]=(0,V.useState)(`power`),[i,a]=(0,V.useState)([`reps`,`*`,`resistance`,`/`,`convert(elapsed, s)`]),o=[{group:`metrics`,items:e===`segment`?[`elapsed`,`reps`,`resistance`,`distance`]:[`sum:reps{}`,`sum:distance{}`,`sum:metMinutes{}`,`sum:elapsed{}`]},{group:`functions`,items:[`convert(·, min)`,`convert(·, km)`,`convert(·, s)`,`min(·, 100)`,`round(·)`]},{group:`lookups`,items:[`lookup("effort", effort, "met")`,`lookup("effort", effort, "disciplineFactor")`,`lookup("rpe-labels", effortLabel, "rpe")`]},{group:`operators`,items:[`+`,`-`,`*`,`/`,`(`,`)`]}],s=`${n} = ${i.join(` `)} -> auto`,c=(0,V.useMemo)(()=>t2(s,e,void 0,void 0),[s,e]);(0,V.useEffect)(()=>t(s),[s]);let l=R0(c.dim??N0);return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{style:{display:`flex`,gap:8,marginBottom:8,alignItems:`center`},children:[(0,H.jsx)(`span`,{style:{fontSize:12,color:`#71717a`},children:`name`}),(0,H.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),style:{...i2,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`3px 8px`}})]}),o.map(e=>(0,H.jsxs)(`div`,{style:{marginBottom:6},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:3},children:e.group}),(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`},children:e.items.map(e=>(0,H.jsx)(`button`,{onClick:()=>a(t=>[...t,e]),style:{...i2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e},e))})]},e.group)),(0,H.jsxs)(`div`,{style:{...r2,...i2,marginTop:8,color:`#d4d4d8`,minHeight:34},children:[i.map((e,t)=>(0,H.jsx)(`span`,{onClick:()=>a(e=>e.filter((e,n)=>n!==t)),title:`click to remove`,style:{cursor:`pointer`,background:`#27272a`,borderRadius:4,padding:`1px 6px`,marginRight:4,display:`inline-block`},children:e},t)),!i.length&&(0,H.jsx)(`span`,{style:{color:`#52525b`},children:`click palette items to build the formula…`})]}),(0,H.jsxs)(`div`,{style:{fontSize:12,color:`#71717a`,marginTop:6},children:[`unit: `,(0,H.jsx)(`b`,{style:{color:`#c084fc`},children:l?l.units.join(` / `):`—`}),` (derived)`]}),(0,H.jsx)(`div`,{style:{...i2,marginTop:6,color:`#52525b`,fontSize:12},children:s}),(0,H.jsx)(a2,{r:c})]})}var u2={segment:`power = reps * resistance / convert(elapsed, s) -> kg/s when has(reps) and has(resistance) and elapsed > 0`,workout:`sessionLoad = round(rpe * convert(session.duration, min)) -> AU where rpe = sessionRpe | max:effortRpe{} | 5 estimated`,store:`acwr = windowMean(daily, 7d) / windowMean(daily, 28d) -> ratio`};function d2(){let[e,t]=Ct(),n=e.get(`v`)??`text`,[r,i]=(0,V.useState)(`segment`),[a,o]=(0,V.useState)(void 0),[s,c]=(0,V.useState)(void 0),[l,u]=(0,V.useState)(u2.segment),[d,f]=(0,V.useState)(``),p=n===`text`?l:d||l,m=(0,V.useMemo)(()=>t2(p,r,a,s),[p,r,a,s]),h=[[`text`,`A · text + completion`],[`slots`,`B · token slots`],[`guided`,`C · guided builder`]];return(0,H.jsxs)(`div`,{style:{background:`#09090b`,minHeight:`100vh`,color:`#e4e4e7`,padding:24,fontFamily:`system-ui`},children:[(0,H.jsxs)(`div`,{style:{maxWidth:1100,margin:`0 auto`},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#f59e0b`,marginBottom:4},children:`PROTOTYPE — throwaway · issue #863`}),(0,H.jsx)(`h1`,{style:{fontSize:20,fontWeight:700,marginBottom:12},children:`Calc-line guided authoring`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:12,marginBottom:16,alignItems:`center`,fontSize:13},children:[[`segment`,`workout`,`store`].map(e=>(0,H.jsxs)(`button`,{onClick:()=>{i(e),u(u2[e])},style:{padding:`3px 12px`,borderRadius:6,border:`1px solid ${r===e?`#7dd3fc`:`#3f3f46`}`,background:`none`,color:r===e?`#7dd3fc`:`#a1a1aa`,cursor:`pointer`},children:[e,` scope`]},e)),(0,H.jsx)(`span`,{style:{color:`#3f3f46`},children:`|`}),(0,H.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:!!a,onChange:e=>o(e.target.checked?8:void 0)}),` sRPE captured`]}),(0,H.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:!!s,onChange:e=>c(e.target.checked?42:void 0)}),` VO₂max known`]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:16,alignItems:`flex-start`},children:[(0,H.jsxs)(`div`,{style:{flex:1},children:[n===`text`&&(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),style:{...r2,...i2,width:`100%`,color:`#e4e4e7`,outline:`none`},placeholder:`name = expression -> unit when predicate`}),(0,H.jsx)(f2,{src:l,scope:r,onApply:e=>u(e)}),(0,H.jsx)(a2,{r:m})]}),n===`slots`&&(0,H.jsx)(c2,{scope:r,onSrc:f}),n===`guided`&&(0,H.jsx)(l2,{scope:r,onSrc:f})]}),(0,H.jsx)(s2,{r:m,scope:r,sessionRpe:a,vo2max:s})]})]}),(0,H.jsx)(`div`,{style:{position:`fixed`,bottom:16,left:`50%`,transform:`translateX(-50%)`,display:`flex`,gap:6,background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:10,padding:6},children:h.map(([e,r])=>(0,H.jsx)(`button`,{onClick:()=>t({v:e}),style:{padding:`4px 14px`,borderRadius:7,border:`none`,background:n===e?`#7dd3fc`:`transparent`,color:n===e?`#09090b`:`#a1a1aa`,cursor:`pointer`,fontSize:13},children:r},e))})]})}function f2({src:e,scope:t,onApply:n}){let r=(0,V.useMemo)(()=>n2(e,t),[e,t]);return r.items.length?(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:r.items.map((t,i)=>(0,H.jsxs)(`button`,{onClick:()=>n(e.slice(0,r.from)+t.insert),style:{...i2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:[t.label,` `,(0,H.jsx)(`span`,{style:{color:`#52525b`},children:t.detail})]},i))}):null}var p2=`01a09d45-885a-738d-ab1e-be31d44fe919`,m2=`:session{result:${p2}}`,h2=`## Morning session
190
+ Thrusters`,docsPath:n?.docsPath??`/guide/structure?h=rep-schemes`}]},[a]),l=(0,V.useMemo)(()=>t===`dark`||t!==`light`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches,[t]),u=jP(),d=(0,V.useCallback)(async()=>{let t=await UR.getState().open({wql:{initialQuery:Fz(),execute:Lz,preferredChoices:Iz()},sources:[Mz(),Pz(dz(u))]});t.dismissed||Rz(t.item,e)},[e,u]),f=(0,V.useCallback)(e=>{if(e===`scroll-to-workout`){r.current?.scrollIntoView({behavior:`smooth`,block:`start`});return}e===`open-search`&&d()},[d]),p=(0,V.useCallback)(async t=>{let n=await hH([`# Playground Widget Example`,``,"```time",t,"```",``,`[▶ Run Workout]{.button action=start-workout}`,``].join(`
191
+ `));e(WA(n))},[e]),m=(0,V.useCallback)(t=>{if(/^https?:\/\//i.test(t)){window.open(t,`_blank`,`noopener,noreferrer`);return}e(t)},[e]);return(0,H.jsxs)(C0,{actionsSlot:(0,H.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,H.jsx)(et,{className:`size-4 text-zinc-500`,"aria-hidden":`true`}),(0,H.jsx)(E1,{checked:l,onChange:e=>n(e?`dark`:`light`),"aria-label":`Toggle dark mode`}),(0,H.jsx)(ir,{className:`size-4 text-zinc-500`,"aria-hidden":`true`})]}),heroSlot:(0,H.jsx)(WQ,{config:w0,onAction:f}),children:[(0,H.jsxs)(`section`,{ref:r,id:`workout-widget-surface`,className:`mt-8 grid grid-cols-1 gap-4 xl:grid-cols-3`,children:[(0,H.jsx)(`div`,{className:`xl:col-span-2`,children:(0,H.jsx)(GQ,{config:s,isDarkMode:l,onRun:p})}),(0,H.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,H.jsx)(KQ,{config:e,onOpenDocs:m},e.title))})]}),(0,H.jsx)(cX,{})]})}function E0({activeIndex:e,onCommand:t,captions:n}){return(0,H.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`tour-captions`,children:n.map((n,r)=>(0,H.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,H.jsx)(D0,{cap:n,onCommand:t})},n.id))})}function D0({cap:e,onCommand:t}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`h3`,{className:`mb-3.5 xl:mb-5 text-[clamp(22px,2vw,32px)] font-extrabold leading-[1.12] tracking-[-0.03em]`,children:[(0,H.jsx)(`span`,{className:`mr-2 align-[0.2em] font-mono text-[0.5em] font-semibold tracking-[0.08em] text-muted-foreground/50`,children:e.num}),e.title]}),(0,H.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,H.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,H.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,H.jsx)(`span`,{children:e})]},t))}),e.foot&&(0,H.jsx)(`div`,{className:`mt-4 xl:mt-6 border-t border-border pt-3 xl:pt-4 font-mono text-[10px] xl:text-[11px] tracking-[0.06em] text-muted-foreground/60`,children:e.foot}),e.extra&&(0,H.jsx)(`div`,{className:`mt-3`,children:e.extra}),e.commands&&e.commands.length>0&&t&&(0,H.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,H.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,H.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,H.jsx)(Wn,{to:e.href,onClick:()=>oH.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 O0({visible:e,children:t}){return(0,H.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 k0=(0,V.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,V.useRef)(null),f=(0,V.useRef)(null),[p,m]=(0,V.useState)(null),h=(0,V.useCallback)(e=>{f.current=e,m(e)},[]),{slice:g,subscribe:_,resync:v,runwayReached:y}=UK(d,!1,r,e),b=j0(d);(0,V.useEffect)(()=>{o?.(b)},[b,o]),(0,V.useEffect)(()=>{s?.(y)},[y,s]);let[x,S]=(0,V.useState)(!1),C=A0(d);(0,V.useEffect)(()=>{(C||y)&&S(!0)},[C,y]);let w=g.stage?.screen??`editor`,T=(0,V.useRef)(null);return(0,V.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,V.useImperativeHandle)(u,()=>({scrollToStage:e=>{let t=d.current,n=r.find(t=>t.id===e);!t||!n||HK(t,Math.min(n.range[0]+.02,n.range[1]-.005))},subscribe:_,resync:v}),[r,_,v]),(0,H.jsxs)(`section`,{id:`tour-section-${e}`,"data-testid":`tour-section-${e}`,children:[n,(0,H.jsx)(BK,{trackRef:d,height:t,stages:r,activeIndex:g.index,segmentId:e,testId:`tour-runway`,pane:(0,H.jsx)(`div`,{ref:h,className:`absolute inset-0 flex flex-col justify-center`,children:(0,H.jsxs)(VY,{children:[(0,H.jsx)(WY,{ringKey:`editor.window`,el:p}),(0,H.jsx)(PH,{title:JY[w],className:`relative h-full max-h-[760px]`,children:(0,H.jsx)(zK,{gateId:`${e}-pane`,segmentId:e,className:`relative h-full`,children:l&&(0,H.jsx)(O0,{visible:w===`editor`,children:(0,H.jsx)(lX,{doc:l.doc,onDocChange:l.onDocChange,onBlocksChange:l.onBlocksChange,onRun:l.onRun,theme:l.theme,withRingTargets:!0})})})}),(0,H.jsx)(GY,{target:g.ring?.key?{key:g.ring.key}:null,accent:g.stage.accent??qY.editor,canvasRef:f})]})}),captions:(0,H.jsx)(E0,{activeIndex:g.index,captions:i,onCommand:c})})]})});function A0(e){let[t,n]=(0,V.useState)(!1);return(0,V.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 j0(e){let[t,n]=(0,V.useState)(()=>typeof IntersectionObserver>`u`);return(0,V.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 M0={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`},N0={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`]}},P0=[{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 F0({chapters:e=[],allQuests:t=[],theme:n,wodFiles:r={},onRun:i}){let a=(0,V.useMemo)(()=>{let t=(e??[]).filter(e=>e.id!==`home-tour`);return t.length>0?t:P0},[e]),o=jH(`(prefers-reduced-motion: reduce)`),{markComplete:s}=OH(`/`,t),{chapters:c}=VX(a),[l,u]=(0,V.useState)(()=>a[0]?.id??`basics`),[d,f]=(0,V.useState)(``),p=(0,V.useRef)([]),m=(0,V.useRef)(l);m.current=l;let h=(0,V.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,BL(M0[e.id]??``,r)])),[a,r]);(0,V.useEffect)(()=>{p.current=[],f(h[l]??``)},[l,h]);let g=(0,V.useCallback)(e=>{p.current=e},[]),_=(0,V.useCallback)(()=>{let e=m.current;s(`${e}-run`),i?.(e,p.current[0]??null,d)},[d,s,i]),v=(0,V.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,V.useMemo)(()=>Object.fromEntries(c.map(e=>[e.chapter.id,e])),[c]),b=(0,V.useMemo)(()=>a.map((e,t)=>{let n=N0[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,H.jsx)(`span`,{"data-testid":`chapter-picker-progress-${e.id}`,className:U(`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:YY[e.id]??`/guide/start`,event:sH.chapterGuideClicked,data:{chapter:e.id},testId:`chapter-picker-guide-${e.id}`}]}}),[a,y]);return(0,H.jsxs)(`section`,{id:`tour-chapter-picker`,"data-testid":`tour-chapter-picker`,className:`flex flex-col`,children:[(0,H.jsx)(eX,{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,H.jsx)(I0,{chapters:a,selectedId:l,onSelect:u,doc:d,onDocChange:f,theme:n,onBlocksChange:g,onRun:_,progressByChapter:y}):(0,H.jsx)(k0,{id:`learn`,heightVh:`600vh`,stages:v,captions:b,onActiveStageChange:u,editor:{doc:d,theme:n,onDocChange:f,onBlocksChange:g,onRun:_}})]})}function I0({chapters:e,selectedId:t,onSelect:n,doc:r,onDocChange:i,theme:a,onBlocksChange:o,onRun:s,progressByChapter:c}){return(0,H.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,H.jsxs)(`div`,{className:`flex flex-col gap-10 lg:flex-row lg:items-start lg:gap-12 xl:gap-16`,children:[(0,H.jsx)(`div`,{className:`w-full lg:w-[58%] xl:w-[60%] lg:sticky lg:top-[110px] z-10 flex-none`,children:(0,H.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,H.jsx)(PH,{title:YY[t]?.split(`/`).pop()??`example.md`,subtitle:`Lesson: ${e.find(e=>e.id===t)?.title??t}`,className:`h-full`,children:(0,H.jsx)(lX,{doc:r,onDocChange:i,onBlocksChange:o,onRun:s,theme:a,withRingTargets:!1})})})}),(0,H.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=Lq(e.badge),o=e.id===t,s=N0[e.id];return(0,H.jsxs)(`div`,{"data-testid":`chapter-picker-row-${e.id}`,className:U(`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,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsxs)(`span`,{className:`font-mono text-xs font-bold uppercase tracking-wider text-primary`,children:[`Chapter 0`,r+1]}),a&&(0,H.jsx)(a,{className:`size-4 text-primary`})]}),(0,H.jsx)(`span`,{className:U(`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,H.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground sm:text-3xl`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-3 text-sm sm:text-base leading-relaxed text-muted-foreground`,children:s?.summary??e.title}),s?.bullets&&(0,H.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,H.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,H.jsx)(`span`,{children:e})]},t))})]}),(0,H.jsxs)(`div`,{className:`mt-6 flex flex-wrap items-center gap-3 pt-4 border-t border-border/50`,children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>n(e.id),"data-testid":`chapter-picker-select-${e.id}`,"aria-pressed":o,className:U(`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,H.jsx)(Ht,{className:`size-3.5 fill-current`}),(0,H.jsx)(`span`,{children:o?`Loaded in editor`:`Load example`})]}),(0,H.jsxs)(Wn,{to:YY[e.id]??`/guide/start`,"data-testid":`chapter-picker-guide-${e.id}`,"aria-label":`Read guide for ${e.title}`,onClick:()=>oH.record(sH.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,H.jsx)(Ie,{className:`size-3.5`}),(0,H.jsx)(`span`,{children:`Read guide →`})]})]})]},e.id)})})]})})}function L0({chapters:e}){let t=()=>oH.record(sH.lessonStarted),n=()=>oH.record(sH.cheatsheetOpened),{chapters:r}=VX(e),i=r.filter(e=>e.chapter.id!==`home-tour`);return(0,H.jsxs)(`section`,{"data-testid":`tour-learn`,className:`mx-auto max-w-5xl px-6 py-16 border-b border-border/60`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-bold tracking-tight`,children:`Learn the Language`}),(0,H.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,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsx)(Wn,{to:`/guide/start`,onClick:t,className:`inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90`,children:`Start Lesson 1`}),(0,H.jsx)(Wn,{to:`/guide/start?h=reference`,onClick:n,className:`text-sm font-semibold text-primary underline-offset-2 hover:underline`,children:`Cheat sheet →`})]})]}),(0,H.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=YY[e.id]??`/guide/start`,a=Lq(e.badge);return(0,H.jsxs)(Wn,{to:i,"data-testid":`learn-progress-chip-${e.id}`,className:U(`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,H.jsx)(a,{className:`size-3.5 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`text-[12px] font-semibold text-foreground`,children:e.title}),(0,H.jsx)(`span`,{className:U(`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 R0=L0;function z0(){let e=sD()??vR,{theme:t}=ji(),[n,r]=(0,V.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches);(0,V.useEffect)(()=>{if(t!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=e=>r(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[t]);let i=(0,V.useMemo)(()=>t===`system`?n?`vs-dark`:`vs`:t===`dark`?`vs-dark`:`vs`,[t,n]),a=MP(`/`),o=jP(),s=a?.chapters??[],c=a?.quests??[],l=(0,V.useMemo)(()=>{let e={};for(let{page:t}of o)for(let n of t.quests)e[n.id]=n.label;return e},[o]),u=cH()?.track,{start:d,finalize:f,end:p}=vH(),[m,h]=(0,V.useState)(null),[g,_]=(0,V.useState)(0),[v,y]=(0,V.useState)(!1),b=(0,V.useCallback)(()=>{h(null),y(!1)},[]),x=(0,V.useCallback)(async(e,t,n)=>{if(t){u?.(sH.chapterExampleRun,{chapter:e}),h(t),_(e=>e+1),y(!0);try{await d(n,t,{pageTitle:`Syntax`,sectionTitle:`Chapter ${e}`})}catch(e){console.error(`[SyntaxView] failed to persist playground run note:`,e),b(),Z({title:`Could not start workout`,variant:`destructive`})}}},[b,d,u]),S=(0,V.useCallback)(async(e,t)=>{try{(t.logs??[]).length===0?await p():await f(t,t.completed)}catch(e){console.error(`[SyntaxView] failed to save session:`,e),Z({title:`Session not saved`,variant:`destructive`})}finally{b()}},[b,p,f]);return(0,H.jsx)(VY,{children:(0,H.jsxs)(`div`,{"data-testid":`syntax-view`,children:[(0,H.jsx)(eX,{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,H.jsx)(F0,{wodFiles:e,chapters:s,allQuests:c,theme:i,onRun:x}),(0,H.jsx)(R0,{quests:c,chapters:s,questLabels:l}),(0,H.jsx)(Gq,{}),(0,H.jsx)(QY,{}),m&&v&&(0,H.jsx)(ZG,{block:m,autoStart:!0,onClose:b,onCompleteWorkout:S},g)]})})}function B0(){let e=Sn();return(0,H.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,H.jsx)(Ve,{className:`w-8 h-8 text-muted-foreground`})}),(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Page not found`}),(0,H.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`The page you are looking for does not exist or has been moved.`})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>e(`/`),className:`inline-flex items-center gap-2 px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors`,children:[(0,H.jsx)(T,{className:`w-4 h-4`}),`Go home`]})]})}var $=(e=0,t=0,n=0,r=0,i=0)=>[e,t,n,r,i],V0=(e,t)=>e.map((e,n)=>e+t[n]),H0=(e,t)=>e.map((e,n)=>e-t[n]),U0=(e,t)=>e.every((e,n)=>e===t[n]),W0=$(),G0=[`length`,`mass`,`time`,`count`,`energy`];function K0(e){if(U0(e,W0))return`dimensionless`;let t=[];return e.forEach((e,n)=>{e!==0&&t.push(`${G0[n]}${e===1?``:`^`+e}`)}),t.join(` · `)}var q0={m:{dim:$(1),toBase:1},km:{dim:$(1),toBase:1e3},mi:{dim:$(1),toBase:1609.34},kg:{dim:$(0,1),toBase:1},lb:{dim:$(0,1),toBase:.4536},ms:{dim:$(0,0,1),toBase:.001},s:{dim:$(0,0,1),toBase:1},min:{dim:$(0,0,1),toBase:60},h:{dim:$(0,0,1),toBase:3600},reps:{dim:$(0,0,0,1),toBase:1},cal:{dim:$(0,0,0,0,1),toBase:1},MET:{dim:W0,toBase:1},pts:{dim:W0,toBase:1},AU:{dim:W0,toBase:1},ratio:{dim:W0,toBase:1},"MET-min":{dim:$(0,0,1),toBase:60},"reps/min":{dim:H0($(0,0,0,1),$(0,0,1)),toBase:1/60},"m/s":{dim:H0($(1),$(0,0,1)),toBase:1},"min/km":{dim:H0($(0,0,1),$(1)),toBase:60/1e3},"sec/km":{dim:H0($(0,0,1),$(1)),toBase:1/1e3},"min/mi":{dim:H0($(0,0,1),$(1)),toBase:60/1609.34},"km/h":{dim:H0($(1),$(0,0,1)),toBase:1e3/3600},"kg/s":{dim:H0(V0($(0,1),$(0,0,0,1)),$(0,0,1)),toBase:1},"lb/s":{dim:H0(V0($(0,1),$(0,0,0,1)),$(0,0,1)),toBase:.4536}},J0=[{dim:H0($(0,0,1),$(1)),name:`pace`,units:[`min/km`,`sec/km`,`min/mi`]},{dim:H0($(1),$(0,0,1)),name:`speed`,units:[`m/s`,`km/h`]},{dim:V0($(0,1),$(0,0,0,1)),name:`volume`,units:[`kg`,`lb`]},{dim:H0(V0($(0,1),$(0,0,0,1)),$(0,0,1)),name:`power`,units:[`kg/s`,`lb/s`]},{dim:$(0,0,1),name:`time`,units:[`min`,`s`,`MET-min`]},{dim:$(0,0,0,1),name:`count`,units:[`reps`]},{dim:$(1),name:`length`,units:[`m`,`km`,`mi`]},{dim:$(0,1),name:`mass`,units:[`kg`,`lb`]},{dim:W0,name:`dimensionless`,units:[`pts`,`AU`,`MET`]}],Y0=e=>J0.find(t=>U0(t.dim,e)),X0=(e,t=W0)=>({v:e,dim:t}),Z0={thruster:{met:6,discipline:`strength`,disciplineFactor:1.2,intensityTier:`high`,resolvedFrom:`bundled`},"pull-up":{met:5,discipline:`gymnastics`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`},run:{met:9.8,discipline:`running`,disciplineFactor:1,intensityTier:`high`,resolvedFrom:`bundled`},squat:{met:5,discipline:`strength`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`}},Q0={met:$(0,0,0,0,0),disciplineFactor:W0},$0={easy:3,moderate:5,hard:7,"all-out":10,max:10},e2={effort:{fields:[`met`,`discipline`,`disciplineFactor`,`intensityTier`,`resolvedFrom`],get:(e,t)=>{let n=Z0[e];if(!n)return t===`resolvedFrom`?X0(NaN):void 0;let r=n[t];return typeof r==`number`?{v:r,dim:Q0[t]??W0}:void 0}},"rpe-labels":{fields:[`rpe`],get:e=>$0[e]===void 0?void 0:X0($0[e])}},t2={min:e=>X0(Math.min(...e.map(e=>e.v)),e[0]?.dim??W0),max:e=>X0(Math.max(...e.map(e=>e.v)),e[0]?.dim??W0),abs:e=>X0(Math.abs(e[0].v),e[0].dim),round:e=>X0(e.length>1?+e[0].v.toFixed(e[1].v):Math.round(e[0].v),e[0].dim),floor:e=>X0(Math.floor(e[0].v),e[0].dim),ceil:e=>X0(Math.ceil(e[0].v),e[0].dim),clamp:e=>X0(Math.min(Math.max(e[0].v,e[1].v),e[2].v),e[0].dim),convert:e=>{let t=e[1].unit??``,n=q0[t];if(!n||!U0(n.dim,e[0].dim))throw Error(`convert: ${t} dimension ≠ value dimension`);return{v:e[0].v/n.toBase,dim:e[0].dim}}},n2=Object.keys(t2).concat([`has`,`lookup`]);function r2(e){let t=[],n=/\s*("(?:[^"]*)"|\d+\.?\d*|[a-zA-Z_][\w.-]*(?::[\w.:*!|,-]+(?:\{[^}]*\})?(?:\s+by\s+\{[^}]*\})?)?|[-+*/(),<>!=]=?|>=|<=|==)/y,r,i=0;for(;i<e.length;){if(n.lastIndex=i,r=n.exec(e),!r||r.index!==i){/\S/.test(e[i])&&t.push({t:`err`,s:e[i]}),i+=1;continue}i=n.lastIndex;let a=r[1];/^".*"$/.test(a)?t.push({t:`str`,s:a.slice(1,-1)}):/^\d/.test(a)?t.push({t:`num`,s:a}):/^[-+*/(),]$/.test(a)||[`>=`,`<=`,`==`,`!=`,`>`,`<`,`=`].includes(a)?t.push({t:`op`,s:a}):t.push({t:`id`,s:a})}return t}function i2(e){let t=0,n=()=>e[t];function r(i){let a,o=e[t++];if(!o)throw Error(`unexpected end`);if(o.t===`num`)a={k:`num`,v:parseFloat(o.s)};else if(o.t===`str`)a={k:`str`,s:o.s};else if(o.s===`-`)a={k:`neg`,e:r(70)};else if(o.s===`(`){if(a=r(0),n()?.s!==`)`)throw Error(`missing )`);t++}else if(o.t===`id`){if(n()?.s===`(`){t++;let e=[];if(n()?.s!==`)`)for(;;){if(e.push(r(0)),n()?.s===`,`){t++;continue}break}if(n()?.s!==`)`)throw Error(`missing )`);t++,a={k:`call`,f:o.s,args:e}}else a={k:`id`,s:o.s}}else throw Error(`unexpected "${o.s}"`);for(;;){let e=n()?.s,o=e===`*`||e===`/`?60:e===`+`||e===`-`?50:[`<`,`<=`,`>`,`>=`,`==`,`!=`].includes(e)?40:e===`and`?30:e===`or`?20:0;if(!o||o<i)break;t++;let s=r(o+1);a={k:`bin`,op:e,l:a,r:s}}return a}let i=r(0);if(t<e.length)throw Error(`trailing "${e[t].s}"`);return i}function a2(e,t,n){switch(e.k){case`num`:return X0(e.v);case`str`:return{v:NaN,dim:W0,unit:e.s};case`neg`:{let r=a2(e.e,t,n);return X0(-r.v,r.dim)}case`id`:{if(/^(sum|avg|max|min|count|last):/.test(e.s)){let t=n(e.s);if(!t)throw Error(`no data for ${e.s}`);return t}let r=t[e.s];if(r===void 0)throw Error(`unknown or absent: ${e.s}`);return r}case`bin`:{if(e.op===`and`)return X0(a2(e.l,t,n).v&&a2(e.r,t,n).v?1:0);if(e.op===`or`)return X0(a2(e.l,t,n).v||a2(e.r,t,n).v?1:0);let r=a2(e.l,t,n),i=a2(e.r,t,n);switch(e.op){case`+`:if(!U0(r.dim,i.dim))throw Error(`+ : ${K0(r.dim)} vs ${K0(i.dim)}`);return X0(r.v+i.v,r.dim);case`-`:if(!U0(r.dim,i.dim))throw Error(`- : ${K0(r.dim)} vs ${K0(i.dim)}`);return X0(r.v-i.v,r.dim);case`*`:return X0(r.v*i.v,V0(r.dim,i.dim));case`/`:return X0(r.v/i.v,H0(r.dim,i.dim));case`<`:return X0(+(r.v<i.v));case`<=`:return X0(+(r.v<=i.v));case`>`:return X0(+(r.v>i.v));case`>=`:return X0(+(r.v>=i.v));case`==`:return X0(+(r.v===i.v));case`!=`:return X0(r.v===i.v?0:1)}throw Error(e.op)}case`call`:{if(e.f===`has`){let r=e.args[0];return r.k===`id`?X0(t[r.s]!==void 0||/^(sum|avg|max|min|count|last):/.test(r.s)&&n(r.s)!==void 0?1:0):X0(0)}if(e.f===`lookup`){let[n,r,i]=e.args,a=n.k===`str`?n.s:``,o=r.k===`str`?r.s:r.k===`id`?String(t[r.s]?.v??r.s):``,s=i.k===`str`?i.s:``,c=e2[a];if(!c)throw Error(`unknown table "${a}"`);if(!c.fields.includes(s))throw Error(`table "${a}" has no field "${s}"`);if(a===`effort`&&s===`resolvedFrom`)return X0(+!!Z0[o]);let l=c.get(o,s);if(!l)throw Error(`lookup miss: ${a}/${o}/${s}`);return l}let r=t2[e.f];if(!r)throw Error(`unknown function ${e.f}`);return r(e.args.map((r,i)=>e.f===`convert`&&i>0&&r.k===`id`?{v:NaN,dim:W0,unit:r.s}:a2(r,t,n)))}}}var o2=[{effort:`thruster`,label:`hard`,reps:21,resistanceKg:43,elapsedMs:95e3},{effort:`pull-up`,reps:21,elapsedMs:6e4},{effort:`thruster`,reps:15,resistanceKg:43,elapsedMs:7e4},{effort:`pull-up`,reps:15,elapsedMs:5e4},{effort:`sled-push`,reps:9,resistanceKg:43,elapsedMs:45e3},{effort:`pull-up`,reps:9,elapsedMs:3e4}],s2=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function c2(e){let t=Z0[e.effort]?.met??4,n=!Z0[e.effort];return{segmentVolume:e.reps&&e.resistanceKg?X0(e.reps*e.resistanceKg,V0($(0,1),$(0,0,0,1))):void 0,metMinutes:X0(t*(e.elapsedMs/6e4),$(0,0,1)),metMinutesEstimated:n?X0(1):void 0,effortRpe:e.label?X0($0[e.label]??0):void 0}}function l2(e){let t={name:``,exprSrc:``,alternates:[],library:!1,bindings:[]};try{let n=e.trim(),r=/\s+when\s+/.exec(n);r&&(t.whenSrc=n.slice(r.index+r[0].length).trim(),n=n.slice(0,r.index));let i=/\s+where\s+/.exec(n);if(i){let e=n.slice(i.index+i[0].length).trim();n=n.slice(0,i.index);for(let n of e.split(/,\s*(?=[a-zA-Z_][\w]*\s*=)/)){let e=n.indexOf(`=`);e>0&&t.bindings.push({name:n.slice(0,e).trim(),src:n.slice(e+1).trim()})}}let a=/\s*->\s*/.exec(n);a&&(t.unit=n.slice(a.index+a[0].length).trim().replace(/\s+(key|grouped).*$/,``),n=n.slice(0,a.index)),/\(library\)/.test(n)&&(t.library=!0,n=n.replace(`(library)`,``));let o=n.indexOf(`=`);if(o<0)throw Error(`expected name = expression`);t.name=n.slice(0,o).trim();let s=n.slice(o+1).trim().split(`|`).map(e=>e.trim());return t.exprSrc=s[0],t.alternates=s.slice(1).map(e=>({src:e.replace(/\s*estimated\s*$/,``),estimated:/\bestimated\b/.test(e)})),t}catch(e){return t.error=e instanceof Error?e.message:String(e),t}}function u2(e,t,n,r){let i=c2(e);return{elapsed:X0(e.elapsedMs/1e3,$(0,0,1)),reps:e.reps===void 0?void 0:X0(e.reps,$(0,0,0,1)),resistance:e.resistanceKg===void 0?void 0:X0(e.resistanceKg,$(0,1)),distance:e.distanceM===void 0?void 0:X0(e.distanceM,$(1)),effort:X0(NaN),effortLabel:e.label?X0(NaN):void 0,segmentVolume:i.segmentVolume,metMinutes:i.metMinutes,effortRpe:i.effortRpe,sessionRpe:n===void 0?void 0:X0(n),"profile.vo2max":r===void 0?void 0:X0(r),...t}}var d2=e=>e.effort;function f2(e,t,n,r){let i=l2(e),a=[];if(i.error)return{calc:i,diagnostics:[i.error]};let o={calc:i,diagnostics:a},s=e=>e instanceof Error?e.message:String(e);if(t!==`store`){try{i2(r2(i.exprSrc))}catch(e){a.push(`expression: ${s(e)}`)}for(let e of i.bindings)for(let t of e.src.split(`|`))try{i2(r2(t.replace(/\s*estimated\s*$/,``)))}catch(t){a.push(`${e.name}: ${s(t)}`)}if(i.whenSrc)try{i2(r2(i.whenSrc))}catch(e){a.push(`when: ${s(e)}`)}}let c=o2,l=(e,t=c.length)=>{let i=/^(sum|avg|max|min|count|last):([\w.]+)/.exec(e);if(!i)return;let[,a,o]=i,s=c.slice(0,t),l=[];for(let e of s){let t=u2(e,{},n,r)[o];t!==void 0&&!Number.isNaN(t.v)&&l.push(t)}if(o===`sessionLoad`&&e.includes(`by {day}`))return X0(NaN);if(!l.length)return;let u=l[0].dim,d=l.map(e=>e.v);if(a===`sum`)return X0(d.reduce((e,t)=>e+t,0),u);if(a===`avg`)return X0(d.reduce((e,t)=>e+t,0)/d.length,u);if(a===`max`)return X0(Math.max(...d),u);if(a===`min`)return X0(Math.min(...d),u);if(a===`count`)return X0(d.length,$(0,0,0,1));if(a===`last`)return l[l.length-1]},u=(e,t,n)=>{let r={...t};for(let e of i.bindings){let t=e.src.split(`|`).map(e=>e.replace(/\s*estimated\s*$/,``).trim()),i;for(let e of t)try{i=d(e,r,n);break}catch{}if(i===void 0)throw Error(`${e.name}: no applicable variant`);r[e.name]=i}return d(e,r,n)},d=(e,t,n)=>a2(i2(r2(e)),t,e=>l(e,n));try{if(t===`segment`){let e=[],t;c.forEach((a,o)=>{try{let s=u2(a,{},n,r);if(s.effort=void 0,i.whenSrc&&!d(i.whenSrc,s,o+1).v){e.push(null);return}let c=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${d2(a)}",`).replace(/lookup\("rpe-labels",\s*effortLabel\s*,/g,`lookup("rpe-labels", "${a.label??``}",`),l=u(c,s,o+1);t||=l.dim;let f=i.unit&&i.unit!==`auto`?` ${i.unit}`:t?` [${K0(l.dim)}]`:``;e.push(`${Math.round(l.v*100)/100}${f}`)}catch(t){e.push(`∅ ${s(t)}`)}}),o.perSegment=e,o.dim=t}else if(t===`workout`){let e=[],t;for(let a=1;a<=c.length;a++)try{let s=c[a-1],l=u2(s,{"session.duration":X0(c.slice(0,a).reduce((e,t)=>e+t.elapsedMs,0)/1e3,$(0,0,1))},n,r);if(i.whenSrc&&!d(i.whenSrc,l,a).v){e.push(null);continue}let f=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${d2(s)}",`),p,m=`primary`;try{p=u(f,l,a)}catch(e){for(let e of i.alternates)try{p=u(e.src,l,a),m=e.estimated?`estimated`:`alternate`;break}catch{}if(p===void 0)throw e}t=p.dim,e.push(`${Math.round(p.v*100)/100}${i.unit&&i.unit!==`auto`?` `+i.unit:``}${m===`estimated`?` (est.)`:``}`),o.variantUsed=m}catch(t){e.push(`∅ ${s(t)}`)}o.running=e,o.dim=t}else{let e=s2,t=(e,t,n)=>e.map((r,i)=>i+1>=t?n(e.slice(i+1-t,i+1)):NaN),n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=e=>{let t=n(e);return Math.sqrt(n(e.map(e=>(e-t)**2)))},a=i.name,s=[];if(a.includes(`acwr`)){let r=t(e,7,n),i=t(e,28,n);s=e.map((e,t)=>r[t]/i[t])}else if(a.includes(`monotony`)){let i=t(e,7,n),a=t(e,7,r);s=e.map((e,t)=>i[t]/a[t])}else if(a.includes(`strain`)){let i=t(e,7,n),a=t(e,7,r),o=t(e,7,e=>e.reduce((e,t)=>e+t,0));s=e.map((e,t)=>i[t]/a[t]*o[t])}else s=t(e,7,n);o.perSegment=s.slice(-7).map(e=>Number.isNaN(e)?null:String(Math.round(e*100)/100)),o.dim=W0}}catch(e){a.push(s(e))}if(o.dim&&i.unit&&i.unit!==`auto`){let e=q0[i.unit];e?!U0(e.dim,o.dim)&&!U0(e.dim,W0)&&a.push(`unit "${i.unit}" is ${K0(e.dim)} but expression computes ${K0(o.dim)}`):a.push(`unknown unit "${i.unit}"`)}return o}function p2(e,t){let n=/([a-zA-Z_][\w.:-]*|"[\w-]*|)$/.exec(e)[1],r=e.length-n.length,i=e.slice(0,r),a=[],o=(e,t,n)=>a.push({label:e,insert:t,detail:n}),s=/lookup\("([\w-]*)",?\s*("[\w-]*",?\s*)?"?([\w-]*)$/.exec(e);if(s){if(s[2]===void 0&&!e.endsWith(`"`))e2&&Object.keys(e2).forEach(e=>o(e,`"${e}"`,`lookup table`));else{let t=s[1];(e.split(`"`).length<=5&&s[3]!==void 0||/,\s*"[\w-]*$/.test(e))&&(e2[t]?.fields??[]).forEach(e=>o(e,`"${e}"`,`${t} field`)),t===`effort`&&/,\s*$/.test(e)&&Object.keys(Z0).concat([`effort`]).forEach(e=>o(e,e===`effort`?`effort`:`"${e}"`,`key`))}return{items:a.filter(e=>e.label.startsWith(n.replace(/"/g,``))),from:r}}return/^(sum|avg|max|min|count|last):[\w.]*$/.test(n)?((t===`segment`?[]:[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`,`sessionLoad`]).forEach(e=>o(e,e,`metric key`)),{items:a.filter(e=>e.label.startsWith(n.split(`:`)[1]??``)),from:r+n.indexOf(`:`)+1}):/->\s*[\w/]*$/.test(i+n)?(Object.keys(q0).forEach(e=>o(e,e,`unit`)),{items:a.filter(e=>e.label.startsWith(n)),from:r}):((t===`segment`?[`elapsed`,`reps`,`resistance`,`distance`,`effort`,`effortLabel`,`segmentVolume`,`metMinutes`,`effortRpe`,`sessionRpe`]:[`sessionRpe`,`session.duration`,`profile.vo2max`]).forEach(e=>o(e,e,t===`segment`?`segment metric / context`:`context node`)),n2.forEach(e=>o(`${e}()`,`${e}()`,`function`)),[`sum:`,`avg:`,`max:`,`count:`,`last:`].forEach(e=>o(`${e}{}`,e,`WQL atom`)),i.includes(`=`)&&o(`estimated`,`estimated`,`variant origin`),[`when `,`-> `,`where `,`| `,` key `,`(library)`].forEach(e=>o(e.trim(),e,`clause`)),{items:a.filter(e=>e.label.startsWith(n)).slice(0,9),from:r})}var m2={background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:8,padding:12},h2={fontFamily:`ui-monospace, monospace`,fontSize:13};function g2({r:e}){let t=Y0(e.dim??W0);return(0,H.jsxs)(`div`,{style:{marginTop:8,fontSize:12},children:[e.dim&&(0,H.jsxs)(`div`,{style:{color:`#a1a1aa`,marginBottom:4},children:[`computes `,(0,H.jsx)(`b`,{style:{color:`#e4e4e7`},children:K0(e.dim)}),t&&t.name!==`dimensionless`&&(0,H.jsxs)(H.Fragment,{children:[` → `,(0,H.jsx)(`span`,{style:{color:`#c084fc`},children:t.name}),` — units: `,t.units.map(t=>(0,H.jsx)(_2,{u:t,active:e.calc.unit===t},t))]})]}),e.diagnostics.map((e,t)=>(0,H.jsxs)(`div`,{style:{color:`#f87171`},children:[`⚠ `,e]},t)),!e.diagnostics.length&&(0,H.jsxs)(`div`,{style:{color:`#34d399`},children:[`✓ valid`,e.variantUsed===`estimated`?` — estimated variant in use`:``]})]})}var _2=({u:e,active:t})=>(0,H.jsx)(`span`,{style:{border:`1px solid ${t?`#c084fc`:`#52525b`}`,borderRadius:4,padding:`0 5px`,marginRight:4,color:t?`#c084fc`:`#a1a1aa`},children:e});function v2({r:e,scope:t,sessionRpe:n,vo2max:r}){return(0,H.jsxs)(`div`,{style:{...m2,minWidth:320},children:[(0,H.jsxs)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:6},children:[`LIVE PREVIEW — `,t===`store`?`last 7 of 28 days (fixture)`:`Fran, 2026-07-28 (fixture)${r?` · VO₂max ${r}`:` · VO₂max unknown`}${n?` · sRPE ${n}`:``}`]}),t===`segment`&&o2.map((t,n)=>(0,H.jsxs)(`div`,{style:{...h2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[t.effort,t.reps?` ×${t.reps}`:``,t.resistanceKg?` ${t.resistanceKg}kg`:``]}),(0,H.jsx)(`span`,{style:{color:e.perSegment?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.perSegment?.[n]??`—`})]},n)),t===`workout`&&o2.map((t,n)=>(0,H.jsxs)(`div`,{style:{...h2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[`after line `,n+1]}),(0,H.jsx)(`span`,{style:{color:e.running?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.running?.[n]??`—`})]},n)),t===`store`&&(e.perSegment??[]).map((e,t)=>(0,H.jsxs)(`div`,{style:{...h2,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,H.jsxs)(`span`,{style:{color:`#71717a`},children:[`D-`,6-t]}),(0,H.jsx)(`span`,{style:{color:`#7dd3fc`},children:e??`—`})]},t))]})}function y2({scope:e,onSrc:t}){let[n,r]=(0,V.useState)(`power`),[i,a]=(0,V.useState)(`reps * resistance / convert(elapsed, s)`),[o,s]=(0,V.useState)(`kg/s`),[c,l]=(0,V.useState)(`has(reps) and has(resistance) and elapsed > 0`),[u,d]=(0,V.useState)(null),f=`${n} = ${i}${o?` -> ${o}`:``}${c?` when ${c}`:``}`,p=(0,V.useMemo)(()=>f2(f,e,void 0,void 0),[f,e]);(0,V.useEffect)(()=>t(f),[f]);let m=[{id:`name`,label:`name`,value:n,set:r,hint:`calc id`},{id:`expr`,label:`=`,value:i,set:a,hint:`expression — metrics, lookups, functions`},{id:`unit`,label:`->`,value:o,set:s,hint:`output unit (auto allowed)`},{id:`when`,label:`when`,value:c,set:l,hint:`applicability predicate`}];return(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{style:{display:`flex`,gap:6,flexWrap:`wrap`,alignItems:`center`},children:m.map(e=>(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4},children:[(0,H.jsx)(`span`,{style:{color:`#71717a`,fontSize:12},children:e.label}),(0,H.jsx)(`button`,{onClick:()=>d(u===e.id?null:e.id),style:{...h2,fontSize:12,background:u===e.id?`#3b0764`:`#27272a`,border:`1px solid ${u===e.id?`#c084fc`:`#3f3f46`}`,borderRadius:6,color:`#e4e4e7`,padding:`4px 10px`,cursor:`pointer`,maxWidth:340,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.value||(0,H.jsx)(`span`,{style:{color:`#52525b`},children:`∅`})})]},e.id))}),u&&(0,H.jsxs)(`div`,{style:{...m2,marginTop:8},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:4},children:m.find(e=>e.id===u)?.hint}),(0,H.jsx)(`input`,{autoFocus:!0,value:m.find(e=>e.id===u).value,onChange:e=>m.find(e=>e.id===u).set(e.target.value),style:{...h2,width:`100%`,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`4px 8px`,outline:`none`}}),(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:p2(m.find(e=>e.id===u).value,e).items.map((e,t)=>(0,H.jsx)(`button`,{onClick:()=>m.find(e=>e.id===u).set(e.insert),style:{...h2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e.label},t))})]}),(0,H.jsx)(`div`,{style:{...h2,marginTop:8,color:`#52525b`,fontSize:12},children:f}),(0,H.jsx)(g2,{r:p})]})}function b2({scope:e,onSrc:t}){let[n,r]=(0,V.useState)(`power`),[i,a]=(0,V.useState)([`reps`,`*`,`resistance`,`/`,`convert(elapsed, s)`]),o=[{group:`metrics`,items:e===`segment`?[`elapsed`,`reps`,`resistance`,`distance`]:[`sum:reps{}`,`sum:distance{}`,`sum:metMinutes{}`,`sum:elapsed{}`]},{group:`functions`,items:[`convert(·, min)`,`convert(·, km)`,`convert(·, s)`,`min(·, 100)`,`round(·)`]},{group:`lookups`,items:[`lookup("effort", effort, "met")`,`lookup("effort", effort, "disciplineFactor")`,`lookup("rpe-labels", effortLabel, "rpe")`]},{group:`operators`,items:[`+`,`-`,`*`,`/`,`(`,`)`]}],s=`${n} = ${i.join(` `)} -> auto`,c=(0,V.useMemo)(()=>f2(s,e,void 0,void 0),[s,e]);(0,V.useEffect)(()=>t(s),[s]);let l=Y0(c.dim??W0);return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{style:{display:`flex`,gap:8,marginBottom:8,alignItems:`center`},children:[(0,H.jsx)(`span`,{style:{fontSize:12,color:`#71717a`},children:`name`}),(0,H.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),style:{...h2,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`3px 8px`}})]}),o.map(e=>(0,H.jsxs)(`div`,{style:{marginBottom:6},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:3},children:e.group}),(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`},children:e.items.map(e=>(0,H.jsx)(`button`,{onClick:()=>a(t=>[...t,e]),style:{...h2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e},e))})]},e.group)),(0,H.jsxs)(`div`,{style:{...m2,...h2,marginTop:8,color:`#d4d4d8`,minHeight:34},children:[i.map((e,t)=>(0,H.jsx)(`span`,{onClick:()=>a(e=>e.filter((e,n)=>n!==t)),title:`click to remove`,style:{cursor:`pointer`,background:`#27272a`,borderRadius:4,padding:`1px 6px`,marginRight:4,display:`inline-block`},children:e},t)),!i.length&&(0,H.jsx)(`span`,{style:{color:`#52525b`},children:`click palette items to build the formula…`})]}),(0,H.jsxs)(`div`,{style:{fontSize:12,color:`#71717a`,marginTop:6},children:[`unit: `,(0,H.jsx)(`b`,{style:{color:`#c084fc`},children:l?l.units.join(` / `):`—`}),` (derived)`]}),(0,H.jsx)(`div`,{style:{...h2,marginTop:6,color:`#52525b`,fontSize:12},children:s}),(0,H.jsx)(g2,{r:c})]})}var x2={segment:`power = reps * resistance / convert(elapsed, s) -> kg/s when has(reps) and has(resistance) and elapsed > 0`,workout:`sessionLoad = round(rpe * convert(session.duration, min)) -> AU where rpe = sessionRpe | max:effortRpe{} | 5 estimated`,store:`acwr = windowMean(daily, 7d) / windowMean(daily, 28d) -> ratio`};function S2(){let[e,t]=Ct(),n=e.get(`v`)??`text`,[r,i]=(0,V.useState)(`segment`),[a,o]=(0,V.useState)(void 0),[s,c]=(0,V.useState)(void 0),[l,u]=(0,V.useState)(x2.segment),[d,f]=(0,V.useState)(``),p=n===`text`?l:d||l,m=(0,V.useMemo)(()=>f2(p,r,a,s),[p,r,a,s]),h=[[`text`,`A · text + completion`],[`slots`,`B · token slots`],[`guided`,`C · guided builder`]];return(0,H.jsxs)(`div`,{style:{background:`#09090b`,minHeight:`100vh`,color:`#e4e4e7`,padding:24,fontFamily:`system-ui`},children:[(0,H.jsxs)(`div`,{style:{maxWidth:1100,margin:`0 auto`},children:[(0,H.jsx)(`div`,{style:{fontSize:11,color:`#f59e0b`,marginBottom:4},children:`PROTOTYPE — throwaway · issue #863`}),(0,H.jsx)(`h1`,{style:{fontSize:20,fontWeight:700,marginBottom:12},children:`Calc-line guided authoring`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:12,marginBottom:16,alignItems:`center`,fontSize:13},children:[[`segment`,`workout`,`store`].map(e=>(0,H.jsxs)(`button`,{onClick:()=>{i(e),u(x2[e])},style:{padding:`3px 12px`,borderRadius:6,border:`1px solid ${r===e?`#7dd3fc`:`#3f3f46`}`,background:`none`,color:r===e?`#7dd3fc`:`#a1a1aa`,cursor:`pointer`},children:[e,` scope`]},e)),(0,H.jsx)(`span`,{style:{color:`#3f3f46`},children:`|`}),(0,H.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:!!a,onChange:e=>o(e.target.checked?8:void 0)}),` sRPE captured`]}),(0,H.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:!!s,onChange:e=>c(e.target.checked?42:void 0)}),` VO₂max known`]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:16,alignItems:`flex-start`},children:[(0,H.jsxs)(`div`,{style:{flex:1},children:[n===`text`&&(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),style:{...m2,...h2,width:`100%`,color:`#e4e4e7`,outline:`none`},placeholder:`name = expression -> unit when predicate`}),(0,H.jsx)(C2,{src:l,scope:r,onApply:e=>u(e)}),(0,H.jsx)(g2,{r:m})]}),n===`slots`&&(0,H.jsx)(y2,{scope:r,onSrc:f}),n===`guided`&&(0,H.jsx)(b2,{scope:r,onSrc:f})]}),(0,H.jsx)(v2,{r:m,scope:r,sessionRpe:a,vo2max:s})]})]}),(0,H.jsx)(`div`,{style:{position:`fixed`,bottom:16,left:`50%`,transform:`translateX(-50%)`,display:`flex`,gap:6,background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:10,padding:6},children:h.map(([e,r])=>(0,H.jsx)(`button`,{onClick:()=>t({v:e}),style:{padding:`4px 14px`,borderRadius:7,border:`none`,background:n===e?`#7dd3fc`:`transparent`,color:n===e?`#09090b`:`#a1a1aa`,cursor:`pointer`,fontSize:13},children:r},e))})]})}function C2({src:e,scope:t,onApply:n}){let r=(0,V.useMemo)(()=>p2(e,t),[e,t]);return r.items.length?(0,H.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:r.items.map((t,i)=>(0,H.jsxs)(`button`,{onClick:()=>n(e.slice(0,r.from)+t.insert),style:{...h2,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:[t.label,` `,(0,H.jsx)(`span`,{style:{color:`#52525b`},children:t.detail})]},i))}):null}var w2=`01a09d45-885a-738d-ab1e-be31d44fe919`,T2=`:session{result:${w2}}`,E2=`## Morning session
180
192
 
181
193
  Fran went unbroken until round three. Throat on fire.
182
194
 
@@ -184,11 +196,11 @@ Fran went unbroken until round three. Throat on fire.
184
196
  (21-15-9)
185
197
  Thruster 43kg
186
198
  Pull-up
187
- \`\`\``,g2=`Should have paced the first round. Next time: breathing ladder on thrusters.`,_2=[{effort:`Thruster`,round:1,reps:21,load:`43kg`,elapsed:`0:48`},{effort:`Pull-up`,round:1,reps:21,load:`bw`,elapsed:`1:12`},{effort:`Thruster`,round:2,reps:15,load:`43kg`,elapsed:`1:05`},{effort:`Pull-up`,round:2,reps:15,load:`bw`,elapsed:`1:31`},{effort:`Thruster`,round:3,reps:9,load:`43kg`,elapsed:`1:22`},{effort:`Pull-up`,round:3,reps:9,load:`bw`,elapsed:`1:47`}];function v2(e){if(!/:session/.test(e))return{rows:[],note:`no :session head — block would render chart/value instead`};let t=/text:"?([\w-]+)"?/.exec(e)?.[1];return{rows:t?_2.filter(e=>e.effort.toLowerCase().includes(t.toLowerCase())):_2}}function y2({wql:e}){let{rows:t,note:n}=(0,V.useMemo)(()=>v2(e),[e]);return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between px-3 py-2 border-b border-border/60 bg-muted/30`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-foreground`,children:`Fran — 2026-09-13`}),(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-mono`,children:n??`${t.length} rows`})]}),t.length===0?(0,H.jsx)(`div`,{className:`px-3 py-4 text-xs text-muted-foreground italic`,children:n??`no rows match`}):(0,H.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`text-left text-muted-foreground border-b border-border/40`,children:[(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Effort`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Rd`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Reps`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Load`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Split`})]})}),(0,H.jsx)(`tbody`,{children:t.map((e,t)=>(0,H.jsxs)(`tr`,{className:`border-b border-border/20 last:border-0`,children:[(0,H.jsx)(`td`,{className:`px-3 py-1.5`,children:e.effort}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-muted-foreground`,children:e.round}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.reps}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.load}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.elapsed})]},t))})]})]})}function b2({children:e}){return(0,H.jsx)(`p`,{className:`text-sm text-foreground/80 whitespace-pre-wrap leading-relaxed`,children:e})}function x2(){return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card px-3 py-2`,children:[(0,H.jsx)(`div`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground mb-1`,children:`time · 3 rounds`}),(0,H.jsx)(`div`,{className:`text-xs font-mono text-foreground/90`,children:`21-15-9 · Thruster 43kg · Pull-up`})]})}function S2({wql:e}){return(0,H.jsxs)(`div`,{className:`rounded-lg border border-dashed border-amber-500/40 bg-muted/20 p-3`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-amber-500 mb-2 font-mono`,children:`note.md — live fence state`}),(0,H.jsxs)(`pre`,{className:`text-[11px] font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed`,children:[h2.split("```time")[0],(0,H.jsx)(`span`,{className:`opacity-50`,children:"```time … ```"}),`
199
+ \`\`\``,D2=`Should have paced the first round. Next time: breathing ladder on thrusters.`,O2=[{effort:`Thruster`,round:1,reps:21,load:`43kg`,elapsed:`0:48`},{effort:`Pull-up`,round:1,reps:21,load:`bw`,elapsed:`1:12`},{effort:`Thruster`,round:2,reps:15,load:`43kg`,elapsed:`1:05`},{effort:`Pull-up`,round:2,reps:15,load:`bw`,elapsed:`1:31`},{effort:`Thruster`,round:3,reps:9,load:`43kg`,elapsed:`1:22`},{effort:`Pull-up`,round:3,reps:9,load:`bw`,elapsed:`1:47`}];function k2(e){if(!/:session/.test(e))return{rows:[],note:`no :session head — block would render chart/value instead`};let t=/text:"?([\w-]+)"?/.exec(e)?.[1];return{rows:t?O2.filter(e=>e.effort.toLowerCase().includes(t.toLowerCase())):O2}}function A2({wql:e}){let{rows:t,note:n}=(0,V.useMemo)(()=>k2(e),[e]);return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between px-3 py-2 border-b border-border/60 bg-muted/30`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-foreground`,children:`Fran — 2026-09-13`}),(0,H.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-mono`,children:n??`${t.length} rows`})]}),t.length===0?(0,H.jsx)(`div`,{className:`px-3 py-4 text-xs text-muted-foreground italic`,children:n??`no rows match`}):(0,H.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`text-left text-muted-foreground border-b border-border/40`,children:[(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Effort`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Rd`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Reps`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Load`}),(0,H.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Split`})]})}),(0,H.jsx)(`tbody`,{children:t.map((e,t)=>(0,H.jsxs)(`tr`,{className:`border-b border-border/20 last:border-0`,children:[(0,H.jsx)(`td`,{className:`px-3 py-1.5`,children:e.effort}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-muted-foreground`,children:e.round}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.reps}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.load}),(0,H.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.elapsed})]},t))})]})]})}function j2({children:e}){return(0,H.jsx)(`p`,{className:`text-sm text-foreground/80 whitespace-pre-wrap leading-relaxed`,children:e})}function M2(){return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card px-3 py-2`,children:[(0,H.jsx)(`div`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground mb-1`,children:`time · 3 rounds`}),(0,H.jsx)(`div`,{className:`text-xs font-mono text-foreground/90`,children:`21-15-9 · Thruster 43kg · Pull-up`})]})}function N2({wql:e}){return(0,H.jsxs)(`div`,{className:`rounded-lg border border-dashed border-amber-500/40 bg-muted/20 p-3`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-amber-500 mb-2 font-mono`,children:`note.md — live fence state`}),(0,H.jsxs)(`pre`,{className:`text-[11px] font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed`,children:[E2.split("```time")[0],(0,H.jsx)(`span`,{className:`opacity-50`,children:"```time … ```"}),`
188
200
 
189
201
  `,(0,H.jsxs)(`span`,{className:`text-sky-400 bg-sky-400/10 rounded px-1 -mx-1`,children:["```query:table\n",e,"\n```"]}),`
190
202
 
191
- `,g2]})]})}var C2=`✎`;function w2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(e);return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(y2,{wql:e}),!n&&(0,H.jsx)(`button`,{onClick:()=>{a(e),r(!0)},className:`absolute top-2 right-2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted`,children:C2})]}),n&&(0,H.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-card p-3 space-y-2 shadow-lg shadow-sky-500/5`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-sky-400 font-mono`,children:`editing query:table — Apply writes the fence`}),(0,H.jsx)(EC,{query:i,onQueryChange:a,autoFocus:!0,placeholder:`:session…`}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`px-3 py-1 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground`,children:`Cancel`}),(0,H.jsx)(`button`,{onClick:()=>{t(i),r(!1)},className:`px-3 py-1 text-xs rounded-md bg-sky-500 text-zinc-950 font-medium`,children:`Apply to fence`})]})]})]})}function T2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1);return(0,H.jsxs)(`div`,{className:`space-y-3 pb-24`,children:[(0,H.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left rounded-lg transition-shadow ${n?`ring-2 ring-sky-500/70`:`hover:ring-1 hover:ring-border`}`,children:(0,H.jsx)(y2,{wql:e})}),(0,H.jsxs)(`div`,{className:`sticky bottom-20 rounded-xl border p-3 space-y-2 shadow-xl backdrop-blur transition-colors ${n?`border-sky-500/60 bg-card/95`:`border-border bg-card/80 opacity-70`}`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-mono ${n?`text-sky-400`:`text-muted-foreground`}`,children:n?`◉ bound: query:table · ${p2.slice(0,8)}…`:`○ click a query block to bind the composer`}),n&&(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-muted-foreground hover:text-foreground`,children:`Done`})]}),n&&(0,H.jsx)(EC,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`})]})]})}function E2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1);return(0,V.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),n?(0,H.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-muted/60 shadow-lg shadow-sky-500/5`,children:[(0,H.jsx)(`div`,{className:`px-3 pt-2 text-[10px] font-mono text-muted-foreground select-none`,children:"```query:table"}),(0,H.jsx)(`div`,{className:`px-3 py-2`,children:(0,H.jsx)(EC,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`,className:`bg-transparent border-0 shadow-none`})}),(0,H.jsxs)(`div`,{className:`px-3 pb-2 flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-mono text-muted-foreground select-none`,children:"```"}),(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-sky-400 hover:text-sky-300 font-mono`,children:`Esc / leave fence ↩`})]})]}):(0,H.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left hover:ring-1 hover:ring-border rounded-lg`,children:(0,H.jsx)(y2,{wql:e})})}var D2=[[`inline`,`A · in-flow expansion`],[`dock`,`B · bound dock`],[`fence`,`C · fence-as-composer`]];function O2(){let[e,t]=Ct(),n=e.get(`v`)??`inline`,[r,i]=(0,V.useState)(m2),a=e=>{let r=D2[(D2.findIndex(([e])=>e===n)+e+D2.length)%D2.length][0];t({v:r})};return(0,V.useEffect)(()=>{let e=e=>{e.target.closest(`input, textarea, [contenteditable]`)||(e.key===`ArrowLeft`&&a(-1),e.key===`ArrowRight`&&a(1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,H.jsxs)(`div`,{className:`min-h-screen bg-background text-foreground p-6`,children:[(0,H.jsxs)(`div`,{className:`max-w-5xl mx-auto grid grid-cols-[1fr_320px] gap-6 items-start`,children:[(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] text-amber-500 mb-1`,children:`PROTOTYPE — throwaway · query:table editing via WqlComposer`}),(0,H.jsx)(`h1`,{className:`text-xl font-bold`,children:`Journal — 2026-09-13`})]}),(0,H.jsx)(b2,{children:h2.split("```time")[0].trim()}),(0,H.jsx)(x2,{}),n===`inline`&&(0,H.jsx)(w2,{wql:r,setWql:i}),n===`dock`&&(0,H.jsx)(T2,{wql:r,setWql:i}),n===`fence`&&(0,H.jsx)(E2,{wql:r,setWql:i}),(0,H.jsx)(b2,{children:g2})]}),(0,H.jsx)(`div`,{className:`sticky top-6`,children:(0,H.jsx)(S2,{wql:r})})]}),(0,H.jsxs)(`div`,{className:`fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-xl border border-border bg-card/95 backdrop-blur px-2 py-1.5 shadow-2xl z-50`,children:[(0,H.jsx)(`button`,{onClick:()=>a(-1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`←`}),D2.map(([e,r])=>(0,H.jsx)(`button`,{onClick:()=>t({v:e}),className:`px-3 py-1 rounded-lg text-xs transition-colors ${n===e?`bg-sky-400 text-zinc-950 font-medium`:`text-muted-foreground hover:text-foreground`}`,children:r},e)),(0,H.jsx)(`button`,{onClick:()=>a(1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`→`})]})]})}function k2(e,t,n=`absent`){return{id:e,fields:t,missPolicy:n,get:()=>void 0}}function A2(){let e=new jd;return e.register(k2(`effort`,{met:{dimension:q,type:`number`},disciplineFactor:{dimension:q,type:`number`},discipline:{dimension:q,type:`string`},intensityTier:{dimension:q,type:`string`},resolvedFrom:{dimension:q,type:`string`}},`default-row`)),e.register(k2(`rpe-labels`,{rpe:{dimension:q,type:`number`}})),e.register(k2(`profile`,{vo2max:{dimension:q,type:`number`}})),e.register(k2(`disciplines`,{disciplineFactor:{dimension:q,type:`number`}},`default-row`)),e}function j2(e,t){for(let n of t)try{e.register(n)}catch{}}function M2(e,t=`segment`){let n=[],r=[];try{let i=bf(e,{scope:t});r=i.defs;for(let e of i.warnings)n.push({severity:`warning`,message:e})}catch(e){return{defs:r,diagnostics:[{severity:`error`,message:e instanceof Error?e.message:String(e)}],dim:void 0,compound:void 0}}let i=new hd(A2());j2(i,[...Nd,...Ld]);let a;for(let e of r){try{i.register(e)}catch(e){n.push({severity:`error`,message:e instanceof Error?e.message:String(e)});continue}let t=Pf(e)??(e.kind===`library`?Object.keys(e.variants[0]?.nodes??{})[0]:void 0),r=[...e.variants].sort((e,t)=>t.priority-e.priority)[0],o=t&&r.nodeDims?.[t];o&&(a=o)}let o;return a&&(o=Ou(a)),r.length===0&&n.push({severity:`warning`,message:`No calc line parsed.`}),{defs:r,diagnostics:n,dim:a,compound:o}}var N2=[`segment`,`workout`,`store`],P2=[`when`,`where`,`key`,`grouped`,`label`,`emit`,`meta`,`estimated`,`library`,`on`,`by`,`without`,`and`,`or`,`not`],F2=[`convert`,`lookup`,`has`,`round`,`floor`,`ceil`,`abs`,`clamp`,`min`,`max`,`sum`,`avg`,`count`,`last`,`windowMean`,`windowSum`,`windowSd`,`mean`],I2=[{name:`elapsed`,dim:ku.elapsed.dim,detail:`s (time)`},{name:`reps`,dim:ku.reps.dim,detail:`count`},{name:`resistance`,dim:ku.resistance.dim,detail:`kg (mass)`},{name:`distance`,dim:ku.distance.dim,detail:`m (length)`},{name:`effort`,dim:Au.effort,detail:`resolved effort slug`},{name:`effortLabel`,dim:Au.effortLabel,detail:`raw effort label`}],L2=[{name:`sessionRpe`,dim:Au.sessionRpe,detail:`captured session RPE`},{name:`session.duration`,dim:Au[`session.duration`],detail:`workout duration`},{name:`profile.vo2max`,dim:Au[`profile.vo2max`],detail:`user VO₂max (mL/kg/min)`}],R2=Object.keys(ku),z2=Object.keys(ju),B2=[{name:`effort`,detail:`effort catalog`,fields:[`met`,`disciplineFactor`,`discipline`,`intensityTier`,`resolvedFrom`]},{name:`rpe-labels`,detail:`effort label → RPE`,fields:[`rpe`]},{name:`profile`,detail:`user profile`,fields:[`vo2max`]},{name:`disciplines`,detail:`canonical disciplines`,fields:[`disciplineFactor`]}],V2=Object.keys(Fu),H2=Object.keys(ju);function U2(e){if(!e)return V2;let t=V2.filter(t=>{let n=Fu[t];return n?n.dim.every((t,n)=>t===e[n]):!1});return t.length?t:V2}var W2=new Set([...P2,...N2,`lookup`]),G2=new Set(F2),K2=new Set([...I2.map(e=>e.name),...L2.map(e=>e.name),...R2,...B2.map(e=>e.name)]),q2=/^\d*\.?\d+(?:d)?/,J2=/^[A-Za-z_][\w.]*/,Y2=wr.define({name:`calcLine`,token(e){if(e.eatSpace())return null;if(e.match(`#`,!1))return e.skipToEnd(),`comment`;if(e.match(/^"([^"]*)"/)||e.match(/^'([^']*)'/))return`string`;if(e.match(/^(->|==|!=|<=|>=)/)||e.match(/^[+\-*/=<>(),:{}[\]]/))return`operator`;if(e.match(q2))return`number`;if(e.match(J2)){let t=e.current();return W2.has(t)?`keyword`:G2.has(t)?`function`:(K2.has(t),`variableName`)}return e.next(),null}}),X2=jr.define([{tag:B.keyword,color:`#c084fc`},{tag:B.function(B.variableName),color:`#60a5fa`},{tag:B.variableName,color:`#e4e4e7`},{tag:B.number,color:`#fbbf24`},{tag:B.string,color:`#34d399`},{tag:B.operator,color:`#a1a1aa`},{tag:B.comment,color:`#71717a`,fontStyle:`italic`}]);function Z2(){return new Pr(Y2,[Ar(X2)])}var Q2=[`effort`,`thruster`,`push-press`,`front-squat`,`wall-ball`,`row`,`run`];function $2(e={}){let t=e.scope??`segment`;return e=>{let n=e.state.sliceDoc(0,e.pos),r=e.matchBefore(/[\w./"]*/);if(!r)return null;if(/lookup\(\s*/.test(n)){let t=n.lastIndexOf(`lookup(`),r=n.slice(t+7);if(!/,/.test(r)&&/^"?[\w.-]*"?$/.test(r.replace(/"/g,``).trim()||``)){let t=r.replace(/"/g,``).trim(),n=B2.filter(e=>e.name.startsWith(t)).map(e=>({label:e.name,insert:`"${e.name}"`,detail:e.detail}));if(n.length)return{from:e.pos-t.length,options:n,validFor:/^[\w.-]*$/}}let i=/lookup\(\s*"[^"]+"\s*,\s*[^,]+,\s*"?([\w-]*)"?$/.exec(n);if(i){let t=/lookup\(\s*"([^"]+)"/.exec(n)?.[1],r=(B2.find(e=>e.name===t)?.fields??[]).filter(e=>e.startsWith(i[1])).map(e=>({label:e,insert:`"${e}"`,detail:`${t} field`}));return{from:e.pos-i[1].length,options:r,validFor:/^[\w-]*$/}}let a=/lookup\(\s*"(effort)"\s*,\s*"?([\w.-]*)"?$/.exec(n);if(a){let t=Q2.filter(e=>e.startsWith(a[2])).map(e=>({label:e,insert:e===`effort`?e:`"${e}"`,detail:`effort key`}));return{from:e.pos-a[2].length,options:t,validFor:/^[\w.-]*$/}}}let i=/->\s*([\w/]*)$/.exec(n);if(i){let n=e.state.doc.lineAt(e.pos).text,r=M2(n,t),a=r.diagnostics.length===0?r.dim:void 0,o=U2(a).filter(e=>e.startsWith(i[1])).map(e=>({label:e,detail:a?`matches inferred dimension`:`unit`}));return{from:e.pos-i[1].length,options:o,validFor:/^[\w/]*$/}}if(t===`store`){let e=/^(sum|avg|max|min|count|last):([\w.]*)$/.exec(r.text);if(e){let t=R2.filter(t=>t.startsWith(e[2])).map(e=>({label:e,detail:`metric key`}));return{from:r.from+r.text.indexOf(`:`)+1,options:t,validFor:/^[\w.]*$/}}}let a=[];if(t===`segment`)a.push(...I2.map(e=>({label:e.name,insert:e.name,detail:e.detail})));else if(a.push(...L2.map(e=>({label:e.name,insert:e.name,detail:e.detail}))),t===`workout`){for(let e of z2)for(let t of[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`])a.push({label:`${e}(${t})`,insert:`${e}(${t})`,detail:`aggregate`});a.push({label:`sum(reps, without: rest)`,insert:`sum(reps, without: rest)`,detail:`exclusion aggregate`})}a.push(...F2.map(e=>({label:`${e}()`,insert:`${e}()`,detail:`function`}))),t===`store`&&a.push(...H2.map(e=>({label:`${e}:{}`,insert:`${e}:`,detail:`WQL atom`}))),a.push(...P2.map(e=>({label:e,insert:e===`when`?`when `:e,detail:`clause`}))),a.push({label:`estimated`,insert:`estimated`,detail:`variant origin`}),a.push({label:`(library)`,insert:`(library)`,detail:`library calc`});let o=a.filter(e=>e.label.startsWith(r.text)).slice(0,20);return o.length?{from:r.from,options:o,validFor:/^[\w./]*$/}:null}}function e4(e){return Jr({override:[$2(e)]})}function t4({value:e,onChange:t,scope:n=`segment`,placeholder:r,readOnly:i=!1,autoFocus:a=!1,className:o}){let s=(0,V.useRef)(null),c=(0,V.useRef)(null),l=(0,V.useRef)(t);return l.current=t,(0,V.useEffect)(()=>{let t=s.current;if(!t)return;c.current?.destroy();let r=Er.updateListener.of(e=>{e.docChanged&&l.current(e.state.doc.toString())}),o=new Er({state:ri.create({doc:e,extensions:[Z2(),e4({scope:n}),Qr(),pi(),yr.of([ti,...$r,...ci]),Er.lineWrapping,ri.readOnly.of(i),r,Er.theme({"&":{height:`auto`,minHeight:`120px`,fontSize:`13px`,border:`1px solid rgb(63 63 70)`,borderRadius:`8px`},".cm-scroller":{fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,lineHeight:`1.55`},".cm-content":{padding:`8px 4px`},".cm-gutters":{borderRight:`1px solid rgb(63 63 70)`,minWidth:`28px`},"&.cm-focused":{outline:`2px solid rgb(139 92 246 / 0.5)`,outlineOffset:`1px`}})]}),parent:t});return a&&requestAnimationFrame(()=>o.focus()),c.current=o,()=>o.destroy()},[n,i]),(0,V.useEffect)(()=>{let t=c.current;if(!t)return;let n=t.state.doc.toString();n!==e&&t.dispatch({changes:{from:0,to:n.length,insert:e}})},[e]),(0,H.jsx)(`div`,{ref:s,className:`calc-line-editor ${o??``}`,"data-testid":`calc-line-editor`})}function n4({analysis:e}){let{dim:t,compound:n,diagnostics:r}=e,i=r.filter(e=>e.severity===`error`),a=r.filter(e=>e.severity===`warning`),o=i.length===0&&a.length===0&&t!==void 0;return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 px-3 py-2 text-xs`,"data-testid":`calc-diagnostics`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[t?(0,H.jsxs)(`div`,{className:`text-muted-foreground`,children:[`computes `,(0,H.jsx)(`b`,{className:`text-foreground`,children:i4(t)}),n&&(0,H.jsxs)(`span`,{className:`text-purple-400 dark:text-purple-300`,children:[` → `,n]})]}):!o&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`dimension unknown`}),o&&(0,H.jsx)(`span`,{className:`text-signal-positive`,children:`✓ valid`})]}),i.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e.message]},`e-${t}`)),a.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-signal-caution`,children:[`⚠ `,e.message]},`w-${t}`)),i.length===0&&a.length===0&&t===void 0&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`Type a calc line to see diagnostics.`})]})}var r4=[[`L`,`length`],[`M`,`mass`],[`T`,`time`],[`C`,`count`],[`E`,`energy`]];function i4(e){let t=[];return e.forEach((e,n)=>{e!==0&&t.push(e===1?r4[n][1]:`${r4[n][1]}${e}`)}),t.length?t.join(`·`):`dimensionless`}function a4(e){return new ga({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function o4(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function s4(e){return e.output?.emitType??e.output?.key??e.id}function c4(e,t){for(let n of e){if(n.outputType!==`analytics`||!(n.metrics.find(e=>e.type?.toLowerCase()===`label`&&String(e.value)===t)??n.metrics.find(e=>String(e.value)===t)))continue;let e=n.metrics.find(e=>typeof e.value==`number`);if(e)return{value:e.value,unit:e.unit,origin:e.origin}}}function l4(e){return String(Number.isInteger(e)?e:Math.round(e*100)/100)}function u4(e,t,n){return Jd(e,{userProfile:t.vo2max===void 0?void 0:{vo2max:t.vo2max},calcs:n}).engine}function d4(e){let t=[],n=e.defs[0];if(!n)return{rows:[],errors:[`No calc line to preview.`]};let r=s4(n),i=e.logs.filter(e=>e.outputType===`segment`);if(e.scope===`segment`){let n=u4(e.block,e,e.defs),a=[];for(let e of i){let t=n.run(a4(o4(e))).metrics.rawMetrics.find(e=>e.type===r);if(!t){a.push(null);continue}let i=typeof t.value==`number`?t.value:NaN;if(!Number.isFinite(i)){a.push(null);continue}a.push({label:e.metrics.find(e=>e.type===`effort-data`)?.value?.label??`segment`,text:l4(i),unit:t.unit,estimated:t.origin===`analyzed-estimated`,raw:i})}return{rows:a,errors:t}}if(e.scope===`workout`){let n=i.map(o4),a=[];for(let t=1;t<=n.length;t++){let i=u4(e.block,e,e.defs);for(let e=0;e<t;e++)i.run(a4(n[e]));let o=c4(i.finalize(),r),s=o&&typeof o.value==`number`?o.value:NaN;o&&Number.isFinite(s)?a.push({label:`after line ${t}`,text:l4(s),unit:o.unit,estimated:o.origin===`analyzed-estimated`,raw:s}):a.push(null)}return{rows:a,errors:t}}return p4(n,t)}var f4=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function p4(e,t){let n=[],r=e.variants[0]?.nodes[Pf(e)??`value`]?.expression??``,i=e=>e.reduce((e,t)=>e+t,0)/e.length,a=e=>{let t=i(e);return Math.sqrt(i(e.map(e=>(e-t)**2)))},o=(e,t)=>f4.map((n,r)=>r+1>=e?t(f4.slice(r+1-e,r+1)):NaN),s=o(7,i),c=o(28,i),l=o(7,a),u=o(7,e=>e.reduce((e,t)=>e+t,0)),d=r.includes(`windowSd`)||r.length===0?s.map((e,t)=>e/l[t]):s.map((e,t)=>e/c[t]);return m4(r.includes(`windowSum`)||r.includes(` * sum`)?u:d,n),{rows:[],series:n,errors:t}}function m4(e,t){for(let n of e.slice(-7))t.push(Number.isNaN(n)?null:Number(Math.round(n*100)/100))}var h4=[{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:21,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:21,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:15,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:15,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:9,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:9,resistanceKg:0}];function g4(e){return{type:`effort-data`,origin:`analyzed`,value:{slug:e.slug,label:e.label,aliases:[],baseAttributes:{met:e.met,discipline:e.discipline},registrySource:`bundled`}}}function _4(e,t){let n=[g4(e)];return n.push({type:`elapsed`,value:e.elapsedMs,origin:`runtime`}),e.reps!==void 0&&n.push({type:`rep`,value:e.reps,origin:`runtime`}),e.resistanceKg!==void 0&&n.push({type:`resistance`,value:e.resistanceKg,origin:`runtime`}),vj(new ga({outputType:`segment`,timeSpan:{started:t*1e3,ended:t*1e3+e.elapsedMs},sourceBlockKey:`preview-block`,stackLevel:1,metrics:n}))}function v4(){return{id:`preview-block`,dialect:`time`,startLine:0,endLine:10,content:"```time\nFran preview\n```",state:`idle`,widgetIds:{},version:1,createdAt:0}}var y4=h4.map((e,t)=>_4(e,t+1)),b4=v4();function x4(e){return e==null?`—`:String(e)}function S4({scope:e,analysis:t,vo2max:n}){let r=(0,V.useMemo)(()=>t.defs.filter(()=>t.diagnostics.length===0),[t]),i=r[0],a=(0,V.useMemo)(()=>{if(i)return d4({logs:y4,block:b4,defs:r,scope:e,vo2max:n})},[i,e,n]);return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 p-3 text-xs`,"data-testid":`calc-preview`,children:[(0,H.jsxs)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wide text-muted-foreground`,children:[`Live preview — `,e===`store`?`last 7 of 28 fixture days`:`Fran (fixture)`]}),!i&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`Enter a valid calc line to see live results.`}),i&&a?.rows&&(0,H.jsxs)(`div`,{className:`space-y-1 font-mono`,children:[a.rows.length===0&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`No applicable segments.`}),a.rows.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:e?e.label:`segment ${t+1}`}),(0,H.jsx)(`span`,{className:e?`text-sky-300 dark:text-sky-400`:`text-muted-foreground`,children:e?`${e.text}${e.unit?` ${e.unit}`:``}${e.estimated?` (est.)`:``}`:`—`})]},t))]}),i&&a?.series&&(0,H.jsx)(`div`,{className:`space-y-1 font-mono`,children:a.series.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[`D-`,6-t]}),(0,H.jsx)(`span`,{className:`text-sky-300 dark:text-sky-400`,children:x4(e)})]},t))}),a?.errors?.length?a.errors.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e]},`e-${t}`)):null]})}var C4=`wodwiki-user-calcs`,w4=1,T4=`calcs`,E4=`user-calc:`,D4;function O4(){return D4||=or(C4,w4,{upgrade(e){e.objectStoreNames.contains(T4)||e.createObjectStore(T4,{keyPath:`id`})}}),D4}async function k4(){return UD?(await ZD(E4)).map(e=>e.value).sort((e,t)=>t.updatedAt-e.updatedAt):(await(await O4()).getAll(T4)).sort((e,t)=>t.updatedAt-e.updatedAt)}async function A4(e){if(UD){await QD(E4+e.id,{id:e.id,lineForm:e.lineForm,updatedAt:e.updatedAt??Date.now()});return}await(await O4()).put(T4,{...e,updatedAt:e.updatedAt??Date.now()})}async function j4(e){if(UD)return $D(E4+e);await(await O4()).delete(T4,e)}var M4=[`segment`,`workout`,`store`];function N4(e,t){let n=e[0]?.id;if(n)return n;let r=/^[\s\S]*?^\s*([A-Za-z_][\w.-]*)\s*=.*$/m.exec(t);return r?r[1]:`custom-${Date.now().toString(36)}`}function P4({defaultScope:e=`segment`,initialId:t}){let[n,r]=(0,V.useState)(`# ${e} calc line
203
+ `,D2]})]})}var P2=`✎`;function F2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(e);return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(A2,{wql:e}),!n&&(0,H.jsx)(`button`,{onClick:()=>{a(e),r(!0)},className:`absolute top-2 right-2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted`,children:P2})]}),n&&(0,H.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-card p-3 space-y-2 shadow-lg shadow-sky-500/5`,children:[(0,H.jsx)(`div`,{className:`text-[10px] text-sky-400 font-mono`,children:`editing query:table — Apply writes the fence`}),(0,H.jsx)(EC,{query:i,onQueryChange:a,autoFocus:!0,placeholder:`:session…`}),(0,H.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`px-3 py-1 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground`,children:`Cancel`}),(0,H.jsx)(`button`,{onClick:()=>{t(i),r(!1)},className:`px-3 py-1 text-xs rounded-md bg-sky-500 text-zinc-950 font-medium`,children:`Apply to fence`})]})]})]})}function I2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1);return(0,H.jsxs)(`div`,{className:`space-y-3 pb-24`,children:[(0,H.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left rounded-lg transition-shadow ${n?`ring-2 ring-sky-500/70`:`hover:ring-1 hover:ring-border`}`,children:(0,H.jsx)(A2,{wql:e})}),(0,H.jsxs)(`div`,{className:`sticky bottom-20 rounded-xl border p-3 space-y-2 shadow-xl backdrop-blur transition-colors ${n?`border-sky-500/60 bg-card/95`:`border-border bg-card/80 opacity-70`}`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-mono ${n?`text-sky-400`:`text-muted-foreground`}`,children:n?`◉ bound: query:table · ${w2.slice(0,8)}…`:`○ click a query block to bind the composer`}),n&&(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-muted-foreground hover:text-foreground`,children:`Done`})]}),n&&(0,H.jsx)(EC,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`})]})]})}function L2({wql:e,setWql:t}){let[n,r]=(0,V.useState)(!1);return(0,V.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),n?(0,H.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-muted/60 shadow-lg shadow-sky-500/5`,children:[(0,H.jsx)(`div`,{className:`px-3 pt-2 text-[10px] font-mono text-muted-foreground select-none`,children:"```query:table"}),(0,H.jsx)(`div`,{className:`px-3 py-2`,children:(0,H.jsx)(EC,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`,className:`bg-transparent border-0 shadow-none`})}),(0,H.jsxs)(`div`,{className:`px-3 pb-2 flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] font-mono text-muted-foreground select-none`,children:"```"}),(0,H.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-sky-400 hover:text-sky-300 font-mono`,children:`Esc / leave fence ↩`})]})]}):(0,H.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left hover:ring-1 hover:ring-border rounded-lg`,children:(0,H.jsx)(A2,{wql:e})})}var R2=[[`inline`,`A · in-flow expansion`],[`dock`,`B · bound dock`],[`fence`,`C · fence-as-composer`]];function z2(){let[e,t]=Ct(),n=e.get(`v`)??`inline`,[r,i]=(0,V.useState)(T2),a=e=>{let r=R2[(R2.findIndex(([e])=>e===n)+e+R2.length)%R2.length][0];t({v:r})};return(0,V.useEffect)(()=>{let e=e=>{e.target.closest(`input, textarea, [contenteditable]`)||(e.key===`ArrowLeft`&&a(-1),e.key===`ArrowRight`&&a(1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,H.jsxs)(`div`,{className:`min-h-screen bg-background text-foreground p-6`,children:[(0,H.jsxs)(`div`,{className:`max-w-5xl mx-auto grid grid-cols-[1fr_320px] gap-6 items-start`,children:[(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{className:`text-[11px] text-amber-500 mb-1`,children:`PROTOTYPE — throwaway · query:table editing via WqlComposer`}),(0,H.jsx)(`h1`,{className:`text-xl font-bold`,children:`Journal — 2026-09-13`})]}),(0,H.jsx)(j2,{children:E2.split("```time")[0].trim()}),(0,H.jsx)(M2,{}),n===`inline`&&(0,H.jsx)(F2,{wql:r,setWql:i}),n===`dock`&&(0,H.jsx)(I2,{wql:r,setWql:i}),n===`fence`&&(0,H.jsx)(L2,{wql:r,setWql:i}),(0,H.jsx)(j2,{children:D2})]}),(0,H.jsx)(`div`,{className:`sticky top-6`,children:(0,H.jsx)(N2,{wql:r})})]}),(0,H.jsxs)(`div`,{className:`fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-xl border border-border bg-card/95 backdrop-blur px-2 py-1.5 shadow-2xl z-50`,children:[(0,H.jsx)(`button`,{onClick:()=>a(-1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`←`}),R2.map(([e,r])=>(0,H.jsx)(`button`,{onClick:()=>t({v:e}),className:`px-3 py-1 rounded-lg text-xs transition-colors ${n===e?`bg-sky-400 text-zinc-950 font-medium`:`text-muted-foreground hover:text-foreground`}`,children:r},e)),(0,H.jsx)(`button`,{onClick:()=>a(1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`→`})]})]})}function B2(e,t,n=`absent`){return{id:e,fields:t,missPolicy:n,get:()=>void 0}}function V2(){let e=new jd;return e.register(B2(`effort`,{met:{dimension:q,type:`number`},disciplineFactor:{dimension:q,type:`number`},discipline:{dimension:q,type:`string`},intensityTier:{dimension:q,type:`string`},resolvedFrom:{dimension:q,type:`string`}},`default-row`)),e.register(B2(`rpe-labels`,{rpe:{dimension:q,type:`number`}})),e.register(B2(`profile`,{vo2max:{dimension:q,type:`number`}})),e.register(B2(`disciplines`,{disciplineFactor:{dimension:q,type:`number`}},`default-row`)),e}function H2(e,t){for(let n of t)try{e.register(n)}catch{}}function U2(e,t=`segment`){let n=[],r=[];try{let i=bf(e,{scope:t});r=i.defs;for(let e of i.warnings)n.push({severity:`warning`,message:e})}catch(e){return{defs:r,diagnostics:[{severity:`error`,message:e instanceof Error?e.message:String(e)}],dim:void 0,compound:void 0}}let i=new hd(V2());H2(i,[...Nd,...Ld]);let a;for(let e of r){try{i.register(e)}catch(e){n.push({severity:`error`,message:e instanceof Error?e.message:String(e)});continue}let t=Pf(e)??(e.kind===`library`?Object.keys(e.variants[0]?.nodes??{})[0]:void 0),r=[...e.variants].sort((e,t)=>t.priority-e.priority)[0],o=t&&r.nodeDims?.[t];o&&(a=o)}let o;return a&&(o=Ou(a)),r.length===0&&n.push({severity:`warning`,message:`No calc line parsed.`}),{defs:r,diagnostics:n,dim:a,compound:o}}var W2=[`segment`,`workout`,`store`],G2=[`when`,`where`,`key`,`grouped`,`label`,`emit`,`meta`,`estimated`,`library`,`on`,`by`,`without`,`and`,`or`,`not`],K2=[`convert`,`lookup`,`has`,`round`,`floor`,`ceil`,`abs`,`clamp`,`min`,`max`,`sum`,`avg`,`count`,`last`,`windowMean`,`windowSum`,`windowSd`,`mean`],q2=[{name:`elapsed`,dim:ku.elapsed.dim,detail:`s (time)`},{name:`reps`,dim:ku.reps.dim,detail:`count`},{name:`resistance`,dim:ku.resistance.dim,detail:`kg (mass)`},{name:`distance`,dim:ku.distance.dim,detail:`m (length)`},{name:`effort`,dim:Au.effort,detail:`resolved effort slug`},{name:`effortLabel`,dim:Au.effortLabel,detail:`raw effort label`}],J2=[{name:`sessionRpe`,dim:Au.sessionRpe,detail:`captured session RPE`},{name:`session.duration`,dim:Au[`session.duration`],detail:`workout duration`},{name:`profile.vo2max`,dim:Au[`profile.vo2max`],detail:`user VO₂max (mL/kg/min)`}],Y2=Object.keys(ku),X2=Object.keys(ju),Z2=[{name:`effort`,detail:`effort catalog`,fields:[`met`,`disciplineFactor`,`discipline`,`intensityTier`,`resolvedFrom`]},{name:`rpe-labels`,detail:`effort label → RPE`,fields:[`rpe`]},{name:`profile`,detail:`user profile`,fields:[`vo2max`]},{name:`disciplines`,detail:`canonical disciplines`,fields:[`disciplineFactor`]}],Q2=Object.keys(Fu),$2=Object.keys(ju);function e4(e){if(!e)return Q2;let t=Q2.filter(t=>{let n=Fu[t];return n?n.dim.every((t,n)=>t===e[n]):!1});return t.length?t:Q2}var t4=new Set([...G2,...W2,`lookup`]),n4=new Set(K2),r4=new Set([...q2.map(e=>e.name),...J2.map(e=>e.name),...Y2,...Z2.map(e=>e.name)]),i4=/^\d*\.?\d+(?:d)?/,a4=/^[A-Za-z_][\w.]*/,o4=wr.define({name:`calcLine`,token(e){if(e.eatSpace())return null;if(e.match(`#`,!1))return e.skipToEnd(),`comment`;if(e.match(/^"([^"]*)"/)||e.match(/^'([^']*)'/))return`string`;if(e.match(/^(->|==|!=|<=|>=)/)||e.match(/^[+\-*/=<>(),:{}[\]]/))return`operator`;if(e.match(i4))return`number`;if(e.match(a4)){let t=e.current();return t4.has(t)?`keyword`:n4.has(t)?`function`:(r4.has(t),`variableName`)}return e.next(),null}}),s4=jr.define([{tag:B.keyword,color:`#c084fc`},{tag:B.function(B.variableName),color:`#60a5fa`},{tag:B.variableName,color:`#e4e4e7`},{tag:B.number,color:`#fbbf24`},{tag:B.string,color:`#34d399`},{tag:B.operator,color:`#a1a1aa`},{tag:B.comment,color:`#71717a`,fontStyle:`italic`}]);function c4(){return new Pr(o4,[Ar(s4)])}var l4=[`effort`,`thruster`,`push-press`,`front-squat`,`wall-ball`,`row`,`run`];function u4(e={}){let t=e.scope??`segment`;return e=>{let n=e.state.sliceDoc(0,e.pos),r=e.matchBefore(/[\w./"]*/);if(!r)return null;if(/lookup\(\s*/.test(n)){let t=n.lastIndexOf(`lookup(`),r=n.slice(t+7);if(!/,/.test(r)&&/^"?[\w.-]*"?$/.test(r.replace(/"/g,``).trim()||``)){let t=r.replace(/"/g,``).trim(),n=Z2.filter(e=>e.name.startsWith(t)).map(e=>({label:e.name,insert:`"${e.name}"`,detail:e.detail}));if(n.length)return{from:e.pos-t.length,options:n,validFor:/^[\w.-]*$/}}let i=/lookup\(\s*"[^"]+"\s*,\s*[^,]+,\s*"?([\w-]*)"?$/.exec(n);if(i){let t=/lookup\(\s*"([^"]+)"/.exec(n)?.[1],r=(Z2.find(e=>e.name===t)?.fields??[]).filter(e=>e.startsWith(i[1])).map(e=>({label:e,insert:`"${e}"`,detail:`${t} field`}));return{from:e.pos-i[1].length,options:r,validFor:/^[\w-]*$/}}let a=/lookup\(\s*"(effort)"\s*,\s*"?([\w.-]*)"?$/.exec(n);if(a){let t=l4.filter(e=>e.startsWith(a[2])).map(e=>({label:e,insert:e===`effort`?e:`"${e}"`,detail:`effort key`}));return{from:e.pos-a[2].length,options:t,validFor:/^[\w.-]*$/}}}let i=/->\s*([\w/]*)$/.exec(n);if(i){let n=e.state.doc.lineAt(e.pos).text,r=U2(n,t),a=r.diagnostics.length===0?r.dim:void 0,o=e4(a).filter(e=>e.startsWith(i[1])).map(e=>({label:e,detail:a?`matches inferred dimension`:`unit`}));return{from:e.pos-i[1].length,options:o,validFor:/^[\w/]*$/}}if(t===`store`){let e=/^(sum|avg|max|min|count|last):([\w.]*)$/.exec(r.text);if(e){let t=Y2.filter(t=>t.startsWith(e[2])).map(e=>({label:e,detail:`metric key`}));return{from:r.from+r.text.indexOf(`:`)+1,options:t,validFor:/^[\w.]*$/}}}let a=[];if(t===`segment`)a.push(...q2.map(e=>({label:e.name,insert:e.name,detail:e.detail})));else if(a.push(...J2.map(e=>({label:e.name,insert:e.name,detail:e.detail}))),t===`workout`){for(let e of X2)for(let t of[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`])a.push({label:`${e}(${t})`,insert:`${e}(${t})`,detail:`aggregate`});a.push({label:`sum(reps, without: rest)`,insert:`sum(reps, without: rest)`,detail:`exclusion aggregate`})}a.push(...K2.map(e=>({label:`${e}()`,insert:`${e}()`,detail:`function`}))),t===`store`&&a.push(...$2.map(e=>({label:`${e}:{}`,insert:`${e}:`,detail:`WQL atom`}))),a.push(...G2.map(e=>({label:e,insert:e===`when`?`when `:e,detail:`clause`}))),a.push({label:`estimated`,insert:`estimated`,detail:`variant origin`}),a.push({label:`(library)`,insert:`(library)`,detail:`library calc`});let o=a.filter(e=>e.label.startsWith(r.text)).slice(0,20);return o.length?{from:r.from,options:o,validFor:/^[\w./]*$/}:null}}function d4(e){return Jr({override:[u4(e)]})}function f4({value:e,onChange:t,scope:n=`segment`,placeholder:r,readOnly:i=!1,autoFocus:a=!1,className:o}){let s=(0,V.useRef)(null),c=(0,V.useRef)(null),l=(0,V.useRef)(t);return l.current=t,(0,V.useEffect)(()=>{let t=s.current;if(!t)return;c.current?.destroy();let r=Er.updateListener.of(e=>{e.docChanged&&l.current(e.state.doc.toString())}),o=new Er({state:ri.create({doc:e,extensions:[c4(),d4({scope:n}),Qr(),pi(),yr.of([ti,...$r,...ci]),Er.lineWrapping,ri.readOnly.of(i),r,Er.theme({"&":{height:`auto`,minHeight:`120px`,fontSize:`13px`,border:`1px solid rgb(63 63 70)`,borderRadius:`8px`},".cm-scroller":{fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,lineHeight:`1.55`},".cm-content":{padding:`8px 4px`},".cm-gutters":{borderRight:`1px solid rgb(63 63 70)`,minWidth:`28px`},"&.cm-focused":{outline:`2px solid rgb(139 92 246 / 0.5)`,outlineOffset:`1px`}})]}),parent:t});return a&&requestAnimationFrame(()=>o.focus()),c.current=o,()=>o.destroy()},[n,i]),(0,V.useEffect)(()=>{let t=c.current;if(!t)return;let n=t.state.doc.toString();n!==e&&t.dispatch({changes:{from:0,to:n.length,insert:e}})},[e]),(0,H.jsx)(`div`,{ref:s,className:`calc-line-editor ${o??``}`,"data-testid":`calc-line-editor`})}function p4({analysis:e}){let{dim:t,compound:n,diagnostics:r}=e,i=r.filter(e=>e.severity===`error`),a=r.filter(e=>e.severity===`warning`),o=i.length===0&&a.length===0&&t!==void 0;return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 px-3 py-2 text-xs`,"data-testid":`calc-diagnostics`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[t?(0,H.jsxs)(`div`,{className:`text-muted-foreground`,children:[`computes `,(0,H.jsx)(`b`,{className:`text-foreground`,children:h4(t)}),n&&(0,H.jsxs)(`span`,{className:`text-purple-400 dark:text-purple-300`,children:[` → `,n]})]}):!o&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`dimension unknown`}),o&&(0,H.jsx)(`span`,{className:`text-signal-positive`,children:`✓ valid`})]}),i.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e.message]},`e-${t}`)),a.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-signal-caution`,children:[`⚠ `,e.message]},`w-${t}`)),i.length===0&&a.length===0&&t===void 0&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`Type a calc line to see diagnostics.`})]})}var m4=[[`L`,`length`],[`M`,`mass`],[`T`,`time`],[`C`,`count`],[`E`,`energy`]];function h4(e){let t=[];return e.forEach((e,n)=>{e!==0&&t.push(e===1?m4[n][1]:`${m4[n][1]}${e}`)}),t.length?t.join(`·`):`dimensionless`}function g4(e){return new ga({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function _4(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function v4(e){return e.output?.emitType??e.output?.key??e.id}function y4(e,t){for(let n of e){if(n.outputType!==`analytics`||!(n.metrics.find(e=>e.type?.toLowerCase()===`label`&&String(e.value)===t)??n.metrics.find(e=>String(e.value)===t)))continue;let e=n.metrics.find(e=>typeof e.value==`number`);if(e)return{value:e.value,unit:e.unit,origin:e.origin}}}function b4(e){return String(Number.isInteger(e)?e:Math.round(e*100)/100)}function x4(e,t,n){return Jd(e,{userProfile:t.vo2max===void 0?void 0:{vo2max:t.vo2max},calcs:n}).engine}function S4(e){let t=[],n=e.defs[0];if(!n)return{rows:[],errors:[`No calc line to preview.`]};let r=v4(n),i=e.logs.filter(e=>e.outputType===`segment`);if(e.scope===`segment`){let n=x4(e.block,e,e.defs),a=[];for(let e of i){let t=n.run(g4(_4(e))).metrics.rawMetrics.find(e=>e.type===r);if(!t){a.push(null);continue}let i=typeof t.value==`number`?t.value:NaN;if(!Number.isFinite(i)){a.push(null);continue}a.push({label:e.metrics.find(e=>e.type===`effort-data`)?.value?.label??`segment`,text:b4(i),unit:t.unit,estimated:t.origin===`analyzed-estimated`,raw:i})}return{rows:a,errors:t}}if(e.scope===`workout`){let n=i.map(_4),a=[];for(let t=1;t<=n.length;t++){let i=x4(e.block,e,e.defs);for(let e=0;e<t;e++)i.run(g4(n[e]));let o=y4(i.finalize(),r),s=o&&typeof o.value==`number`?o.value:NaN;o&&Number.isFinite(s)?a.push({label:`after line ${t}`,text:b4(s),unit:o.unit,estimated:o.origin===`analyzed-estimated`,raw:s}):a.push(null)}return{rows:a,errors:t}}return w4(n,t)}var C4=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function w4(e,t){let n=[],r=e.variants[0]?.nodes[Pf(e)??`value`]?.expression??``,i=e=>e.reduce((e,t)=>e+t,0)/e.length,a=e=>{let t=i(e);return Math.sqrt(i(e.map(e=>(e-t)**2)))},o=(e,t)=>C4.map((n,r)=>r+1>=e?t(C4.slice(r+1-e,r+1)):NaN),s=o(7,i),c=o(28,i),l=o(7,a),u=o(7,e=>e.reduce((e,t)=>e+t,0)),d=r.includes(`windowSd`)||r.length===0?s.map((e,t)=>e/l[t]):s.map((e,t)=>e/c[t]);return T4(r.includes(`windowSum`)||r.includes(` * sum`)?u:d,n),{rows:[],series:n,errors:t}}function T4(e,t){for(let n of e.slice(-7))t.push(Number.isNaN(n)?null:Number(Math.round(n*100)/100))}var E4=[{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:21,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:21,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:15,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:15,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:9,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:9,resistanceKg:0}];function D4(e){return{type:`effort-data`,origin:`analyzed`,value:{slug:e.slug,label:e.label,aliases:[],baseAttributes:{met:e.met,discipline:e.discipline},registrySource:`bundled`}}}function O4(e,t){let n=[D4(e)];return n.push({type:`elapsed`,value:e.elapsedMs,origin:`runtime`}),e.reps!==void 0&&n.push({type:`rep`,value:e.reps,origin:`runtime`}),e.resistanceKg!==void 0&&n.push({type:`resistance`,value:e.resistanceKg,origin:`runtime`}),vj(new ga({outputType:`segment`,timeSpan:{started:t*1e3,ended:t*1e3+e.elapsedMs},sourceBlockKey:`preview-block`,stackLevel:1,metrics:n}))}function k4(){return{id:`preview-block`,dialect:`time`,startLine:0,endLine:10,content:"```time\nFran preview\n```",state:`idle`,widgetIds:{},version:1,createdAt:0}}var A4=E4.map((e,t)=>O4(e,t+1)),j4=k4();function M4(e){return e==null?`—`:String(e)}function N4({scope:e,analysis:t,vo2max:n}){let r=(0,V.useMemo)(()=>t.defs.filter(()=>t.diagnostics.length===0),[t]),i=r[0],a=(0,V.useMemo)(()=>{if(i)return S4({logs:A4,block:j4,defs:r,scope:e,vo2max:n})},[i,e,n]);return(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 p-3 text-xs`,"data-testid":`calc-preview`,children:[(0,H.jsxs)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wide text-muted-foreground`,children:[`Live preview — `,e===`store`?`last 7 of 28 fixture days`:`Fran (fixture)`]}),!i&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`Enter a valid calc line to see live results.`}),i&&a?.rows&&(0,H.jsxs)(`div`,{className:`space-y-1 font-mono`,children:[a.rows.length===0&&(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:`No applicable segments.`}),a.rows.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:e?e.label:`segment ${t+1}`}),(0,H.jsx)(`span`,{className:e?`text-sky-300 dark:text-sky-400`:`text-muted-foreground`,children:e?`${e.text}${e.unit?` ${e.unit}`:``}${e.estimated?` (est.)`:``}`:`—`})]},t))]}),i&&a?.series&&(0,H.jsx)(`div`,{className:`space-y-1 font-mono`,children:a.series.map((e,t)=>(0,H.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[`D-`,6-t]}),(0,H.jsx)(`span`,{className:`text-sky-300 dark:text-sky-400`,children:M4(e)})]},t))}),a?.errors?.length?a.errors.map((e,t)=>(0,H.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e]},`e-${t}`)):null]})}var P4=`wodwiki-user-calcs`,F4=1,I4=`calcs`,L4=`user-calc:`,R4;function z4(){return R4||=or(P4,F4,{upgrade(e){e.objectStoreNames.contains(I4)||e.createObjectStore(I4,{keyPath:`id`})}}),R4}async function B4(){return UD?(await ZD(L4)).map(e=>e.value).sort((e,t)=>t.updatedAt-e.updatedAt):(await(await z4()).getAll(I4)).sort((e,t)=>t.updatedAt-e.updatedAt)}async function V4(e){if(UD){await QD(L4+e.id,{id:e.id,lineForm:e.lineForm,updatedAt:e.updatedAt??Date.now()});return}await(await z4()).put(I4,{...e,updatedAt:e.updatedAt??Date.now()})}async function H4(e){if(UD)return $D(L4+e);await(await z4()).delete(I4,e)}var U4=[`segment`,`workout`,`store`];function W4(e,t){let n=e[0]?.id;if(n)return n;let r=/^[\s\S]*?^\s*([A-Za-z_][\w.-]*)\s*=.*$/m.exec(t);return r?r[1]:`custom-${Date.now().toString(36)}`}function G4({defaultScope:e=`segment`,initialId:t}){let[n,r]=(0,V.useState)(`# ${e} calc line
192
204
  segmentVolume = reps * resistance (library) when has(reps) and has(resistance)
193
- `),[i,a]=(0,V.useState)(e),[o,s]=(0,V.useState)([]),[c,l]=(0,V.useState)(),u=(0,V.useMemo)(()=>M2(n,i),[n,i]),d=N4(u.defs,n),f=u.diagnostics.every(e=>e.severity!==`error`)&&u.defs.length>0,p=async()=>{s(await k4())};(0,V.useEffect)(()=>{p()},[]),(0,V.useEffect)(()=>{t&&(async()=>{let e=(await k4()).find(e=>e.id===t);e&&(r(e.lineForm),l(`Loaded "${e.id}".`))})()},[t]);let m=async()=>{if(!f){l(`Cannot save: fix the errors first.`);return}try{await A4({id:d,lineForm:n,updatedAt:Date.now()}),await p(),l(`Saved "${d}".`)}catch(e){console.error(`[CalcAuthoringPanel] save failed:`,e),l(`Save failed: ${e instanceof Error?e.message:String(e)}`)}},h=async e=>{try{await j4(e),await p(),l(`Deleted "${e}".`)}catch(e){console.error(`[CalcAuthoringPanel] delete failed:`,e),l(`Delete failed: ${e instanceof Error?e.message:String(e)}`)}},g=e=>{let t=/^\s*(segment|workout|store)\b/.exec(e.lineForm);t&&a(t[1]),r(e.lineForm),l(`Loaded "${e.id}".`)};return(0,H.jsxs)(`div`,{className:`space-y-3`,"data-testid":`calc-authoring-panel`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Scope`}),(0,H.jsx)(`div`,{className:`flex gap-1`,children:M4.map(e=>(0,H.jsx)(`button`,{onClick:()=>a(e),className:`rounded px-2.5 py-1 text-xs font-medium transition-colors ${i===e?`bg-purple-600 text-white dark:bg-purple-700 dark:text-white`:`bg-muted text-muted-foreground hover:bg-muted/80`}`,children:e},e))}),(0,H.jsx)(`div`,{className:`ml-auto flex gap-2`,children:(0,H.jsx)(`button`,{onClick:m,disabled:!f,className:`rounded bg-signal-positive px-3 py-1 text-xs font-medium text-white dark:text-white disabled:opacity-40`,children:`Save`})})]}),(0,H.jsx)(t4,{value:n,onChange:r,scope:i,autoFocus:!0}),(0,H.jsx)(n4,{analysis:u}),(0,H.jsx)(S4,{scope:i,analysis:u}),c&&(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:c}),o.length>0&&(0,H.jsxs)(`div`,{className:`mt-2`,children:[(0,H.jsx)(`div`,{className:`mb-1 text-[11px] uppercase tracking-wide text-muted-foreground`,children:`Saved user calcs`}),(0,H.jsx)(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,children:o.map(e=>(0,H.jsxs)(`li`,{className:`flex items-center justify-between px-3 py-2 text-sm`,children:[(0,H.jsx)(`button`,{onClick:()=>g(e),className:`text-left font-mono text-purple-300 dark:text-purple-400 hover:underline`,children:e.id}),(0,H.jsx)(`button`,{onClick:()=>h(e.id),className:`text-xs text-muted-foreground hover:text-destructive`,children:`delete`})]},e.id))})]})]})}function F4(){let e=Sn(),[t]=Gt(`zip`),[n]=Gt(`z`),[r]=(0,V.useState)(()=>{let e=window.location.search;return e.includes(`zip=`)||e.includes(`z=`)});return(0,V.useEffect)(()=>{!t&&!n&&!r&&e(`/`,{replace:!0})},[t,n,e,r]),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}async function I4(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 L4(){let e=Sn(),t=mt(),{date:n}=zn(),[r]=Gt(`zip`),[i,a]=(0,V.useState)({state:`loading`});return(0,V.useEffect)(()=>{if(!(t.pathname===`/load/journal`||t.pathname.startsWith(`/load/journal/`)))return;if(!r){e(Q.journal,{replace:!0});return}let i=!1,o=async()=>{try{a({state:`loading`});let t;try{t=await I4(r)}catch(e){console.error(`Failed to decode zip:`,e),a({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{o()}}),Z({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(i)return;let c;if(n){let t=Uj(n);if(!t){a({state:`error`,error:`Invalid date format`}),Z({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),e(Q.journal,{replace:!0});return}c=t.dateKey}else c=Vj();if(i)return;if(Hj(c)){a({state:`pending-confirmation`,content:t,dateKey:c,onConfirmBackdate:async()=>{i||await s(t,c)}});return}await s(t,c)}catch(e){console.error(`Unexpected error in journal zip processor:`,e),i||(a({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{o()}}),Z({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},s=async(t,n)=>{if(!i)try{a({state:`creating`});let r=await Kj.create({journalDate:n,title:n,rawContent:t});i||(a({state:`success`,content:t,dateKey:n}),e(qA(r.id),{replace:!0}))}catch(e){console.error(`Failed to create journal entry:`,e),i||(a({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{s(t,n)}}),Z({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return o(),()=>{i=!0}},[r,n,e]),i}var R4=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(!1),{triggerRef:u,align:d,recompute:f}=uY(`end`),p=async()=>{l(!0);try{await t()}finally{l(!1)}},m=async e=>{l(!0),s(!1);try{await n(e)}finally{l(!1)}},h=e=>{e&&f(),s(e)},g=e?HP(e):`Date`,_=i||c;return(0,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:p,disabled:_,className:U(`flex items-center gap-2 px-3 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,_&&`opacity-60 cursor-not-allowed`),children:[c?(0,H.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,H.jsx)(yn,{className:`h-4 w-4 shrink-0`}),(0,H.jsx)(`span`,{children:`Import Today`})]}),(0,H.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,H.jsxs)(gL,{open:o,onOpenChange:h,children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(`button`,{ref:e=>{u.current=e},type:`button`,title:`Select a date to plan for the future`,className:U(`flex items-center gap-1.5 px-2.5 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,_&&`opacity-60 cursor-not-allowed`),disabled:_,children:[(0,H.jsx)(dt,{className:`h-4 w-4 shrink-0`}),e&&(0,H.jsx)(`span`,{className:`leading-none text-xs`,children:g})]})}),(0,H.jsx)(vL,{align:d,className:`p-0 w-auto`,children:(0,H.jsx)(LJ,{selectedDate:e||null,onDateSelect:m,entryDates:r})})]})]})},z4=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let[i,a]=V.useState(!1),o=VP(new Date(`${e}T00:00:00`));return(0,H.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-50 flex items-center justify-center`,onKeyDown:e=>{e.key===`Escape`&&n()},onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,H.jsx)(`div`,{className:`absolute inset-0 bg-black/50 animate-in fade-in`}),(0,H.jsx)(`div`,{className:`relative z-10 w-full max-w-sm mx-auto px-4 animate-in zoom-in-95 fade-in`,children:(0,H.jsxs)(`div`,{className:`bg-background rounded-lg border border-border shadow-lg`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border`,children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold`,children:`Backdate Journal Entry`}),(0,H.jsx)(`button`,{onClick:n,className:`p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors`,"aria-label":`Close modal`,children:(0,H.jsx)(Te,{className:`h-4 w-4`})})]}),(0,H.jsxs)(`div`,{className:`px-6 py-4 space-y-4`,children:[(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The date you selected is in the past.`}),(0,H.jsxs)(`p`,{className:`text-sm`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Import to: `}),(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:o})]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This will create a journal entry for the selected date. Are you sure you want to proceed?`})]}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex gap-2 justify-end`,children:[(0,H.jsx)(W,{variant:`outline`,onClick:n,disabled:r||i,children:`Cancel`}),(0,H.jsx)(W,{onClick:async()=>{a(!0);try{await t()}finally{a(!1)}},disabled:r||i,className:U(r||i?`opacity-70`:``),children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`inline-block animate-spin mr-2`,children:`⏳`}),`Importing...`]}):`Confirm & Import`})]})]})})]})},B4={h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,H.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,H.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,H.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,H.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,H.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,H.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,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,H.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,H.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,H.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,H.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,H.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,H.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`my-6 border-border/50`})};function V4(){let e=Sn(),t=L4(),[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,H.jsxs)(`div`,{className:`flex flex-col h-screen bg-background`,children:[(0,H.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,H.jsx)(`button`,{onClick:()=>{e(-1)},className:`p-1.5 rounded hover:bg-muted transition-colors text-muted-foreground hover:text-foreground`,title:`Go back`,children:(0,H.jsx)(ar,{className:`h-5 w-5`})}),(0,H.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,H.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,H.jsx)(W,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`?null:(0,H.jsx)(R4,{selectedDate:i,onImportToday:async()=>{u&&await u()},onDateSelect:async e=>{a(e);let t=new Date;t.setHours(0,0,0,0);let n=new Date(e);n.setHours(0,0,0,0),n<t?r(!0):u&&await u()},isLoading:o===`creating`})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`loading`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,H.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,H.jsx)(gt,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,H.jsx)(W,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,H.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,H.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,H.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,H.jsx)(gn,{remarkPlugins:[Un],components:B4,children:s})}):null]}),n&&c&&(0,H.jsx)(z4,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function H4(){let e=mt(),t=Sn(),[n,r]=(0,V.useState)({kind:`loading`}),[i,a]=(0,V.useState)(!1),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null);(0,V.useEffect)(()=>{let n=!0,i=new URLSearchParams(e.search).get(`source`);if(!i){t(Q.catalogs,{replace:!0});return}return r({kind:`loading`}),a(!1),l(null),(async()=>{try{let e=new URL(i);if(e.protocol!==`https:`||e.username||e.password||e.search||e.hash)throw Error(`Enter an HTTPS catalog directory URL without credentials, query parameters, or a fragment.`);e.pathname.endsWith(`/`)||(e.pathname+=`/`);let t=await new ik(e.href).fetchManifest();n&&r({kind:`ready`,url:e.href,manifest:t})}catch(e){n&&r({kind:`error`,message:e instanceof Error?e.message:`Unable to read catalog manifest.`})}})(),()=>{n=!1}},[e.search,t]);let u=async e=>{if(!(n.kind!==`ready`||o)){s(!0),l(null);try{let r=hk().find(e=>nO(new URL(e.url,window.location.href).href)===n.url)??lO(n.manifest.name?.trim()||new URL(n.url).hostname,n.url,{repositoryUrl:n.manifest.repositoryUrl}),a=await Nk(r.id,{subscribe:!1});if(a!==`imported`&&a!==`current`)throw Error(`Catalog import did not complete (${a}). Your existing content was kept.`);if(e){let e=LO(r.id,i),t=NO(r.id,!0);if(!e||!t)throw Error(`Content imported, but subscription preferences could not be saved. Browser storage is unavailable; these choices last this session only.`)}t(`${Q.catalogs}?manage=1`,{replace:!0})}catch(e){l(e instanceof Error?e.message:`Catalog import failed. Your existing content was kept.`)}finally{s(!1)}}};return(0,H.jsxs)(`main`,{className:`mx-auto flex min-h-dvh w-full max-w-2xl flex-col justify-center gap-5 p-6`,"data-testid":`catalog-subscription-intake`,children:[n.kind===`loading`&&(0,H.jsx)(`p`,{role:`status`,children:`Checking catalog manifest…`}),n.kind===`error`&&(0,H.jsx)(`p`,{role:`alert`,className:`break-words text-destructive`,children:n.message}),n.kind===`ready`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`h1`,{className:`text-xl font-semibold`,children:[`Subscribe to `,n.manifest.name?.trim()||new URL(n.url).hostname,`?`]}),(0,H.jsx)(`a`,{href:n.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-sm underline`,children:n.url}),n.manifest.description&&(0,H.jsx)(`p`,{children:n.manifest.description}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Opening this link has not added any content or source. Choose whether to import once or subscribe for future update checks.`}),(0,H.jsxs)(`dl`,{className:`grid grid-cols-2 gap-2 text-sm`,children:[(0,H.jsx)(`dt`,{children:`Published version`}),(0,H.jsxs)(`dd`,{children:[`v`,n.manifest.version]}),(0,H.jsx)(`dt`,{children:`Published at`}),(0,H.jsx)(`dd`,{children:new Date(n.manifest.builtAt).toLocaleString()}),(0,H.jsx)(`dt`,{children:`Schema`}),(0,H.jsxs)(`dd`,{children:[`v`,n.manifest.schema]}),(0,H.jsx)(`dt`,{children:`Chunks`}),(0,H.jsx)(`dd`,{children:n.manifest.chunks.length}),(0,H.jsx)(`dt`,{children:`Catalog items`}),(0,H.jsx)(`dd`,{children:n.manifest.chunks.reduce((e,t)=>e+t.count,0)}),(0,H.jsx)(`dt`,{children:`Download size`}),(0,H.jsxs)(`dd`,{children:[(n.manifest.chunks.reduce((e,t)=>e+t.bytes,0)/1024).toFixed(1),` KB`]})]}),n.manifest.repositoryUrl&&(0,H.jsx)(`a`,{href:n.manifest.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-sm underline`,children:`Git source directory`}),(0,H.jsxs)(`label`,{className:`flex items-start gap-3 rounded-lg border border-border p-4`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),disabled:o,"aria-label":`Auto-sync this catalog`,className:`mt-1 size-4 shrink-0`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`span`,{className:`font-medium`,children:`Auto-sync this catalog`}),(0,H.jsx)(`span`,{className:`mt-1 block text-sm text-muted-foreground`,children:`When subscribed, apply new versions in the background on page load. Off keeps updates manual. Import Once ignores this preference and creates no subscription.`})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,H.jsx)(W,{variant:`outline`,disabled:o,onClick:()=>void u(!1),children:`Import Once`}),(0,H.jsx)(W,{disabled:o,onClick:()=>void u(!0),children:o?`Importing…`:`Import & Subscribe`})]})]}),c&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:c}),(0,H.jsx)(W,{variant:`ghost`,disabled:o,onClick:()=>t(Q.catalogs,{replace:!0}),children:`Decline & Dismiss`})]})}async function U4(e,t,n){let r=await X.getNote(e);if(!r)return;let i=`:session{result:${n}}`;if(r.rawContent.includes(i))return;let a=Object.values(r.blocks??{}).find(e=>e.id===t);if(!a||a.to==null)return;let o=`${r.rawContent.slice(0,a.to)}\n\n\`\`\`query:table\n${i}\n\`\`\`${r.rawContent.slice(a.to)}`;await new ID().updateEntry(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function W4(){let{runtimeId:e}=zn(),t=Sn(),n=(0,V.useRef)(e?VJ.get(e):void 0),r=(0,V.useRef)(null),i=(0,V.useCallback)(async()=>{let t=n.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(r.current=t.captured,t.captured.block):(r.current||=t.snapshot?await hF(t.snapshot,t.block,e,t.origin):await gF(t.noteId,t.block,e,t.origin),r.current.block)},[e]);(0,V.useEffect)(()=>{e&&VJ.delete(e)},[e]);let a=n.current,o=(0,V.useCallback)((n,r)=>!r||!e||!a?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):wV.record({runBlock:a.block,blockId:a.block.id,noteId:a.noteId,resultId:e,data:r,createdAt:r.endTime||Date.now(),...a.origin?{origin:a.origin}:{}}).then(async()=>{if(r.completed){try{await U4(a.noteId,a.block.id,e)}catch{}t(ej(e),{replace:!0})}}),[e,a,t]),s=(0,V.useCallback)(()=>{if(!a){t(`/`);return}if(a.returnTo){t(a.returnTo,{replace:!0});return}t(GJ(ZF(a.noteId)),{replace:!0})},[a,t]);return a?(0,H.jsx)(BG,{block:a.block,prepareRun:i,onClose:s,onCompleteWorkout:o,autoStart:!0}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-red-400`,children:`Runtime not found. Please start the workout from the editor.`})}var G4=null;async function K4(e){(!G4||G4.attempt!==e)&&(G4={attempt:e,promise:iH(gY.content)});try{return await G4.promise}finally{G4?.attempt===e&&(G4=null)}}function q4(){let e=Sn(),[t,n]=(0,V.useState)(!1),[r,i]=(0,V.useState)(0);return(0,V.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await K4(r);t||e(WA(n),{replace:!0})}catch{t||n(!0)}})(),()=>{t=!0}},[e,r]),t?(0,H.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,H.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{n(!1),i(e=>e+1)},children:`Try again`})]}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function J4(){let e=Sn(),t=mt(),[n]=Gt(`zip`),[r]=Gt(`z`),[i]=Gt(`by`),[a]=Gt(`src`);(0,V.useEffect)(()=>{if(t.pathname!==`/load`&&!(t.pathname===`/`&&r))return;if(r){let t=!1;return(async()=>{try{let e=await I4(r);if(e===null)throw Error(`Invalid workout link`);if(t)return;let n=yY(e,i??void 0);if(await aH(n,{reuseKey:`home`,title:`Home playground`}),t)return;SY({content:n,by:i??void 0})}catch(e){console.error(`Failed to decode zip:`,e),t||Z({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}t||e(`/`,{replace:!0})})(),()=>{t=!0}}if(!n)return;let o=!1,s=a&&a.startsWith(`/`)?a:void 0;return(async()=>{try{let t=await I4(n);if(t===null)throw Error(`Invalid workout link`);if(o)return;let r=s?await iH(t,{sourcePath:s}):await iH(t);o||e(WA(r),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),o||(Z({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),e(Q.home,{replace:!0}))}})(),()=>{o=!0}},[n,r,i,a,e,t.pathname])}function Y4(){let{pathname:e,hash:t}=mt(),{scrollToSection:n}=hA();return(0,V.useEffect)(()=>{if(t){let e=t.slice(1);n(e);let r=setTimeout(()=>{n(e)},50);return()=>clearTimeout(r)}window.scrollTo(0,0)},[e,t]),null}function X4(){return J4(),L4(),(0,V.useEffect)(()=>{vD.current().catch(console.error),lD(),nZ()},[]),null}function Z4({settling:e}){return e?(0,H.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading library…`}):(0,H.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The seed corpus is missing the root page. Re-running the seed import usually restores it.`}),(0,H.jsx)(W,{variant:`outline`,size:`sm`,"data-testid":`root-reseed`,onClick:()=>{Ak().then(()=>iD())},children:`Re-seed library`})]})}function Q4(){let e=(0,V.useRef)(()=>{}),t=jP(),n=eZ(),r=(0,V.useMemo)(()=>eP(()=>e.current(),t),[t]);return(0,H.jsx)(Ai,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,H.jsx)(ey,{children:(0,H.jsx)(Bk,{children:(0,H.jsx)(Uk,{children:(0,H.jsx)(ek,{children:(0,H.jsx)(Mt,{children:(0,H.jsxs)(i,{children:[(0,H.jsx)(X4,{}),(0,H.jsx)(uA,{}),(0,H.jsxs)(_A,{tree:r,children:[(0,H.jsx)(Y4,{}),(0,H.jsxs)(Xt,{children:[(0,H.jsx)(z,{path:`*`,element:t.some(({route:e})=>e===Q.home)?(0,H.jsx)(k0,{}):(0,H.jsx)(Z4,{settling:n===`preparing`})}),(0,H.jsx)(z,{path:`/proto/calc-authoring`,element:(0,H.jsx)(d2,{})}),(0,H.jsx)(z,{path:`/proto/query-block-composer`,element:(0,H.jsx)(O2,{})}),(0,H.jsx)(z,{path:`/settings`,element:(0,H.jsx)(_n,{to:`/settings/appearance`,replace:!0})}),(0,H.jsx)(z,{path:`/settings/appearance`,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsProfile,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsData,element:(0,H.jsx)(_n,{to:Q.settingsStorage,replace:!0})}),(0,H.jsx)(z,{path:Q.settingsDatabase,element:(0,H.jsx)(_n,{to:Q.settingsStorage,replace:!0})}),(0,H.jsx)(z,{path:Q.settingsStorage,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsSync,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/settings/system`,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsQueries,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsTags,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/settings/library/calcs`,element:(0,H.jsx)(`div`,{className:`p-6`,children:(0,H.jsx)(P4,{})})}),(0,H.jsx)(z,{path:`/legacy`,element:(0,H.jsx)(m0,{})}),(0,H.jsx)(z,{path:`/syntax`,element:(0,H.jsx)(O0,{})}),(0,H.jsx)(z,{path:`/chapters/basics`,element:(0,H.jsx)(_n,{to:`/guide/start`,replace:!0})}),(0,H.jsx)(z,{path:`/chapters/sequences`,element:(0,H.jsx)(_n,{to:`/guide/start`,replace:!0})}),(0,H.jsx)(z,{path:`/chapters/protocols`,element:(0,H.jsx)(_n,{to:`/guide/protocols`,replace:!0})}),(0,H.jsx)(z,{path:`/challenge`,element:(0,H.jsx)(_n,{to:`/`,replace:!0})}),(0,H.jsx)(z,{path:Q.plan,element:(0,H.jsx)(e0,{})}),(0,H.jsx)(z,{path:Q.feeds,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feed,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feedDetail,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feedItem,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.catalogs,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.subscribe,element:(0,H.jsx)(H4,{})}),(0,H.jsx)(z,{path:Q.collections,element:(0,H.jsx)(q1,{})}),(0,H.jsx)(z,{path:`/collections/:slug`,element:(0,H.jsx)(K1,{})}),(0,H.jsx)(z,{path:`/collections/:slug/:target`,element:(0,H.jsx)(K1,{})}),(0,H.jsx)(z,{path:Q.collection,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.collectionTarget,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.load,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(F4,{})})}),(0,H.jsx)(z,{path:Q.loadJournal,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(V4,{})})}),(0,H.jsx)(z,{path:Q.loadJournalDate,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(V4,{})})}),(0,H.jsx)(z,{path:Q.playgroundRoot,element:(0,H.jsx)(q4,{})}),(0,H.jsx)(z,{path:Q.playground,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.playgrounds,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.notePlaygroundAlias,element:(0,H.jsx)(W1,{})}),(0,H.jsx)(z,{path:Q.note,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journalNote,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journalEntry,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.noteById,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journal,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.pages,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.run,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(W4,{})})}),(0,H.jsx)(z,{path:Q.tracker,element:(0,H.jsx)(Q1,{})}),(0,H.jsx)(z,{path:`/results`,element:(0,H.jsx)(Y1,{})}),(0,H.jsx)(z,{path:`/results/segments`,element:(0,H.jsx)(X1,{})}),(0,H.jsx)(z,{path:Q.sessionDetail,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.sessions,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.sessionDate,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/review/:runtimeId`,element:(0,H.jsx)($1,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review`,element:(0,H.jsx)($1,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review/:sectionId`,element:(0,H.jsx)($1,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,H.jsx)($1,{})}),(0,H.jsx)(z,{path:`/workout/:category/:name`,element:(0,H.jsx)(G1,{})}),(0,H.jsx)(z,{path:Q.efforts,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.effort,element:(0,H.jsx)(J1,{})}),(0,H.jsx)(z,{path:Q.effortSlug,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.equipment,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.equipmentSlug,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboard,element:(0,H.jsx)(Z1,{})}),(0,H.jsx)(z,{path:Q.dashboards,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboardView,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboardSlug,element:(0,H.jsx)(H1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.analytics,element:(0,H.jsx)(_n,{to:`/dashboards`,replace:!0})}),(0,H.jsx)(z,{path:Q.analyticsExplorer,element:(0,H.jsx)(t0,{})}),t.map(({route:t})=>(0,H.jsx)(z,{path:t,element:(0,H.jsx)(H1,{searchHandlerRef:e})},t))]}),(0,H.jsx)(o0,{})]})]})})})})})})})}function $4({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e);return hD(),(0,H.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-semibold`,children:`The API data store could not be opened.`}),(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,H.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,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,H.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 e3(){let e=(0,V.useSyncExternalStore)(yb,vb),t=e.phase===`updating`;return(0,H.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,H.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var t3=(0,Oi.createRoot)(document.getElementById(`root`));function n3(){let[e,t]=(0,V.useState)(!1),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(0),o=(0,V.useSyncExternalStore)(yb,vb);return(0,V.useEffect)(()=>{let e=!1,n;return CD().then(()=>UD?JD():void 0).then(()=>{e||(n=ED(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),n?(0,H.jsx)($4,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,H.jsx)(e3,{}):e?(0,H.jsx)(Q4,{}):(0,H.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading…`})}t3.render((0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(n3,{})}));export{UR as t};
194
- //# sourceMappingURL=main-CCnQ9nH-.js.map
205
+ `),[i,a]=(0,V.useState)(e),[o,s]=(0,V.useState)([]),[c,l]=(0,V.useState)(),u=(0,V.useMemo)(()=>U2(n,i),[n,i]),d=W4(u.defs,n),f=u.diagnostics.every(e=>e.severity!==`error`)&&u.defs.length>0,p=async()=>{s(await B4())};(0,V.useEffect)(()=>{p()},[]),(0,V.useEffect)(()=>{t&&(async()=>{let e=(await B4()).find(e=>e.id===t);e&&(r(e.lineForm),l(`Loaded "${e.id}".`))})()},[t]);let m=async()=>{if(!f){l(`Cannot save: fix the errors first.`);return}try{await V4({id:d,lineForm:n,updatedAt:Date.now()}),await p(),l(`Saved "${d}".`)}catch(e){console.error(`[CalcAuthoringPanel] save failed:`,e),l(`Save failed: ${e instanceof Error?e.message:String(e)}`)}},h=async e=>{try{await H4(e),await p(),l(`Deleted "${e}".`)}catch(e){console.error(`[CalcAuthoringPanel] delete failed:`,e),l(`Delete failed: ${e instanceof Error?e.message:String(e)}`)}},g=e=>{let t=/^\s*(segment|workout|store)\b/.exec(e.lineForm);t&&a(t[1]),r(e.lineForm),l(`Loaded "${e.id}".`)};return(0,H.jsxs)(`div`,{className:`space-y-3`,"data-testid":`calc-authoring-panel`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Scope`}),(0,H.jsx)(`div`,{className:`flex gap-1`,children:U4.map(e=>(0,H.jsx)(`button`,{onClick:()=>a(e),className:`rounded px-2.5 py-1 text-xs font-medium transition-colors ${i===e?`bg-purple-600 text-white dark:bg-purple-700 dark:text-white`:`bg-muted text-muted-foreground hover:bg-muted/80`}`,children:e},e))}),(0,H.jsx)(`div`,{className:`ml-auto flex gap-2`,children:(0,H.jsx)(`button`,{onClick:m,disabled:!f,className:`rounded bg-signal-positive px-3 py-1 text-xs font-medium text-white dark:text-white disabled:opacity-40`,children:`Save`})})]}),(0,H.jsx)(f4,{value:n,onChange:r,scope:i,autoFocus:!0}),(0,H.jsx)(p4,{analysis:u}),(0,H.jsx)(N4,{scope:i,analysis:u}),c&&(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:c}),o.length>0&&(0,H.jsxs)(`div`,{className:`mt-2`,children:[(0,H.jsx)(`div`,{className:`mb-1 text-[11px] uppercase tracking-wide text-muted-foreground`,children:`Saved user calcs`}),(0,H.jsx)(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,children:o.map(e=>(0,H.jsxs)(`li`,{className:`flex items-center justify-between px-3 py-2 text-sm`,children:[(0,H.jsx)(`button`,{onClick:()=>g(e),className:`text-left font-mono text-purple-300 dark:text-purple-400 hover:underline`,children:e.id}),(0,H.jsx)(`button`,{onClick:()=>h(e.id),className:`text-xs text-muted-foreground hover:text-destructive`,children:`delete`})]},e.id))})]})]})}function K4(){let e=Sn(),[t]=Gt(`zip`),[n]=Gt(`z`),[r]=(0,V.useState)(()=>{let e=window.location.search;return e.includes(`zip=`)||e.includes(`z=`)});return(0,V.useEffect)(()=>{!t&&!n&&!r&&e(`/`,{replace:!0})},[t,n,e,r]),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}async function q4(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 J4(){let e=Sn(),t=mt(),{date:n}=zn(),[r]=Gt(`zip`),[i,a]=(0,V.useState)({state:`loading`});return(0,V.useEffect)(()=>{if(!(t.pathname===`/load/journal`||t.pathname.startsWith(`/load/journal/`)))return;if(!r){e(Q.journal,{replace:!0});return}let i=!1,o=async()=>{try{a({state:`loading`});let t;try{t=await q4(r)}catch(e){console.error(`Failed to decode zip:`,e),a({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{o()}}),Z({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(i)return;let c;if(n){let t=Uj(n);if(!t){a({state:`error`,error:`Invalid date format`}),Z({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),e(Q.journal,{replace:!0});return}c=t.dateKey}else c=Vj();if(i)return;if(Hj(c)){a({state:`pending-confirmation`,content:t,dateKey:c,onConfirmBackdate:async()=>{i||await s(t,c)}});return}await s(t,c)}catch(e){console.error(`Unexpected error in journal zip processor:`,e),i||(a({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{o()}}),Z({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},s=async(t,n)=>{if(!i)try{a({state:`creating`});let r=await Kj.create({journalDate:n,title:n,rawContent:t});i||(a({state:`success`,content:t,dateKey:n}),e(qA(r.id),{replace:!0}))}catch(e){console.error(`Failed to create journal entry:`,e),i||(a({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{s(t,n)}}),Z({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return o(),()=>{i=!0}},[r,n,e]),i}var Y4=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(!1),{triggerRef:u,align:d,recompute:f}=xY(`end`),p=async()=>{l(!0);try{await t()}finally{l(!1)}},m=async e=>{l(!0),s(!1);try{await n(e)}finally{l(!1)}},h=e=>{e&&f(),s(e)},g=e?HP(e):`Date`,_=i||c;return(0,H.jsxs)(`div`,{className:U(`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,H.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:p,disabled:_,className:U(`flex items-center gap-2 px-3 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,_&&`opacity-60 cursor-not-allowed`),children:[c?(0,H.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,H.jsx)(yn,{className:`h-4 w-4 shrink-0`}),(0,H.jsx)(`span`,{children:`Import Today`})]}),(0,H.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,H.jsxs)(gL,{open:o,onOpenChange:h,children:[(0,H.jsx)(_L,{asChild:!0,children:(0,H.jsxs)(`button`,{ref:e=>{u.current=e},type:`button`,title:`Select a date to plan for the future`,className:U(`flex items-center gap-1.5 px-2.5 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,_&&`opacity-60 cursor-not-allowed`),disabled:_,children:[(0,H.jsx)(dt,{className:`h-4 w-4 shrink-0`}),e&&(0,H.jsx)(`span`,{className:`leading-none text-xs`,children:g})]})}),(0,H.jsx)(vL,{align:d,className:`p-0 w-auto`,children:(0,H.jsx)(JJ,{selectedDate:e||null,onDateSelect:m,entryDates:r})})]})]})},X4=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let[i,a]=V.useState(!1),o=VP(new Date(`${e}T00:00:00`));return(0,H.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-50 flex items-center justify-center`,onKeyDown:e=>{e.key===`Escape`&&n()},onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,H.jsx)(`div`,{className:`absolute inset-0 bg-black/50 animate-in fade-in`}),(0,H.jsx)(`div`,{className:`relative z-10 w-full max-w-sm mx-auto px-4 animate-in zoom-in-95 fade-in`,children:(0,H.jsxs)(`div`,{className:`bg-background rounded-lg border border-border shadow-lg`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border`,children:[(0,H.jsx)(`h2`,{className:`text-base font-semibold`,children:`Backdate Journal Entry`}),(0,H.jsx)(`button`,{onClick:n,className:`p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors`,"aria-label":`Close modal`,children:(0,H.jsx)(Te,{className:`h-4 w-4`})})]}),(0,H.jsxs)(`div`,{className:`px-6 py-4 space-y-4`,children:[(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The date you selected is in the past.`}),(0,H.jsxs)(`p`,{className:`text-sm`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`Import to: `}),(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:o})]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This will create a journal entry for the selected date. Are you sure you want to proceed?`})]}),(0,H.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex gap-2 justify-end`,children:[(0,H.jsx)(W,{variant:`outline`,onClick:n,disabled:r||i,children:`Cancel`}),(0,H.jsx)(W,{onClick:async()=>{a(!0);try{await t()}finally{a(!1)}},disabled:r||i,className:U(r||i?`opacity-70`:``),children:i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`inline-block animate-spin mr-2`,children:`⏳`}),`Importing...`]}):`Confirm & Import`})]})]})})]})},Z4={h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,H.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,H.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,H.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,H.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,H.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,H.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,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,H.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,H.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,H.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,H.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,H.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,H.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`my-6 border-border/50`})};function Q4(){let e=Sn(),t=J4(),[n,r]=(0,V.useState)(!1),[i,a]=(0,V.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,H.jsxs)(`div`,{className:`flex flex-col h-screen bg-background`,children:[(0,H.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,H.jsx)(`button`,{onClick:()=>{e(-1)},className:`p-1.5 rounded hover:bg-muted transition-colors text-muted-foreground hover:text-foreground`,title:`Go back`,children:(0,H.jsx)(ar,{className:`h-5 w-5`})}),(0,H.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,H.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,H.jsx)(W,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`?null:(0,H.jsx)(Y4,{selectedDate:i,onImportToday:async()=>{u&&await u()},onDateSelect:async e=>{a(e);let t=new Date;t.setHours(0,0,0,0);let n=new Date(e);n.setHours(0,0,0,0),n<t?r(!0):u&&await u()},isLoading:o===`creating`})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`loading`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,H.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,H.jsx)(gt,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,H.jsx)(W,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,H.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,H.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,H.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,H.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,H.jsxs)(`div`,{className:`text-center`,children:[(0,H.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,H.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,H.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,H.jsx)(gn,{remarkPlugins:[Un],components:Z4,children:s})}):null]}),n&&c&&(0,H.jsx)(X4,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function $4(){let e=mt(),t=Sn(),[n,r]=(0,V.useState)({kind:`loading`}),[i,a]=(0,V.useState)(!1),[o,s]=(0,V.useState)(!1),[c,l]=(0,V.useState)(null);(0,V.useEffect)(()=>{let n=!0,i=new URLSearchParams(e.search).get(`source`);if(!i){t(Q.catalogs,{replace:!0});return}return r({kind:`loading`}),a(!1),l(null),(async()=>{try{let e=new URL(i);if(e.protocol!==`https:`||e.username||e.password||e.search||e.hash)throw Error(`Enter an HTTPS catalog directory URL without credentials, query parameters, or a fragment.`);e.pathname.endsWith(`/`)||(e.pathname+=`/`);let t=await new ik(e.href).fetchManifest();n&&r({kind:`ready`,url:e.href,manifest:t})}catch(e){n&&r({kind:`error`,message:e instanceof Error?e.message:`Unable to read catalog manifest.`})}})(),()=>{n=!1}},[e.search,t]);let u=async e=>{if(!(n.kind!==`ready`||o)){s(!0),l(null);try{let r=hk().find(e=>nO(new URL(e.url,window.location.href).href)===n.url)??lO(n.manifest.name?.trim()||new URL(n.url).hostname,n.url,{repositoryUrl:n.manifest.repositoryUrl}),a=await Nk(r.id,{subscribe:!1});if(a!==`imported`&&a!==`current`)throw Error(`Catalog import did not complete (${a}). Your existing content was kept.`);if(e){let e=LO(r.id,i),t=NO(r.id,!0);if(!e||!t)throw Error(`Content imported, but subscription preferences could not be saved. Browser storage is unavailable; these choices last this session only.`)}t(`${Q.catalogs}?manage=1`,{replace:!0})}catch(e){l(e instanceof Error?e.message:`Catalog import failed. Your existing content was kept.`)}finally{s(!1)}}};return(0,H.jsxs)(`main`,{className:`mx-auto flex min-h-dvh w-full max-w-2xl flex-col justify-center gap-5 p-6`,"data-testid":`catalog-subscription-intake`,children:[n.kind===`loading`&&(0,H.jsx)(`p`,{role:`status`,children:`Checking catalog manifest…`}),n.kind===`error`&&(0,H.jsx)(`p`,{role:`alert`,className:`break-words text-destructive`,children:n.message}),n.kind===`ready`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`h1`,{className:`text-xl font-semibold`,children:[`Subscribe to `,n.manifest.name?.trim()||new URL(n.url).hostname,`?`]}),(0,H.jsx)(`a`,{href:n.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-sm underline`,children:n.url}),n.manifest.description&&(0,H.jsx)(`p`,{children:n.manifest.description}),(0,H.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Opening this link has not added any content or source. Choose whether to import once or subscribe for future update checks.`}),(0,H.jsxs)(`dl`,{className:`grid grid-cols-2 gap-2 text-sm`,children:[(0,H.jsx)(`dt`,{children:`Published version`}),(0,H.jsxs)(`dd`,{children:[`v`,n.manifest.version]}),(0,H.jsx)(`dt`,{children:`Published at`}),(0,H.jsx)(`dd`,{children:new Date(n.manifest.builtAt).toLocaleString()}),(0,H.jsx)(`dt`,{children:`Schema`}),(0,H.jsxs)(`dd`,{children:[`v`,n.manifest.schema]}),(0,H.jsx)(`dt`,{children:`Chunks`}),(0,H.jsx)(`dd`,{children:n.manifest.chunks.length}),(0,H.jsx)(`dt`,{children:`Catalog items`}),(0,H.jsx)(`dd`,{children:n.manifest.chunks.reduce((e,t)=>e+t.count,0)}),(0,H.jsx)(`dt`,{children:`Download size`}),(0,H.jsxs)(`dd`,{children:[(n.manifest.chunks.reduce((e,t)=>e+t.bytes,0)/1024).toFixed(1),` KB`]})]}),n.manifest.repositoryUrl&&(0,H.jsx)(`a`,{href:n.manifest.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-sm underline`,children:`Git source directory`}),(0,H.jsxs)(`label`,{className:`flex items-start gap-3 rounded-lg border border-border p-4`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),disabled:o,"aria-label":`Auto-sync this catalog`,className:`mt-1 size-4 shrink-0`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`span`,{className:`font-medium`,children:`Auto-sync this catalog`}),(0,H.jsx)(`span`,{className:`mt-1 block text-sm text-muted-foreground`,children:`When subscribed, apply new versions in the background on page load. Off keeps updates manual. Import Once ignores this preference and creates no subscription.`})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,H.jsx)(W,{variant:`outline`,disabled:o,onClick:()=>void u(!1),children:`Import Once`}),(0,H.jsx)(W,{disabled:o,onClick:()=>void u(!0),children:o?`Importing…`:`Import & Subscribe`})]})]}),c&&(0,H.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:c}),(0,H.jsx)(W,{variant:`ghost`,disabled:o,onClick:()=>t(Q.catalogs,{replace:!0}),children:`Decline & Dismiss`})]})}async function e3(e,t,n){let r=await X.getNote(e);if(!r)return;let i=`:session{result:${n}}`;if(r.rawContent.includes(i))return;let a=Object.values(r.blocks??{}).find(e=>e.id===t);if(!a||a.to==null)return;let o=`${r.rawContent.slice(0,a.to)}\n\n\`\`\`query:table\n${i}\n\`\`\`${r.rawContent.slice(a.to)}`;await new ID().updateEntry(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function t3(){let{runtimeId:e}=zn(),t=Sn(),n=(0,V.useRef)(e?QJ.get(e):void 0),r=(0,V.useRef)(null),i=(0,V.useCallback)(async()=>{let t=n.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(r.current=t.captured,t.captured.block):(r.current||=t.snapshot?await hF(t.snapshot,t.block,e,t.origin):await gF(t.noteId,t.block,e,t.origin),r.current.block)},[e]);(0,V.useEffect)(()=>{e&&QJ.delete(e)},[e]);let a=n.current,o=(0,V.useCallback)((n,r)=>!r||!e||!a?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):FV.record({runBlock:a.block,blockId:a.block.id,noteId:a.noteId,resultId:e,data:r,createdAt:r.endTime||Date.now(),...a.origin?{origin:a.origin}:{}}).then(async()=>{if(r.completed){try{await e3(a.noteId,a.block.id,e)}catch{}t(ej(e),{replace:!0})}}),[e,a,t]),s=(0,V.useCallback)(()=>{if(!a){t(`/`);return}if(a.returnTo){t(a.returnTo,{replace:!0});return}t(nY(ZF(a.noteId)),{replace:!0})},[a,t]);return a?(0,H.jsx)(ZG,{block:a.block,prepareRun:i,onClose:s,onCompleteWorkout:o,autoStart:!0}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-red-400`,children:`Runtime not found. Please start the workout from the editor.`})}var n3=null;async function r3(e){(!n3||n3.attempt!==e)&&(n3={attempt:e,promise:hH(DY.content)});try{return await n3.promise}finally{n3?.attempt===e&&(n3=null)}}function i3(){let e=Sn(),[t,n]=(0,V.useState)(!1),[r,i]=(0,V.useState)(0);return(0,V.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await r3(r);t||e(WA(n),{replace:!0})}catch{t||n(!0)}})(),()=>{t=!0}},[e,r]),t?(0,H.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,H.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,H.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{n(!1),i(e=>e+1)},children:`Try again`})]}):(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function a3(){let e=Sn(),t=mt(),[n]=Gt(`zip`),[r]=Gt(`z`),[i]=Gt(`by`),[a]=Gt(`src`);(0,V.useEffect)(()=>{if(t.pathname!==`/load`&&!(t.pathname===`/`&&r))return;if(r){let t=!1;return(async()=>{try{let e=await q4(r);if(e===null)throw Error(`Invalid workout link`);if(t)return;let n=AY(e,i??void 0);if(await gH(n,{reuseKey:`home`,title:`Home playground`}),t)return;NY({content:n,by:i??void 0})}catch(e){console.error(`Failed to decode zip:`,e),t||Z({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}t||e(`/`,{replace:!0})})(),()=>{t=!0}}if(!n)return;let o=!1,s=a&&a.startsWith(`/`)?a:void 0;return(async()=>{try{let t=await q4(n);if(t===null)throw Error(`Invalid workout link`);if(o)return;let r=s?await hH(t,{sourcePath:s}):await hH(t);o||e(WA(r),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),o||(Z({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),e(Q.home,{replace:!0}))}})(),()=>{o=!0}},[n,r,i,a,e,t.pathname])}function o3(){let{pathname:e,hash:t}=mt(),{scrollToSection:n}=hA();return(0,V.useEffect)(()=>{if(t){let e=t.slice(1);n(e);let r=setTimeout(()=>{n(e)},50);return()=>clearTimeout(r)}window.scrollTo(0,0)},[e,t]),null}function s3(){return a3(),J4(),(0,V.useEffect)(()=>{vD.current().catch(console.error),lD(),pZ()},[]),null}function c3({settling:e}){return e?(0,H.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading library…`}):(0,H.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The seed corpus is missing the root page. Re-running the seed import usually restores it.`}),(0,H.jsx)(W,{variant:`outline`,size:`sm`,"data-testid":`root-reseed`,onClick:()=>{Ak().then(()=>iD())},children:`Re-seed library`})]})}function l3(){let e=(0,V.useRef)(()=>{}),t=jP(),n=dZ(),r=(0,V.useMemo)(()=>eP(()=>e.current(),t),[t]);return(0,H.jsx)(Ai,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,H.jsx)(ey,{children:(0,H.jsx)(Bk,{children:(0,H.jsx)(Uk,{children:(0,H.jsx)(ek,{children:(0,H.jsx)(Mt,{children:(0,H.jsxs)(i,{children:[(0,H.jsx)(s3,{}),(0,H.jsx)(uA,{}),(0,H.jsxs)(_A,{tree:r,children:[(0,H.jsx)(o3,{}),(0,H.jsxs)(Xt,{children:[(0,H.jsx)(z,{path:`*`,element:t.some(({route:e})=>e===Q.home)?(0,H.jsx)(B0,{}):(0,H.jsx)(c3,{settling:n===`preparing`})}),(0,H.jsx)(z,{path:`/proto/calc-authoring`,element:(0,H.jsx)(S2,{})}),(0,H.jsx)(z,{path:`/proto/query-block-composer`,element:(0,H.jsx)(z2,{})}),(0,H.jsx)(z,{path:`/settings`,element:(0,H.jsx)(_n,{to:`/settings/appearance`,replace:!0})}),(0,H.jsx)(z,{path:`/settings/appearance`,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsProfile,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsData,element:(0,H.jsx)(_n,{to:Q.settingsStorage,replace:!0})}),(0,H.jsx)(z,{path:Q.settingsDatabase,element:(0,H.jsx)(_n,{to:Q.settingsStorage,replace:!0})}),(0,H.jsx)(z,{path:Q.settingsStorage,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsSync,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/settings/system`,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsQueries,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.settingsTags,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/settings/library/calcs`,element:(0,H.jsx)(`div`,{className:`p-6`,children:(0,H.jsx)(G4,{})})}),(0,H.jsx)(z,{path:`/legacy`,element:(0,H.jsx)(T0,{})}),(0,H.jsx)(z,{path:`/syntax`,element:(0,H.jsx)(z0,{})}),(0,H.jsx)(z,{path:`/chapters/basics`,element:(0,H.jsx)(_n,{to:`/guide/start`,replace:!0})}),(0,H.jsx)(z,{path:`/chapters/sequences`,element:(0,H.jsx)(_n,{to:`/guide/start`,replace:!0})}),(0,H.jsx)(z,{path:`/chapters/protocols`,element:(0,H.jsx)(_n,{to:`/guide/protocols`,replace:!0})}),(0,H.jsx)(z,{path:`/challenge`,element:(0,H.jsx)(_n,{to:`/`,replace:!0})}),(0,H.jsx)(z,{path:Q.plan,element:(0,H.jsx)(d0,{})}),(0,H.jsx)(z,{path:Q.feeds,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feed,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feedDetail,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.feedItem,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.catalogs,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.subscribe,element:(0,H.jsx)($4,{})}),(0,H.jsx)(z,{path:Q.collections,element:(0,H.jsx)(i0,{})}),(0,H.jsx)(z,{path:`/collections/:slug`,element:(0,H.jsx)(r0,{})}),(0,H.jsx)(z,{path:`/collections/:slug/:target`,element:(0,H.jsx)(r0,{})}),(0,H.jsx)(z,{path:Q.collection,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.collectionTarget,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.load,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(K4,{})})}),(0,H.jsx)(z,{path:Q.loadJournal,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(Q4,{})})}),(0,H.jsx)(z,{path:Q.loadJournalDate,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(Q4,{})})}),(0,H.jsx)(z,{path:Q.playgroundRoot,element:(0,H.jsx)(i3,{})}),(0,H.jsx)(z,{path:Q.playground,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.playgrounds,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.notePlaygroundAlias,element:(0,H.jsx)(t0,{})}),(0,H.jsx)(z,{path:Q.note,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journalNote,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journalEntry,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.noteById,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.journal,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.pages,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.run,element:(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,H.jsx)(t3,{})})}),(0,H.jsx)(z,{path:Q.tracker,element:(0,H.jsx)(l0,{})}),(0,H.jsx)(z,{path:`/results`,element:(0,H.jsx)(o0,{})}),(0,H.jsx)(z,{path:`/results/segments`,element:(0,H.jsx)(s0,{})}),(0,H.jsx)(z,{path:Q.sessionDetail,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.sessions,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.sessionDate,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:`/review/:runtimeId`,element:(0,H.jsx)(u0,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review`,element:(0,H.jsx)(u0,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review/:sectionId`,element:(0,H.jsx)(u0,{})}),(0,H.jsx)(z,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,H.jsx)(u0,{})}),(0,H.jsx)(z,{path:`/workout/:category/:name`,element:(0,H.jsx)(n0,{})}),(0,H.jsx)(z,{path:Q.efforts,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.effort,element:(0,H.jsx)(a0,{})}),(0,H.jsx)(z,{path:Q.effortSlug,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.equipment,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.equipmentSlug,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboard,element:(0,H.jsx)(c0,{})}),(0,H.jsx)(z,{path:Q.dashboards,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboardView,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.dashboardSlug,element:(0,H.jsx)($1,{searchHandlerRef:e})}),(0,H.jsx)(z,{path:Q.analytics,element:(0,H.jsx)(_n,{to:`/dashboards`,replace:!0})}),(0,H.jsx)(z,{path:Q.analyticsExplorer,element:(0,H.jsx)(f0,{})}),t.map(({route:t})=>(0,H.jsx)(z,{path:t,element:(0,H.jsx)($1,{searchHandlerRef:e})},t))]}),(0,H.jsx)(_0,{})]})]})})})})})})})}function u3({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e);return hD(),(0,H.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,H.jsx)(`p`,{className:`text-sm font-semibold`,children:`The API data store could not be opened.`}),(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,H.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,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,H.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 d3(){let e=(0,V.useSyncExternalStore)(yb,vb),t=e.phase===`updating`;return(0,H.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,H.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,H.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var f3=(0,Oi.createRoot)(document.getElementById(`root`));function p3(){let[e,t]=(0,V.useState)(!1),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(0),o=(0,V.useSyncExternalStore)(yb,vb);return(0,V.useEffect)(()=>{let e=!1,n;return CD().then(()=>UD?JD():void 0).then(()=>{e||(n=ED(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),n?(0,H.jsx)(u3,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,H.jsx)(d3,{}):e?(0,H.jsx)(l3,{}):(0,H.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading…`})}f3.render((0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(p3,{})}));export{UR as t};
206
+ //# sourceMappingURL=main-CqewmQAx.js.map