cctally 1.43.3 → 1.44.0

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.
@@ -15,7 +15,7 @@ Error generating stack: `+e.message+`
15
15
  `]},t):e.type===`exit`?(0,U.jsxs)(`span`,{className:`update-stream-exit`,children:[`(exited rc=${e.rc??`?`})`,`
16
16
  `]},t):(0,U.jsxs)(`span`,{className:`update-stream-line`,children:[e.data??``,`
17
17
  `]},t))]})}var Jo=3e3,Yo=1e3;function Xo(e){if(e==null)return`0s`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Zo(){let e=(0,_.useSyncExternalStore)(V,()=>B().update),t=e.runId,n=e.startedAt,r=e.state?.update_command??``,i=e.state?.latest_version??``,[,a]=(0,_.useState)(0);(0,_.useEffect)(()=>{let e=window.setInterval(()=>a(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);let o=(0,_.useRef)(!1);return(0,_.useEffect)(()=>{if(!t)return;let e=null,n=null,r=null,i=!1;o.current=!0;function a(){r!=null&&(window.clearTimeout(r),r=null),o.current=!1}function s(t,n){a();let r={};try{t instanceof MessageEvent&&typeof t.data==`string`&&(r=JSON.parse(t.data))}catch{}if(H({type:`APPEND_UPDATE_STREAM`,event:{type:n,data:typeof r.data==`string`?r.data:void 0,name:typeof r.name==`string`?r.name:void 0,rc:typeof r.rc==`number`?r.rc:void 0,step:typeof r.step==`string`?r.step:void 0,message:typeof r.message==`string`?r.message:void 0,ts:typeof r.ts==`number`?r.ts:void 0}}),n===`exit`){let e=typeof r.rc==`number`?r.rc:-1;e!==0&&H({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`subprocess exited with rc=${e}`})}else n===`execvp`?H({type:`SET_UPDATE_STATUS`,status:`success`}):n===`error_event`?H({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:typeof r.message==`string`?r.message:`update worker error`}):n===`done`&&(e&&=(e.close(),null))}function c(){n??=window.setInterval(async()=>{if(!i)try{let e=await fetch(`/api/update/status`);if(!e.ok)return;let t=await e.json(),r=t?.current_run_id??null,i=t?.state??{};if(r===null){let e=i?.current_version,t=i?.latest_version,r=B().update;typeof e==`string`&&typeof t==`string`&&e===t?H({type:`SET_UPDATE_STATUS`,status:`success`}):r.status===`running`&&H({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`update worker exited (stream unavailable)`}),r.stream.length===0&&H({type:`APPEND_UPDATE_STREAM`,event:{type:`stdout`,data:`(SSE stream unavailable; install completed in background — see ~/.local/share/cctally/update.log for full output)`}}),n!=null&&(window.clearInterval(n),n=null)}}catch{}},Yo)}r=window.setTimeout(()=>{i||o.current&&(o.current=!1,e&&=(e.close(),null),c())},Jo);try{e=new EventSource(`/api/update/stream/${encodeURIComponent(t)}`),e.addEventListener(`message`,e=>s(e,`stdout`)),[`stdout`,`stderr`,`step`,`exit`,`execvp`,`error_event`,`done`,`heartbeat`].forEach(t=>{e.addEventListener(t,e=>s(e,t))}),e.onerror=()=>{o.current&&(a(),e&&=(e.close(),null),c())}}catch{a(),c()}return()=>{i=!0,r!=null&&(window.clearTimeout(r),r=null),n!=null&&(window.clearInterval(n),n=null),e&&=(e.close(),null),o.current=!1,et()}},[t]),(0,U.jsxs)(`div`,{className:`update-modal-body`,children:[(0,U.jsxs)(`div`,{className:`update-running-row`,children:[(0,U.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,U.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:r||`updating cctally`}),(0,U.jsxs)(`span`,{className:`update-elapsed`,children:[Xo(n),` elapsed`]})]}),(0,U.jsx)(qo,{events:e.stream}),(0,U.jsxs)(`p`,{className:`update-stream-cap`,children:[`Output streams over SSE · press Esc to hide (install continues to `,i||`latest`,`)`]})]})}var Qo=1500;function $o(e){if(e==null)return`—`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function es(){let e=(0,_.useSyncExternalStore)(V,()=>B().update),t=e.startedAt,n=e.state?.update_command??``,r=e.state?.latest_version??``;return(0,_.useEffect)(()=>{let e=window.setInterval(()=>{et()},Qo);return()=>window.clearInterval(e)},[]),(0,U.jsxs)(`div`,{className:`update-modal-body`,children:[(0,U.jsxs)(`div`,{className:`update-running-row update-running-row-success`,children:[(0,U.jsx)(`span`,{className:`update-check`,"aria-hidden":`true`,children:`✓`}),(0,U.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:n||`cctally`}),(0,U.jsxs)(`span`,{className:`update-elapsed`,children:[`finished in `,$o(t)]})]}),(0,U.jsxs)(`div`,{className:`update-row-label`,children:[`Restarting dashboard on the new code`,r?` (${r})`:``,`…`]}),(0,U.jsxs)(`div`,{className:`update-running-row`,children:[(0,U.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,U.jsx)(`span`,{className:`update-success-reconnect`,children:`reconnecting (this page will refresh in a moment)`})]})]})}var ts=12;function ns(e,t){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`exit`&&typeof n.rc==`number`)return`exited rc=${n.rc}`;if(n.type===`error_event`)return n.message??`worker error`}return t??`unknown failure`}function rs(){let e=(0,_.useSyncExternalStore)(V,()=>B().update),[t,n]=(0,_.useState)(`idle`),r=e.state?.update_command??``,i=e.stream.filter(e=>e.type===`stderr`&&e.data).map(e=>e.data).slice(-ts),a=ns(e.stream,e.errorMessage);function o(){H({type:`RESET_UPDATE_RUN`}),tt()}async function s(){if(r)try{await navigator.clipboard.writeText(r),n(`ok`),window.setTimeout(()=>n(`idle`),1500)}catch{n(`err`),window.setTimeout(()=>n(`idle`),1500)}}return(0,U.jsxs)(`div`,{className:`update-modal-body`,children:[(0,U.jsxs)(`div`,{className:`update-running-row update-running-row-failed`,children:[(0,U.jsx)(`span`,{className:`update-x`,"aria-hidden":`true`,children:`✗`}),(0,U.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:r||`cctally update`}),(0,U.jsx)(`span`,{className:`update-elapsed`,children:a})]}),i.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`div`,{className:`update-row-label`,children:[`stderr (last `,i.length,` line`,i.length===1?``:`s`,`)`]}),(0,U.jsx)(`pre`,{className:`update-stream update-stream-fail`,children:i.map((e,t)=>(0,U.jsxs)(`span`,{className:`update-stream-line err`,children:[e,`
18
- `]},t))})]}):(0,U.jsx)(`p`,{className:`update-manual-note`,children:e.errorMessage??`See ~/.local/share/cctally/update.log for the full failure log.`}),(0,U.jsxs)(`p`,{className:`update-stream-cap`,children:[`Full log: `,(0,U.jsx)(`code`,{children:`~/.local/share/cctally/update.log`})]}),(0,U.jsxs)(`div`,{className:`update-actions`,children:[(0,U.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,onClick:o,children:`Retry`}),(0,U.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:s,disabled:!r,children:t===`ok`?`Copied!`:t===`err`?`Copy failed`:`Copy command`}),(0,U.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>it.close(),children:`Close`})]})]})}var is={idle:`Update available`,running:`Updating cctally`,success:`Update complete`,failed:`Update failed`},as={idle:`accent-amber`,running:`accent-amber`,success:`accent-green`,failed:`accent-red`};function os(){let e=(0,_.useSyncExternalStore)(V,()=>B().update),t=()=>H({type:`CLOSE_UPDATE_MODAL`});if(Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:t,when:()=>B().update.modalOpen}],[])),!e.modalOpen||!e.state)return null;let n=e.status,r=as[n]??`accent-amber`,i=is[n]??`Update`;n===`running`&&e.state.latest_version?i=`Updating cctally → ${e.state.latest_version}`:n===`success`&&e.state.latest_version&&(i=`Update complete → ${e.state.latest_version}`);let a;switch(n){case`running`:a=(0,U.jsx)(Zo,{});break;case`success`:a=(0,U.jsx)(es,{});break;case`failed`:a=(0,U.jsx)(rs,{});break;default:a=(0,U.jsx)(Ko,{});break}return(0,U.jsxs)(`div`,{id:`update-modal-root`,className:`update-modal-root`,children:[(0,U.jsx)(`div`,{className:`modal-backdrop`,onClick:t}),(0,U.jsxs)(`div`,{className:`modal-card update-modal-card ${r}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-modal-title`,children:[(0,U.jsx)(`div`,{className:`modal-handle`,"aria-hidden":`true`}),(0,U.jsxs)(`header`,{className:`modal-header`,children:[(0,U.jsx)(`h2`,{id:`update-modal-title`,children:i}),(0,U.jsx)(`button`,{className:`modal-close`,"aria-label":`Close`,onClick:t,children:`×`})]}),(0,U.jsx)(`div`,{className:`modal-body`,children:a})]})]})}function ss({title:e,accentClass:t,children:n,headerExtras:r}){let i=()=>H({type:`CLOSE_MODAL`});return Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:i}],[])),(0,U.jsxs)(`div`,{id:`modal-root`,children:[(0,U.jsx)(`div`,{className:`modal-backdrop`,onClick:i}),(0,U.jsxs)(`div`,{className:`modal-card ${t}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`modal-title`,children:[(0,U.jsx)(`div`,{className:`modal-handle`,"aria-hidden":`true`}),(0,U.jsxs)(`header`,{className:`modal-header`,children:[(0,U.jsx)(`h2`,{id:`modal-title`,children:e}),r,(0,U.jsx)(`button`,{className:`modal-close`,"aria-label":`Close`,onClick:i,children:`×`})]}),(0,U.jsx)(`div`,{id:`modal-body`,className:`modal-body`,children:n})]})]})}function cs(e){return e==null||!isFinite(e)?0:Math.max(0,Math.min(100,e))}function ls(e,t,n){let r=A.dateShort(t,n);return e&&r?`${e} → ${r}`:e||(r?`→ ${r}`:`—`)}function us(e){if(e==null||!isFinite(e))return[`—`,``];let t=(+e).toFixed(1),n=t.indexOf(`.`);return n===-1?[t,`.0%`]:[t.slice(0,n),t.slice(n)+`%`]}function ds(e){let t=[],n=[...e].sort((e,t)=>(e.percent??0)-(t.percent??0));for(let e of n)e.percent!=null&&(t.length&&e.percent-(t[t.length-1].percent??0)<3||t.push(e));return t}function fs(e){if(!Array.isArray(e)||e.length<2)return null;let t=e.map(e=>e.marginal_usd).filter(e=>e!=null&&isFinite(e)),n=t.length?t.reduce((e,t)=>e+t,0)/t.length:null,r=e[e.length-1].percent,i=[];return n!=null&&i.push(`avg marginal $`+n.toFixed(2)),r!=null&&i.push(`latest at `+r+`%`),i.length?i.join(` · `):null}function ps(e,t){let n=[];for(let t of e)n.push({kind:`milestone`,ts:t.captured_at_utc,data:t});for(let e of t)n.push({kind:`credit`,ts:e.effective_reset_at_utc,data:e});return n.sort((e,t)=>e.ts.localeCompare(t.ts)),n}function ms(){let e=W(),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e?.current_week??null,i=e?.header??null,a=Array.isArray(r?.milestones)?r.milestones:[],o=Array.isArray(r?.five_hour_milestones)?r.five_hour_milestones:[],s=ps(o,Array.isArray(r?.five_hour_block?.credits)?r.five_hour_block.credits:[]),c=cs(r?.used_pct),[l,u]=us(r?.used_pct),d=r?ls(i?.week_label,r.reset_at_utc,n):`—`,f=ds(a),p=fs(a);return(0,U.jsx)(ss,{title:`Current Week — per-percent milestones`,accentClass:`accent-green`,headerExtras:(0,U.jsx)(qt,{panel:`current-week`,panelLabel:`Current week`,triggerId:`current-week-modal`,onClick:()=>H(R(`current-week`,`current-week-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-current-week`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,id:`mcw-badges`,children:(0,U.jsx)(`span`,{className:`m-pill accent-green`,id:`mcw-week-pill`,children:d})}),(0,U.jsxs)(`div`,{className:`mcw-herobar`,children:[(0,U.jsxs)(`div`,{className:`mcw-bignum`,id:`mcw-bignum`,children:[(0,U.jsx)(`span`,{className:`int`,children:l}),(0,U.jsx)(`span`,{className:`unit`,children:u})]}),(0,U.jsxs)(`div`,{className:`mcw-pbar-wrap`,children:[(0,U.jsxs)(`div`,{className:`mcw-pbar`,children:[(0,U.jsx)(`div`,{className:`fill`,id:`mcw-fill`,style:{width:c+`%`}}),(0,U.jsx)(`div`,{className:`ticks`,id:`mcw-ticks`,children:f.map(e=>(0,U.jsx)(`div`,{className:`tick`,"data-p":String(e.percent),style:{left:cs(e.percent)+`%`}},e.percent))}),(0,U.jsx)(`div`,{className:`marker`,id:`mcw-marker`,style:{left:c+`%`}})]}),(0,U.jsxs)(`div`,{className:`mcw-pscale`,children:[(0,U.jsx)(`span`,{children:`0%`}),(0,U.jsx)(`span`,{children:`25%`}),(0,U.jsx)(`span`,{children:`50%`}),(0,U.jsx)(`span`,{children:`75%`}),(0,U.jsx)(`span`,{children:`100%`})]})]}),(0,U.jsxs)(`div`,{className:`mcw-mini`,id:`mcw-mini`,children:[(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`spent`}),(0,U.jsx)(`span`,{className:`v v-magenta`,id:`mcw-spent`,children:A.usd2(r?.spent_usd)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`$ / 1%`}),(0,U.jsx)(`span`,{className:`v v-cyan`,id:`mcw-dpp`,children:A.usd3(r?.dollar_per_pct)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`reset`}),(0,U.jsx)(`span`,{className:`v`,id:`mcw-reset`,children:A.datetimeShortZ(r?.reset_at_utc,n)})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-ms`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Milestones`]}),(0,U.jsxs)(`div`,{className:`mcw-mshead`,children:[(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mcw-ms-count`,children:[a.length,` crossed`]}),(0,U.jsx)(`span`,{className:`mcw-ms-sub`,id:`mcw-ms-sub`,hidden:!p,children:p??``})]}),a.length===0?(0,U.jsx)(`p`,{className:`empty-state`,id:`mcw-empty`,children:`No milestones yet — earliest crosses at 1\xA0%.`}):(0,U.jsxs)(`table`,{className:`m-histable`,id:`mcw-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`%`}),(0,U.jsxs)(`th`,{children:[`Crossed (`,t.offsetLabel,`)`]}),(0,U.jsx)(`th`,{className:`num`,children:`Cumulative $`}),(0,U.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,U.jsx)(`th`,{className:`num`,children:`5h %`})]})}),(0,U.jsx)(`tbody`,{id:`mcw-rows`,children:a.map(e=>(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:e.percent??`—`})}),(0,U.jsx)(`td`,{className:`d`,children:A.startedShort(e.crossed_at_utc,n,{noSuffix:!0})}),(0,U.jsx)(`td`,{className:`num`,children:e.cumulative_usd==null?`—`:`$`+e.cumulative_usd.toFixed(2)}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-marginal`,children:e.marginal_usd==null?`—`:`$`+e.marginal_usd.toFixed(2)})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-fh`,children:e.five_hour_pct_at_cross==null?`—`:Math.round(e.five_hour_pct_at_cross)+`%`})})]},e.percent))})]}),s.length>0&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-ms sec-5h`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`5h milestones`]}),(0,U.jsx)(`div`,{className:`mcw-mshead`,children:(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mcw-5h-count`,children:[o.length,` crossed`]})}),(0,U.jsxs)(`table`,{className:`m-histable mcw-5h-table`,id:`mcw-5h-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`%`}),(0,U.jsxs)(`th`,{children:[`When (`,t.offsetLabel,`)`]}),(0,U.jsx)(`th`,{className:`num`,children:`Block $`}),(0,U.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,U.jsx)(`th`,{className:`num`,children:`7d %`})]})}),(0,U.jsx)(`tbody`,{children:s.map((e,t)=>{if(e.kind===`credit`)return(0,U.jsx)(`tr`,{className:`mcw-5h-credit-row`,children:(0,U.jsxs)(`td`,{colSpan:5,className:`mcw-5h-credit-cell`,children:[`⚡ CREDIT\xA0`,` `,e.data.delta_pp>0?`+`:``,e.data.delta_pp.toFixed(0),`pp\xA0@`,` `,A.startedShort(e.ts,n,{noSuffix:!0})]})},`credit-${t}-${e.ts}`);let r=e.data;return(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:r.percent_threshold})}),(0,U.jsx)(`td`,{className:`d`,children:A.startedShort(r.captured_at_utc,n,{noSuffix:!0})}),(0,U.jsx)(`td`,{className:`num`,children:`$`+r.block_cost_usd.toFixed(2)}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-marginal`,children:r.marginal_cost_usd==null?`—`:`$`+r.marginal_cost_usd.toFixed(2)})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-fh`,children:r.seven_day_pct_at_crossing==null?`—`:Math.round(r.seven_day_pct_at_crossing)+`%`})})]},`fhms-${r.percent_threshold}-${r.reset_event_id}`)})})]})]})]})})}function hs(e){if(!e)return`—`;let t=e.elapsed_hours,n=e.remaining_hours;if(t==null||n==null)return`—`;let r=t+n;if(r<=0)return`—`;let i=t/r*100;return Math.min(100,i).toFixed(1)+`%`}function gs(e){return e==null||!isFinite(e)?null:e<0?0:e>110?110:e}function _s(e){return e==null||!isFinite(e)?`—`:e<0?`~`+(+e).toFixed(1)+`%`:(+e).toFixed(1)+`%`}function vs(e,t){for(let t of e)t.trueXPct=t.pos/110*100;if(e.length<2||t<=0){for(let t of e)t.resolvedXPct=t.trueXPct;return}let n=e.slice().sort((e,t)=>e.trueXPct-t.trueXPct),r=n[0],i=n[1],a=r.pillWidthPx/2/t*100,o=i.pillWidthPx/2/t*100,s=8/t*100,c=a+o+s,l=2*c;if(i.trueXPct-r.trueXPct<c){let e=(r.trueXPct+i.trueXPct)/2;r.resolvedXPct=e-l/2,i.resolvedXPct=e+l/2;let t=a,n=100-o;r.resolvedXPct<t&&(r.resolvedXPct=t,i.resolvedXPct-r.resolvedXPct<l&&(i.resolvedXPct=Math.min(n,r.resolvedXPct+l))),i.resolvedXPct>n&&(i.resolvedXPct=n,i.resolvedXPct-r.resolvedXPct<l&&(r.resolvedXPct=Math.max(t,i.resolvedXPct-l)))}else r.resolvedXPct=r.trueXPct,i.resolvedXPct=i.trueXPct}function ys(e,t,n){(0,_.useEffect)(()=>{let r=e.current,i=t.current;if(!r||!i||!n)return;let a=r.querySelector(`.mfc-pills`),o=r.querySelector(`.mfc-leaders`),s=i.querySelector(`.mfc-rangeband`);if(!a||!o)return;let c=n.week_avg_projection_pct,l=n.recent_24h_projection_pct,u=gs(c),d=gs(l),f=[];u!=null&&c!=null&&f.push({kind:`wa`,pos:u,raw:c}),d!=null&&l!=null&&f.push({kind:`r24`,pos:d,raw:l});let p=new Set(f.map(e=>e.kind));i.querySelectorAll(`.mfc-chev`).forEach(e=>{let t=e.dataset.kind;(!t||!p.has(t))&&e.remove()}),a.querySelectorAll(`.mfc-pill`).forEach(e=>{let t=e.dataset.kind;(!t||!p.has(t))&&e.remove()});let m=f.map(e=>({...e,trueXPct:0,resolvedXPct:0,pillWidthPx:0}));for(let e of m){let t=e.pos/110*100,n=i.querySelector(`.mfc-chev[data-kind="${e.kind}"]`);n||(n=document.createElement(`div`),n.className=`mfc-chev `+e.kind,n.dataset.kind=e.kind,i.appendChild(n)),n.style.left=t+`%`;let r=a.querySelector(`.mfc-pill[data-kind="${e.kind}"]`),o=_s(e.raw);r?r.textContent!==o&&(r.textContent=o):(r=document.createElement(`div`),r.className=`mfc-pill `+e.kind,r.dataset.kind=e.kind,r.textContent=o,a.appendChild(r)),e.pillEl=r}if(s){let e=!1;if(m.length===2){let t=m[0].pos/110*100,n=m[1].pos/110*100,r=Math.min(t,n),i=Math.max(t,n)-r;i>=.5&&(s.style.left=r+`%`,s.style.width=i+`%`,e=!0)}s.hidden=!e}let h=()=>{for(let e of m)if(!e.pillEl||!e.pillEl.isConnected)return;let e=r.clientWidth;if(e<=0){requestAnimationFrame(h);return}for(let e of m)e.pillWidthPx=e.pillEl.getBoundingClientRect().width;vs(m,e);for(let e of m)e.pillEl.style.left=e.resolvedXPct+`%`;for(;o.firstChild;)o.removeChild(o.firstChild);for(let e of m){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`class`,e.kind),t.setAttribute(`vector-effect`,`non-scaling-stroke`),t.setAttribute(`d`,`M ${e.resolvedXPct} 0 C ${e.resolvedXPct} 10, ${e.trueXPct} 8, ${e.trueXPct} 18`),o.appendChild(t)}};h()},[e,t,n])}function bs(){let e=W()?.forecast??null,t=e?.explain??null,n=(0,_.useRef)(null),r=(0,_.useRef)(null);ys(n,r,e);let i=(0,U.jsx)(qt,{panel:`forecast`,panelLabel:`Forecast`,triggerId:`forecast-modal`,onClick:()=>H(R(`forecast`,`forecast-modal`))});if(!e)return(0,U.jsx)(ss,{title:`Forecast — explain`,accentClass:`accent-purple`,headerExtras:i,children:(0,U.jsx)(`section`,{className:`modal-forecast`,children:(0,U.jsx)(`p`,{className:`empty-state`,id:`mfc-empty`,children:`No forecast data yet.`})})});let a=Ct(e.verdict),o=a?`m-pill ${a.accent}`:`m-pill`,s=a?`${a.glyph} ${a.label}`:`—`,c=`m-pill`,l=`—`,u=!0;e.confidence===`high`?(c=`m-pill accent-blue`,l=`high confidence`,u=!1):e.confidence===`low`&&(c=`m-pill accent-red`,l=`low confidence`,u=!1);let d=t?.rates,f=t?.week;return(0,U.jsx)(ss,{title:`Forecast — explain`,accentClass:`accent-purple`,headerExtras:i,children:(0,U.jsxs)(`section`,{className:`modal-forecast`,children:[(0,U.jsxs)(`div`,{className:`m-chipstrip`,id:`mfc-chips`,children:[(0,U.jsx)(`span`,{className:o,id:`mfc-verdict`,children:s}),(0,U.jsx)(`span`,{className:c,id:`mfc-confidence`,hidden:u,children:l})]}),(0,U.jsxs)(`div`,{className:`m-hero cols-2`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-wa`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#gauge`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mfc-wa-pct`,children:A.pct1(e.week_avg_projection_pct)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Week-avg projection`}),(0,U.jsx)(`div`,{className:`sub`,id:`mfc-wa-sub`,children:A.ratePctPerHour(d?.week_average_pct_per_hour)})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-r24`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#zap`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mfc-r24-pct`,children:A.pct1(e.recent_24h_projection_pct)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Recent-24h projection`}),(0,U.jsx)(`div`,{className:`sub`,id:`mfc-r24-sub`,children:A.ratePctPerHour(d?.recent_24h_pct_per_hour)})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-range`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#bar-chart`})}),`Range vs. caps`]}),(0,U.jsxs)(`div`,{className:`mfc-rangewrap`,id:`mfc-rangewrap`,ref:n,children:[(0,U.jsx)(`div`,{className:`mfc-pills`,id:`mfc-pills`}),(0,U.jsx)(`svg`,{className:`mfc-leaders`,id:`mfc-leaders`,viewBox:`0 0 100 18`,preserveAspectRatio:`none`,"aria-hidden":`true`}),(0,U.jsxs)(`div`,{className:`mfc-rangetrack`,id:`mfc-rangetrack`,ref:r,children:[(0,U.jsx)(`div`,{className:`mfc-zone safe`}),(0,U.jsx)(`div`,{className:`mfc-zone warn`}),(0,U.jsx)(`div`,{className:`mfc-zone over`}),(0,U.jsx)(`div`,{className:`mfc-rangeband`,id:`mfc-rangeband`,hidden:!0}),(0,U.jsx)(`div`,{className:`mfc-bound b90`,children:(0,U.jsx)(`div`,{className:`lbl`,children:`90%`})}),(0,U.jsx)(`div`,{className:`mfc-bound b100`,children:(0,U.jsx)(`div`,{className:`lbl`,children:`100%`})})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-rates`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`Rates`]}),(0,U.jsxs)(`div`,{className:`mfc-kvgrid`,children:[(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`$ / 1%`}),(0,U.jsx)(`span`,{className:`v v-cyan`,id:`mfc-dpp`,children:A.usd3(d?.dollars_per_percent)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`week done`}),(0,U.jsx)(`span`,{className:`v v-green`,id:`mfc-wkdone`,children:hs(f)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`elapsed`}),(0,U.jsx)(`span`,{className:`v v-green`,id:`mfc-elapsed`,children:A.hours1(f?.elapsed_hours)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`remaining`}),(0,U.jsx)(`span`,{className:`v`,id:`mfc-remain`,children:A.hours1(f?.remaining_hours)})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-bud`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),`Daily budgets to stay under`]}),(0,U.jsxs)(`div`,{className:`mfc-kvgrid mfc-kvgrid-single`,children:[(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`@ 100% cap`}),(0,U.jsx)(`span`,{className:`v v-magenta`,id:`mfc-bud100`,children:A.usd2PerDay(e.budget_100_per_day_usd)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`@ 90% cap`}),(0,U.jsx)(`span`,{className:`v v-amber`,id:`mfc-bud90`,children:A.usd2PerDay(e.budget_90_per_day_usd)})]})]})]})})}function xs(e){let t=Math.max(1,Math.round(e/4));return`${e} week${e===1?``:`s`} · ${t} month${t===1?``:`s`}`}function Ss(e){let t=e.findIndex(e=>e&&e.is_current);return t>=0?t:e.length-1}function Cs(e,t){let n=e.filter((e,n)=>n!==t).map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e));if(n.length<4)return null;let r=n.slice(-4).sort((e,t)=>e-t);return(r[1]+r[2])/2}function ws(e){if(!e.length)return null;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function Ts(e,t){let n=[];if(!e.length)return n;let r={left:44,right:14,top:12,bottom:22},i=600-r.left-r.right,a=140-r.top-r.bottom,o=e.length,s=e=>r.left+(o===1?i:e/(o-1)*i),c=e.map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e)),l=c.length?Math.min(...c)*.96:0,u=c.length?Math.max(...c)*1.04:1;u-l<1e-6&&(l-=.01,u+=.01);let d=e=>r.top+a*(1-(e-l)/(u-l)),f=e.map(e=>e.used_pct).filter(e=>e!=null&&isFinite(e)),p=f.length?Math.min(...f)*.96:0,m=f.length?Math.max(...f)*1.04:100;m-p<1e-6&&(--p,m+=1);let h=e=>r.top+a*(1-(e-p)/(m-p));if(n.push({el:`line`,attrs:{class:`mtr-axis`,x1:r.left,y1:r.top+a,x2:600-r.right,y2:r.top+a},key:`axis`}),c.length){let e=ws(c);e!=null&&(n.push({el:`line`,attrs:{class:`mtr-hl`,x1:r.left,y1:d(e),x2:600-r.right,y2:d(e)},key:`med-line`}),n.push({el:`text`,attrs:{class:`mtr-medlabel`,x:r.left+2,y:d(e)-3},text:`median $`+e.toFixed(2),key:`med-label`}))}{let t=[];e.forEach((e,n)=>{e.used_pct!=null&&isFinite(e.used_pct)&&t.push(`${s(n)},${h(e.used_pct)}`)}),t.length>=2&&n.push({el:`polyline`,attrs:{class:`mtr-trendline-dim`,points:t.join(` `)},key:`poly-used`})}{let t=[];e.forEach((e,n)=>{e.dollar_per_pct!=null&&isFinite(e.dollar_per_pct)&&t.push(`${s(n)},${d(e.dollar_per_pct)}`)}),t.length>=2&&n.push({el:`polyline`,attrs:{class:`mtr-trendline`,points:t.join(` `)},key:`poly-dpp`})}e.forEach((e,r)=>{if(e.dollar_per_pct==null||!isFinite(e.dollar_per_pct))return;let i=r===t;n.push({el:`circle`,attrs:{class:`mtr-trenddot`+(i?` cur`:``),cx:s(r),cy:d(e.dollar_per_pct),r:i?5:3},key:`dot-${r}`})}),c.length&&(n.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:r.top+8},text:`$`+(u/1.04).toFixed(2),key:`ymax`}),n.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:r.top+a},text:`$`+(l/.96).toFixed(2),key:`ymin`}));let g=e[t];return g&&g.dollar_per_pct!=null&&isFinite(g.dollar_per_pct)&&n.push({el:`text`,attrs:{class:`mtr-curlabel`,x:Math.max(r.left+4,s(t)-22),y:Math.min(138,d(g.dollar_per_pct)+16)},text:`$`+g.dollar_per_pct.toFixed(2),key:`curlabel`}),n}function Es(e,t){return t===0?`Now`+(e.label?` · `+e.label:``):`W−`+t+(e.label?` · `+e.label:``)}function Ds(e){return e==null||!isFinite(e)?{cls:`flat`,text:`—`}:e>5e-4?{cls:`up`,text:`+`+e.toFixed(2)}:e<-5e-4?{cls:`down`,text:e.toFixed(2)}:{cls:`flat`,text:`0.00`}}function Os(e){return e==null||!isFinite(e)?{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`—`}:e<-5e-4?{cls:`delta-down`,iconHref:`/static/icons.svg#trending-down`,text:`−$`+Math.abs(e).toFixed(3)}:e>5e-4?{cls:`delta-up`,iconHref:`/static/icons.svg#trending-up`,text:`+$`+e.toFixed(3)}:{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`$0.000`}}function ks(){let e=W(),t=ne(e),n=(0,U.jsx)(qt,{panel:`trend`,panelLabel:`Trend`,triggerId:`trend-modal`,onClick:()=>H(R(`trend`,`trend-modal`))});if(!t.length)return(0,U.jsx)(ss,{title:`Trend — 12-week history`,accentClass:`accent-amber`,headerExtras:n,children:(0,U.jsx)(`section`,{className:`modal-trend`,children:(0,U.jsx)(`p`,{className:`empty-state`,id:`mtr-empty`,children:`No history data yet.`})})});let r=Ss(t),i=t[r],a=e?.trend?.history_median_dpp,o=a!=null&&isFinite(a)?a:Cs(t,r),s=Os(i&&i.dollar_per_pct!=null&&o!=null?i.dollar_per_pct-o:null),c=Ts(t,r),l=t.some(e=>e.used_pct!=null&&isFinite(e.used_pct)),u=t.length;return(0,U.jsx)(ss,{title:`Trend — 12-week history`,accentClass:`accent-amber`,headerExtras:n,children:(0,U.jsxs)(`section`,{className:`modal-trend`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,children:(0,U.jsx)(`span`,{className:`m-pill accent-amber`,id:`mtr-weeks-pill`,children:xs(u)})}),(0,U.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-cur`,children:i&&i.dollar_per_pct!=null?`$`+i.dollar_per_pct.toFixed(3):`—`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Current $ / 1%`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-med`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#minus`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-med`,children:o==null?`—`:`$`+o.toFixed(3)}),(0,U.jsx)(`div`,{className:`lbl`,children:`4-week median`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-delta ${s.cls}`,id:`mtr-delta-kv`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:s.iconHref})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-delta`,children:s.text}),(0,U.jsx)(`div`,{className:`lbl`,children:`vs median`})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-spark`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#trending-down`})}),`12-week history · $/1%`,(0,U.jsxs)(`span`,{className:`mtr-legend`+(l?``:` legend-no-used`),"aria-hidden":`true`,children:[(0,U.jsx)(`span`,{className:`sw sw-dpp`}),(0,U.jsx)(`span`,{className:`sw-lbl`,children:`$/1%`}),(0,U.jsx)(`span`,{className:`sw sw-used`}),(0,U.jsx)(`span`,{className:`sw-lbl`,children:`used %`})]})]}),(0,U.jsxs)(`div`,{className:`mtr-sparkhero`,children:[(0,U.jsx)(`svg`,{id:`mtr-svg`,viewBox:`0 0 600 140`,preserveAspectRatio:`none`,"aria-hidden":`true`,children:c.map(e=>{let{el:t,attrs:n,text:r,key:i}=e,a={};for(let e in n)a[e===`class`?`className`:e]=n[e];return t===`line`?(0,U.jsx)(`line`,{...a},i):t===`polyline`?(0,U.jsx)(`polyline`,{...a},i):t===`circle`?(0,U.jsx)(`circle`,{...a},i):(0,U.jsx)(`text`,{...a,children:r},i)})}),(0,U.jsx)(`div`,{className:`mtr-sparkaxis`,id:`mtr-sparkaxis`,children:u>0?(0,U.jsxs)(_.Fragment,{children:[(0,U.jsxs)(`span`,{children:[`W−`,u-1]}),(0,U.jsxs)(`span`,{children:[`W−`,Math.floor((u-1)/2)]}),(0,U.jsx)(`span`,{children:`Now`})]}):null})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tbl`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Weekly detail`]}),(0,U.jsxs)(`div`,{className:`mtr-tbl-head`,children:[(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mtr-tbl-count`,children:[u,` weeks`]}),(0,U.jsx)(`span`,{className:`mtr-tbl-sub`,children:`current row highlighted · negative Δ = $/1% down vs prior week`})]}),(0,U.jsxs)(`table`,{className:`m-histable`,id:`mtr-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`Week`}),(0,U.jsx)(`th`,{className:`num`,children:`Used %`}),(0,U.jsx)(`th`,{className:`num`,children:`$ / 1%`}),(0,U.jsx)(`th`,{className:`num`,children:`Δ $/1%`})]})}),(0,U.jsx)(`tbody`,{id:`mtr-rows`,children:t.map((e,t)=>{let n=Es(e,u-1-t),r=e.used_pct==null?`—`:Math.round(e.used_pct)+`%`,i=e.dollar_per_pct==null?`—`:`$`+e.dollar_per_pct.toFixed(2),a=Ds(e.delta);return(0,U.jsxs)(`tr`,{className:e.is_current?`cur`:void 0,children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`wlab`,children:n})}),(0,U.jsx)(`td`,{className:`num usedpct`,children:r}),(0,U.jsx)(`td`,{className:`num dpp`,children:i}),(0,U.jsx)(`td`,{className:`num delta ${a.cls}`,children:a.text})]},e.label+`|`+t)})})]})]})})}var As=/(^|\/)(subagents\/|agent-)/;function js(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Ms(){let e=(0,_.useSyncExternalStore)(V,()=>B().openSessionId),t=js(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!0),[o,s]=(0,_.useState)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(!1),u=(0,_.useRef)(null);return(0,_.useEffect)(()=>{u.current=e??B().snapshot?.sessions?.rows?.[0]?.session_id??null,l.current=!1},[e]),(0,_.useEffect)(()=>{let e=u.current;if(!e){a(!1),s(`No session available.`),r(null),c.current=null;return}let t=c.current!==e||n==null;c.current=e,t&&(a(!0),s(null),r(null));let i=new AbortController;return fetch(`/api/session/${encodeURIComponent(e)}`,{signal:i.signal}).then(async e=>{if(e.status===404){(t||l.current)&&(a(!1),s(`Session not found (the cache may have rolled forward).`),r(null)),l.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();l.current=!1,r(n),s(null),a(!1)}).catch(e=>{e.name!==`AbortError`&&(l.current=!1,t&&(s(`Failed to load: `+e.message),a(!1)))}),()=>i.abort()},[e,t]),(0,U.jsx)(ss,{title:`Session detail`,accentClass:`accent-orange`,headerExtras:(0,U.jsx)(qt,{panel:`sessions`,panelLabel:`Session`,triggerId:`session-modal`,onClick:()=>H(R(`sessions`,`session-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-sessions`,children:[i?(0,U.jsx)(`div`,{className:`modal-loading`,id:`msess-loading`,children:`Loading session detail…`}):null,o?(0,U.jsx)(`div`,{className:`modal-error`,id:`msess-error`,children:o}):null,!i&&!o&&n?(0,U.jsx)(Ns,{detail:n}):null]})})}function Ns({detail:e}){let t=Array.isArray(e.source_paths)?e.source_paths:[],n=[],r=[];t.forEach(e=>{As.test(e)?r.push(e):n.push(e)});let i=e.cost_total_usd??0,a=[[`Input`,e.input_tokens,null],[`Output`,e.output_tokens,null],[`Cache creation`,e.cache_creation_tokens,null],[`Cache read`,e.cache_read_tokens,null],[`Cache hit %`,e.cache_hit_pct,`cache-hit`]].filter(e=>e[1]!=null),o=!e.models||e.models.length===0,s=!e.cost_per_model||e.cost_per_model.length===0;return(0,U.jsxs)(`div`,{className:`modal-content`,id:`msess-content`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,children:(0,U.jsx)(`span`,{className:`msess-badge`,id:`msess-id`,"aria-label":`Session ID`,children:e.session_id??`—`})}),(0,U.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-cost`,children:e.cost_total_usd==null?`—`:`$`+e.cost_total_usd.toFixed(2)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-dur`,children:e.duration_min==null?`—`:e.duration_min+` min`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Duration`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#folder`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-project`,title:e.project_path??``,"aria-label":`Project`,children:e.project_label??e.project_path??`—`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Project`})]})]})]}),(0,U.jsxs)(`div`,{className:`msess-ts`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`started`}),(0,U.jsx)(`span`,{className:`v`,id:`msess-started`,children:e.started_utc??`—`})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`last activity`}),(0,U.jsx)(`span`,{className:`v`,id:`msess-last`,children:e.last_activity_utc??`—`})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,U.jsx)(`div`,{className:`msess-tok-grid`,id:`msess-tokens`,children:a.map(([e,t,n])=>(0,U.jsxs)(`div`,{className:`msess-tok-tile`+(n?` `+n:``),children:[(0,U.jsx)(`div`,{className:`lbl`,children:e}),(0,U.jsx)(`div`,{className:`n`,children:n===`cache-hit`?t.toFixed(1)+`%`:t.toLocaleString(`en-US`)}),n===`cache-hit`?(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:Math.max(0,Math.min(t,100))+`%`}})}):null]},e))}),o?null:(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-mod`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#sparkles`})}),`Models`]}),(0,U.jsx)(`div`,{className:`m-chipstrip`,id:`msess-models`,children:(e.models||[]).map(e=>(0,U.jsx)(`span`,{className:`chip `+dn(e.name),children:e.name},e.name))})]}),s?null:(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,U.jsxs)(`div`,{className:`msess-costm`,children:[(0,U.jsx)(`div`,{className:`bar`,id:`msess-cost-bar`,children:(e.cost_per_model||[]).map(e=>{let t=i>0&&e.cost_usd!=null?e.cost_usd/i*100:0;return(0,U.jsx)(`div`,{className:`seg `+dn(e.model),style:{width:t+`%`}},e.model)})}),(0,U.jsx)(`div`,{className:`legend`,id:`msess-cost-legend`,children:(e.cost_per_model||[]).map(e=>{let t=i>0&&e.cost_usd!=null?e.cost_usd/i*100:0;return(0,U.jsxs)(`div`,{className:`lg`,children:[(0,U.jsx)(`span`,{className:`sw `+dn(e.model)}),(0,U.jsx)(`span`,{className:`name`,children:e.model}),(0,U.jsx)(`span`,{className:`v`,children:e.cost_usd==null?`—`:`$`+e.cost_usd.toFixed(3)}),(0,U.jsxs)(`span`,{className:`pct`,children:[Math.round(t),`%`]})]},e.model)})})]})]}),t.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-src`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#file-text`})}),`Source files`]}),(0,U.jsxs)(`div`,{className:`msess-src`,id:`msess-src`,children:[(0,U.jsxs)(`div`,{className:`src-head`,children:[(0,U.jsxs)(`span`,{className:`count-pill`,children:[t.length,` file`,t.length===1?``:`s`]}),(0,U.jsxs)(`span`,{className:`sub`,children:[n.length,` primary`,r.length>0?(0,U.jsxs)(U.Fragment,{children:[` `,(0,U.jsx)(`span`,{className:`dot`,children:`·`}),` `,(0,U.jsxs)(`span`,{className:`subcount`,children:[r.length,` subagent`,r.length===1?``:`s`]})]}):null]})]}),n.length>0?n.map(e=>(0,U.jsx)(`div`,{className:`primary-path`,children:e},e)):r.length>0?(0,U.jsxs)(`div`,{className:`src-empty-primary`,children:[`No primary path resolved · `,r.length,` subagent path`,r.length===1?``:`s`,` below`]}):null,r.length>0?(0,U.jsxs)(`details`,{className:`subagents`,open:n.length===0,children:[(0,U.jsxs)(`summary`,{children:[`Show `,r.length,` subagent path`,r.length===1?``:`s`]}),(0,U.jsx)(`ul`,{className:`paths`,children:r.map(e=>(0,U.jsx)(`li`,{children:e},e))})]}):null]})]}):null]})}function Ps({row:e,variant:t,accentClass:n}){let r=Wt(),i={tz:r.resolvedTz,offsetLabel:r.offsetLabel},a=(e,t)=>`${A.datetimeShort(e,i)} → ${A.datetimeShort(t,i)}`,o=e.delta_cost_pct==null?`flat`:e.delta_cost_pct>0?`up`:e.delta_cost_pct<0?`down`:`flat`,s=t===`weekly`?`week`:t===`monthly`?`month`:`day`,c=t===`daily`?`Today`:`Now`;return(0,U.jsxs)(`div`,{className:`detail-card ${n}`,children:[(0,U.jsxs)(`div`,{className:`head`,children:[(0,U.jsxs)(`div`,{className:`big`,children:[e.label,e.is_current&&(0,U.jsx)(`span`,{className:`pill-current`,children:c})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`cost`,style:{color:`var(--text)`,fontWeight:700},children:A.usd2(e.cost_usd)}),` `,e.delta_cost_pct==null?(0,U.jsx)(`span`,{className:`delta flat`,children:`—`}):(0,U.jsxs)(`span`,{className:`delta ${o}`,children:[A.deltaPct(e.delta_cost_pct),` vs prior `,s]})]})]}),t===`weekly`&&e.week_start_at&&e.week_end_at&&(0,U.jsxs)(`div`,{className:`window`,children:[`Subscription window: `,a(e.week_start_at,e.week_end_at)]}),(0,U.jsx)(`div`,{className:`model-stack`,role:`presentation`,children:e.models.map(e=>(0,U.jsx)(`span`,{className:e.chip,style:{width:`${e.cost_pct}%`}},e.model))}),(0,U.jsx)(`div`,{className:`chips`,children:e.models.map(e=>(0,U.jsxs)(`span`,{className:`chip ${e.chip}`,children:[e.display,` `,Math.round(e.cost_pct),`% · `,A.usd2(e.cost_usd)]},e.model))}),(0,U.jsxs)(`div`,{className:`tokens-row`,children:[(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Input`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.input_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Output`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.output_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache+`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.cache_creation_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache-read`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.cache_read_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Total`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.total_tokens)})]}),e.cache_hit_pct!=null&&(0,U.jsxs)(`div`,{className:`t cache`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache hit`}),(0,U.jsxs)(`span`,{className:`v`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:`${Math.min(100,Math.max(0,e.cache_hit_pct))}%`}})})]})]}),t===`weekly`&&(0,U.jsxs)(`div`,{className:`stats2`,children:[(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Used %`}),(0,U.jsx)(`span`,{className:`v`,children:A.pct0(e.used_pct)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`$/1%`}),(0,U.jsx)(`span`,{className:`v`,children:A.usd2(e.dollar_per_pct)})]})]})]})}function Fs(e){return e==null||e===0?`num`:e>0?`num delta-up`:`num delta-down`}function Is(e){let t=new Set,n=[];for(let r of e.models)t.has(r.chip)||(t.add(r.chip),n.push(r.chip));return n}function Ls({row:e}){let t=Is(e),n=t.slice(0,3),r=t.length>3?t.length-3:0;return(0,U.jsxs)(`span`,{className:`models-chips`,children:[n.map(e=>(0,U.jsx)(`span`,{className:`chip ${e}`,children:e},e)),r>0&&(0,U.jsxs)(`span`,{className:`models-chips-more`,children:[`…+`,r]})]})}function Rs({rows:e,variant:t,accentClass:n,selectedIndex:r,onSelect:i}){return(0,U.jsxs)(`table`,{className:`history-table history-table--${t} ${n}`,role:`grid`,"aria-rowcount":e.length,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:t===`weekly`?`Week`:`Month`}),(0,U.jsx)(`th`,{children:`Models`}),(0,U.jsx)(`th`,{className:`num`,children:`Cost (USD)`}),t===`weekly`&&(0,U.jsx)(`th`,{className:`num`,children:`Used %`}),t===`weekly`&&(0,U.jsx)(`th`,{className:`num`,children:`$/1%`}),(0,U.jsx)(`th`,{className:`num`,children:`Δ`})]})}),(0,U.jsx)(`tbody`,{children:e.map((e,n)=>(0,U.jsxs)(`tr`,{className:n===r?`selected`:void 0,"aria-rowindex":n+1,"aria-selected":n===r,onClick:()=>i(n),children:[(0,U.jsxs)(`td`,{children:[e.label,n===r?` ▶`:``]}),(0,U.jsx)(`td`,{children:(0,U.jsx)(Ls,{row:e})}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(e.cost_usd)}),t===`weekly`&&(0,U.jsx)(`td`,{className:`num`,children:A.pct0(e.used_pct)}),t===`weekly`&&(0,U.jsx)(`td`,{className:`num`,children:A.usd2(e.dollar_per_pct)}),(0,U.jsx)(`td`,{className:Fs(e.delta_cost_pct),children:A.deltaPct(e.delta_cost_pct)})]},e.label))})]})}function zs(){let e=W()?.weekly?.rows??[],[t,n]=(0,_.useState)(0),r=e.length;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`weekly`,action:()=>n(e=>Math.min(e+1,Math.max(0,r-1)))},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`weekly`,action:()=>n(e=>Math.max(e-1,0))}]),[r]);let i=(0,U.jsx)(qt,{panel:`weekly`,panelLabel:`Weekly`,triggerId:`weekly-modal`,onClick:()=>H(R(`weekly`,`weekly-modal`))});if(r===0)return(0,U.jsx)(ss,{title:`Weekly history · last 12`,accentClass:`accent-cyan`,headerExtras:i,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let a=e[Math.min(t,r-1)];return(0,U.jsxs)(ss,{title:`Weekly history · last 12`,accentClass:`accent-cyan`,headerExtras:i,children:[(0,U.jsx)(Ps,{row:a,variant:`weekly`,accentClass:`accent-cyan`}),(0,U.jsx)(Rs,{rows:e,variant:`weekly`,accentClass:`accent-cyan`,selectedIndex:t,onSelect:n})]})}function Bs(){let e=W()?.monthly?.rows??[],[t,n]=(0,_.useState)(0),r=e.length;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`monthly`,action:()=>n(e=>Math.min(e+1,Math.max(0,r-1)))},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`monthly`,action:()=>n(e=>Math.max(e-1,0))}]),[r]);let i=(0,U.jsx)(qt,{panel:`monthly`,panelLabel:`Monthly`,triggerId:`monthly-modal`,onClick:()=>H(R(`monthly`,`monthly-modal`))});if(r===0)return(0,U.jsx)(ss,{title:`Monthly history · last 12`,accentClass:`accent-pink`,headerExtras:i,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let a=e[Math.min(t,r-1)];return(0,U.jsxs)(ss,{title:`Monthly history · last 12`,accentClass:`accent-pink`,headerExtras:i,children:[(0,U.jsx)(Ps,{row:a,variant:`monthly`,accentClass:`accent-pink`}),(0,U.jsx)(Rs,{rows:e,variant:`monthly`,accentClass:`accent-pink`,selectedIndex:t,onSelect:n})]})}var Vs=720,Hs=180,Us={left:46,right:20,top:18,bottom:20};function Ws(e){return e===0?`$0`:e<10?`$`+e.toFixed(2):`$`+Math.round(e).toString()}function Gs(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Ks({detail:e}){let t=Gs(),n=Wt(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},i=Date.parse(e.start_at),a=Date.parse(e.end_at)-i||1,o=e=>Us.left+(Date.parse(e)-i)/a*(Vs-Us.left-Us.right),s=Math.max(e.cost_usd,e.projection?.total_cost_usd??0),c=e=>{let t=Us.top,n=Hs-Us.bottom;return s<=0?n:n-e/s*(n-t)},l=[];for(let e=0;e<=5;e++)l.push(new Date(i+e*36e5).toISOString());let u=e.samples.length>0?e.samples[e.samples.length-1].cum:0,d=e.is_active?t||new Date().toISOString():null,f=[];if(e.samples.length>0){f.push([o(e.start_at),c(0)]);for(let t of e.samples)f.push([o(t.t),c(t.cum)]);d&&f.push([o(d),c(u)])}let p=f.map(([e,t])=>`${e.toFixed(1)},${t.toFixed(1)}`).join(` `),m=f.length>0?`M ${p.replace(/ /g,` L `)} L ${f[f.length-1][0].toFixed(1)},${c(0).toFixed(1)} Z`:``,h=s<=0?[0]:[0,s/2,s];return(0,U.jsx)(`div`,{className:`mblock-timeline`,children:(0,U.jsxs)(`svg`,{viewBox:`0 0 ${Vs} ${Hs}`,style:{width:`100%`,height:`auto`},role:`img`,"aria-label":`Cumulative cost over the 5-hour block window`,children:[h.map(e=>(0,U.jsx)(`text`,{x:8,y:c(e)+4,fill:`var(--text-dim)`,fontSize:10,children:Ws(e)},e)),(0,U.jsx)(`line`,{x1:Us.left,y1:Us.top,x2:Us.left,y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),(0,U.jsx)(`line`,{x1:Us.left,y1:Hs-Us.bottom,x2:Vs-Us.right,y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),l.slice(1,-1).map(e=>(0,U.jsx)(`line`,{x1:o(e),y1:Us.top,x2:o(e),y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeDasharray:`2 3`,strokeWidth:.5},e)),l.map(e=>(0,U.jsx)(`text`,{x:o(e)-14,y:Hs-5,fill:`var(--text-dim)`,fontSize:9,children:A.timeHHmm(e,r,{noSuffix:!0})},e)),f.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`path`,{d:m,fill:`var(--accent-green)`,opacity:.12}),(0,U.jsx)(`polyline`,{points:p,fill:`none`,stroke:`var(--accent-green)`,strokeWidth:2}),(0,U.jsx)(`circle`,{cx:f[f.length-1][0],cy:f[f.length-1][1],r:3,fill:`var(--accent-green)`})]}):(0,U.jsx)(`text`,{x:Vs/2,y:Hs/2,fill:`var(--text-faint)`,fontSize:11,textAnchor:`middle`,children:`No spend recorded yet in this block.`}),e.is_active&&e.projection&&d&&f.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`polyline`,{points:`${o(d).toFixed(1)},${c(u).toFixed(1)} ${o(e.end_at).toFixed(1)},${c(e.projection.total_cost_usd).toFixed(1)}`,fill:`none`,stroke:`var(--accent-amber)`,strokeWidth:1.5,strokeDasharray:`5 4`,opacity:.85}),(0,U.jsx)(`circle`,{cx:o(e.end_at),cy:c(e.projection.total_cost_usd),r:3,fill:`var(--accent-amber)`,opacity:.85}),(0,U.jsxs)(`text`,{x:o(e.end_at)-50,y:c(e.projection.total_cost_usd)-6,fill:`var(--accent-amber)`,fontSize:9,children:[`proj $`,e.projection.total_cost_usd.toFixed(2)]}),(0,U.jsx)(`line`,{x1:o(d),y1:Us.top,x2:o(d),y2:Hs-Us.bottom,stroke:`var(--accent-amber)`,strokeWidth:1.2}),(0,U.jsx)(`text`,{x:o(d)+4,y:Us.top+10,fill:`var(--accent-amber)`,fontSize:9,children:`now`})]}):null]})})}function qs(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Js(e,t){let n=Date.parse(e.start_at),r=e.is_active?Date.parse(t)||Date.now():e.actual_end_at?Date.parse(e.actual_end_at):Date.parse(e.end_at),i=Math.max(0,Math.floor((r-n)/6e4)),a=Math.floor(i/60),o=i%60;return`${a}h ${String(o).padStart(2,`0`)}m`}function Ys(e,t,n){return`${A.timeHHmm(e,n)} → ${A.timeHHmm(t,n)}`}function Xs(){let e=(0,_.useSyncExternalStore)(V,()=>B().openBlockStartAt),t=qs(),n=Wt(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(!1),f=(0,_.useRef)(null);return(0,_.useEffect)(()=>{f.current=e??null,d.current=!1},[e]),(0,_.useEffect)(()=>{let e=f.current;if(!e){s(!1),l(`No block bound.`),a(null),u.current=null;return}let t=u.current!==e||i==null;u.current=e,t&&(s(!0),l(null),a(null));let n=new AbortController;return fetch(`/api/block/${encodeURIComponent(e)}`,{signal:n.signal}).then(async e=>{if(e.status===404){(t||d.current)&&(s(!1),l(`Block not found (the cache may have rolled forward).`),a(null)),d.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();d.current=!1,a(n),l(null),s(!1)}).catch(e=>{e.name!==`AbortError`&&(d.current=!1,t&&(l(`Failed to load: `+e.message),s(!1)))}),()=>n.abort()},[e,t]),(0,U.jsx)(ss,{title:i?`${i.anchor===`heuristic`?`~ `:``}Block · ${i.label}`:`Block`,accentClass:`accent-blue`,headerExtras:(0,U.jsx)(qt,{panel:`blocks`,panelLabel:`5-hour block`,triggerId:`block-modal`,onClick:()=>H(R(`blocks`,`block-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-block`,children:[o?(0,U.jsx)(`div`,{className:`modal-loading`,children:`Loading block detail…`}):null,c?(0,U.jsx)(`div`,{className:`modal-error`,children:c}):null,!o&&!c&&i?(0,U.jsx)(Zs,{detail:i,generatedAt:t,ctx:r}):null]})})}function Zs({detail:e,generatedAt:t,ctx:n}){let r=e.cost_usd??0;return(0,U.jsxs)(`div`,{className:`modal-content`,children:[(0,U.jsxs)(`div`,{className:`m-chipstrip`,children:[e.is_active?(0,U.jsx)(`span`,{className:`m-pill accent-green`,children:`● Active`}):null,e.anchor===`heuristic`?(0,U.jsx)(`span`,{className:`m-pill accent-amber`,children:`~ heuristic anchor`}):null,(0,U.jsx)(`span`,{className:`m-pill accent-blue`,children:Ys(e.start_at,e.end_at,n)}),(0,U.jsxs)(`span`,{className:`m-pill`,children:[e.entries_count.toLocaleString(`en-US`),` `,e.entries_count===1?`entry`:`entries`]})]}),(0,U.jsxs)(`div`,{className:`m-hero `+(e.is_active?`cols-4`:`cols-3`),children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:A.usd2(e.cost_usd)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:Js(e,t)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Elapsed`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:e.total_tokens.toLocaleString(`en-US`)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total tokens`})]})]}),e.is_active?(0,U.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:e.projection?A.usd2(e.projection.total_cost_usd):`—`}),(0,U.jsxs)(`div`,{className:`lbl`,children:[`Projected`,e.projection?` · ${e.projection.remaining_minutes}m left`:``]})]})]}):null]}),(0,U.jsx)(Ks,{detail:e}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,U.jsxs)(`div`,{className:`msess-tok-grid mblock-tok-grid`,children:[(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Input`}),(0,U.jsx)(`div`,{className:`n`,children:e.input_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Output`}),(0,U.jsx)(`div`,{className:`n`,children:e.output_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache create`}),(0,U.jsx)(`div`,{className:`n`,children:e.cache_creation_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache read`}),(0,U.jsx)(`div`,{className:`n`,children:e.cache_read_tokens.toLocaleString(`en-US`)})]}),e.cache_hit_pct==null?null:(0,U.jsxs)(`div`,{className:`msess-tok-tile cache-hit`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache hit %`}),(0,U.jsxs)(`div`,{className:`n`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:Math.min(100,Math.max(0,e.cache_hit_pct))+`%`}})})]})]}),e.models.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,U.jsxs)(`div`,{className:`msess-costm`,children:[(0,U.jsx)(`div`,{className:`bar`,children:e.models.map(e=>{let t=r>0?e.cost_usd/r*100:0;return(0,U.jsx)(`div`,{className:`seg `+dn(e.model),style:{width:t+`%`}},e.model)})}),(0,U.jsx)(`div`,{className:`legend`,children:e.models.map(e=>{let t=r>0?e.cost_usd/r*100:0;return(0,U.jsxs)(`div`,{className:`lg`,children:[(0,U.jsx)(`span`,{className:`sw `+dn(e.model)}),(0,U.jsx)(`span`,{className:`name`,children:e.display}),(0,U.jsxs)(`span`,{className:`v`,children:[`$`,e.cost_usd.toFixed(2)]}),(0,U.jsxs)(`span`,{className:`pct`,children:[Math.round(t),`%`]})]},e.model)})})]})]}):null,e.is_active&&e.burn_rate&&e.projection?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-burn`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),`Burn rate & projection`]}),(0,U.jsxs)(`div`,{className:`mblock-burn`,children:[(0,U.jsxs)(`div`,{className:`row`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Burn rate`}),(0,U.jsx)(`span`,{className:`v amber`,children:A.usd2(e.burn_rate.cost_per_hour)}),(0,U.jsx)(`span`,{className:`dim`,children:`/ hr`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsx)(`span`,{className:`v cyan`,children:Math.round(e.burn_rate.tokens_per_minute).toLocaleString(`en-US`)}),(0,U.jsx)(`span`,{className:`dim`,children:`tok / min`})]}),(0,U.jsxs)(`div`,{className:`row`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Projection`}),(0,U.jsx)(`span`,{className:`v amber`,children:A.usd2(e.projection.total_cost_usd)}),(0,U.jsx)(`span`,{className:`dim`,children:`total`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsx)(`span`,{className:`v cyan`,children:e.projection.total_tokens.toLocaleString(`en-US`)}),(0,U.jsx)(`span`,{className:`dim`,children:`tok`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsxs)(`span`,{className:`v`,children:[e.projection.remaining_minutes,` min`]}),(0,U.jsx)(`span`,{className:`dim`,children:`remaining`})]})]})]}):null]})}function Qs({rows:e,selectedDate:t,onSelect:n}){let r=[...e].reverse(),i=r.reduce((e,t)=>Math.max(e,t.cost_usd),0),a=r.length>0?$s(r[0].date):``,o=r.length>0?$s(r[r.length-1].date):``,s=r.find(e=>e.is_today),c=s?`${$s(s.date)} · today`:``;return(0,U.jsxs)(`section`,{className:`daily-modal-bars`,"aria-label":`30-day cost`,children:[(0,U.jsxs)(`div`,{className:`daily-modal-bars-head`,children:[(0,U.jsxs)(`span`,{children:[`30-day cost · selected: `,t?$s(t):`—`]}),(0,U.jsx)(`span`,{className:`hint`,children:`↑↓ navigate · click any bar`})]}),(0,U.jsx)(`div`,{className:`daily-modal-bars-grid`,role:`img`,"aria-label":`30-day cost histogram`,children:r.map(e=>{let r=e.cost_usd<=0,a=e.date===t,o=r?4:i>0?e.cost_usd/i*100:0,s=[`bar`,r?`zero`:``,a?`sel`:``,e.is_today?`today`:``].filter(Boolean).join(` `);return(0,U.jsx)(`button`,{"data-date":e.date,className:s,style:{height:`${o}%`},disabled:r,"aria-pressed":a,"aria-label":`${e.label} cost ${e.cost_usd>0?A.usd2(e.cost_usd):`no usage`}`,title:e.cost_usd>0?`${e.label} · ${A.usd2(e.cost_usd)}`:`${e.label} · —`,onClick:()=>{r||n(e.date)}},e.date)})}),r.length>0&&(0,U.jsxs)(`div`,{className:`daily-modal-bars-axis`,children:[(0,U.jsx)(`span`,{children:a}),c&&(0,U.jsx)(`span`,{children:c}),(0,U.jsx)(`span`,{children:o})]})]})}function $s(e){let t=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],n=e.split(`-`).map(Number);return`${t[n[1]-1]} ${n[2]}`}function ec(){let e=W()?.daily?.rows??[],t=(0,_.useSyncExternalStore)(V,()=>B().openDailyDate),[n,r]=(0,_.useState)(null);(0,_.useEffect)(()=>{t&&r(t)},[]);let i=new Set(e.map(e=>e.date)),a=e[0]?.date??null,o=n&&i.has(n)?n:a;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`daily`,action:()=>{let t=o;if(!t)return;let n=e.findIndex(e=>e.date===t);n<0||n>=e.length-1||r(e[n+1].date)}},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`daily`,action:()=>{let t=o;if(!t)return;let n=e.findIndex(e=>e.date===t);n<=0||r(e[n-1].date)}}]),[e,o]);let s=(0,U.jsx)(qt,{panel:`daily`,panelLabel:`Daily`,triggerId:`daily-modal`,onClick:()=>H(R(`daily`,`daily-modal`))});if(e.length===0)return(0,U.jsx)(ss,{title:`Daily history · last 30`,accentClass:`accent-indigo`,headerExtras:s,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let c=e.findIndex(e=>e.date===o),l=c>=0?c:0,u=e[l],d=e[l+1],f=tc(u,d);return(0,U.jsxs)(ss,{title:`Daily history · last 30`,accentClass:`accent-indigo`,headerExtras:s,children:[(0,U.jsx)(Qs,{rows:e,selectedDate:o,onSelect:r}),(0,U.jsx)(Ps,{row:f,variant:`daily`,accentClass:`accent-indigo`})]})}function tc(e,t){let n=t&&t.cost_usd>0?(e.cost_usd-t.cost_usd)/t.cost_usd:null;return{label:e.label,cost_usd:e.cost_usd,total_tokens:e.total_tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cache_creation_tokens:e.cache_creation_tokens,cache_read_tokens:e.cache_read_tokens,used_pct:null,dollar_per_pct:null,delta_cost_pct:n,is_current:e.is_today,models:e.models,cache_hit_pct:e.cache_hit_pct}}var nc=[`#d946ef`,`#c084fc`,`#60a5fa`,`#fbbf24`,`#22d3ee`],rc=`#64748b`,ic=5,ac=400,oc=150;function sc({trend:e,yMode:t,windowWeeks:n,onProjectSelect:r}){let i=(0,_.useMemo)(()=>{let t=Math.max(0,Math.min(n,e.window_weeks)),r=e.weeks.slice(-t),i=e.projects.map(e=>{let n=e.weekly_cost.slice(-t),r=n.reduce((e,t)=>e+t,0);return{key:e.key,weekly:n,cost:r,color:``}}).sort((e,t)=>t.cost-e.cost),a=i.slice(0,ic).map((e,t)=>({...e,color:nc[t]??rc})),o=i.slice(ic),s=r.map((e,t)=>o.reduce((e,n)=>e+(n.weekly[t]??0),0)),c=s.reduce((e,t)=>e+t,0),l=[...a];return o.length>0&&c>0&&l.push({key:`(other)`,weekly:s,cost:c,color:rc}),{weeks:r,series:l}},[e,n]),a=cn();if(i.weeks.length===0||i.series.length===0)return(0,U.jsxs)(`div`,{className:`panel-empty`,children:[`No project activity in the last `,n,` week`,n===1?``:`s`,`.`]});let o=i.weeks.length,s=i.weeks.map((e,t)=>i.series.reduce((e,n)=>e+(n.weekly[t]??0),0)),c=t===`share`?100:Math.max(...s,.01),l=(e,t=`left`)=>o<=1?t===`left`?ac*.1:ac*.9:e/(o-1)*ac,u=Array(o).fill(0),d=i.series.map(e=>{let n=[];for(let e=0;e<o;e++){let t=oc-u[e]/c*oc;n.push(`${l(e,`left`).toFixed(2)},${t.toFixed(2)}`),o===1&&n.push(`${l(e,`right`).toFixed(2)},${t.toFixed(2)}`)}for(let r=o-1;r>=0;r--){let i=s[r]??0,a=t===`share`?i>0?(e.weekly[r]??0)/i*100:0:e.weekly[r]??0;u[r]+=a;let d=oc-u[r]/c*oc;o===1&&n.push(`${l(r,`right`).toFixed(2)},${d.toFixed(2)}`),n.push(`${l(r,`left`).toFixed(2)},${d.toFixed(2)}`)}return{color:e.color,key:e.key,points:n.join(` `)}}),f=i.weeks.map(e=>(0,U.jsx)(`span`,{children:e.week_label},e.week_start_date));return(0,U.jsxs)(`div`,{className:`projects-trend`,children:[(0,U.jsx)(`svg`,{viewBox:`0 0 ${ac} ${oc}`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Stacked area: project ${t===`share`?`share %`:`cost`} over ${o} weeks`,children:d.map(e=>{let t=e.key===`(other)`;return(0,U.jsx)(`polygon`,{fill:e.color,opacity:t?.5:.65,points:e.points,"data-series-key":e.key,onClick:()=>{t||r?.(e.key)},style:{cursor:t?`default`:`pointer`}},e.key)})}),(0,U.jsx)(`div`,{className:`projects-trend-xaxis`,children:f}),(0,U.jsx)(`div`,{className:`projects-trend-legend`,children:i.series.map(e=>{let t=e.key===`(other)`,n=(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{className:`sw`,style:{background:e.color}}),e.key]});return a&&!t?(0,U.jsx)(`button`,{type:`button`,className:`projects-trend-legend-item`,"data-series-key":e.key,onClick:()=>r?.(e.key),children:n},e.key):(0,U.jsx)(`span`,{className:`projects-trend-legend-item`,"data-series-key":e.key,children:n},e.key)})})]})}function cc(e,t){let[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),c=W()?.generated_at??``,l=(0,_.useRef)(0),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(!1);return(0,_.useEffect)(()=>{if(!e){r(null),a(!1),s(null),l.current=0,u.current=null,d.current=null,f.current=!1;return}let i=u.current!==e||d.current!==t,o=i||n==null;if(o&&f.current&&!i)return;o&&(a(!0),s(null)),i&&(l.current=0),u.current=e,d.current=t,f.current=!0;let c=new AbortController,p=`/api/project/${encodeURIComponent(e)}?weeks=${t}`;return fetch(p,{signal:c.signal}).then(async e=>{if(e.status===404){l.current+=1,l.current>=2?(r(null),s(`Project no longer in cache — close this drill.`),a(!1)):o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1));return}if(!e.ok){o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1));return}l.current=0,r(await e.json()),s(null),a(!1)}).catch(e=>{e?.name!==`AbortError`&&o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1))}).finally(()=>{f.current=!1}),()=>c.abort()},[e,t,c]),{data:n,loading:i,error:o}}function lc({projectKey:e,windowWeeks:t}){let{data:n,loading:r,error:i}=cc(e,t),a=Wt(),o={tz:a.resolvedTz,offsetLabel:a.offsetLabel},s=n!=null&&(n.key!==e||n.window_weeks!==t);if(r&&!n||s)return(0,U.jsx)(`div`,{className:`panel-empty`,children:`Loading…`});if(i&&!n)return(0,U.jsx)(`div`,{className:`panel-empty`,children:i});if(!n)return null;let c=n.models[0]?.cost_usd??0,l=c>0?c:1,u=Math.max(0,n.sessions_total-n.sessions.length);return(0,U.jsxs)(`div`,{className:`projects-drill`,"data-testid":`projects-drill`,"aria-live":`polite`,children:[(0,U.jsx)(`div`,{className:`projects-drill-head`,children:(0,U.jsxs)(`span`,{className:`title`,children:[`▾ `,n.key,` · `,n.sessions_total,` session`,n.sessions_total===1?``:`s`,` · `,A.usd2(n.window_cost_usd),` (`,t,`w)`]})}),(0,U.jsxs)(`div`,{className:`projects-drill-grid`,children:[(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`section-label`,children:`Models (this project)`}),n.models.length===0?(0,U.jsx)(`div`,{className:`muted`,children:`No model data for this window.`}):n.models.map(e=>{let t={"--w":`${e.cost_usd/l*100}%`};return(0,U.jsxs)(`div`,{className:`drill-bar-row`,children:[(0,U.jsx)(`span`,{className:`chip ${dn(e.model)}`,children:e.model}),(0,U.jsx)(`div`,{className:`drill-bar`,style:t}),(0,U.jsx)(`span`,{className:`cost ${fn(e.cost_usd)}`,children:A.usd2(e.cost_usd)})]},e.model)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`section-label`,children:`Recent sessions →`}),n.sessions.length===0?(0,U.jsx)(`div`,{className:`muted`,children:`No sessions for this window.`}):n.sessions.map((e,t)=>(0,U.jsxs)(`button`,{"data-testid":`drill-session-${t}`,className:`drill-session-row`,onClick:()=>H({type:`OPEN_MODAL`,kind:`session`,sessionId:e.session_id}),children:[(0,U.jsx)(`span`,{className:`started`,children:A.datetimeShort(e.last_activity_at,o)}),(0,U.jsx)(`span`,{className:`chip ${dn(e.primary_model)}`,children:e.primary_model}),(0,U.jsx)(`span`,{className:`cost ${fn(e.cost_usd)}`,children:A.usd2(e.cost_usd)})]},e.session_id)),(0,U.jsxs)(`div`,{className:`drill-session-footer`,children:[u>0&&(0,U.jsxs)(`span`,{className:`muted`,children:[`+`,u,` more`]}),(0,U.jsx)(`button`,{type:`button`,"data-testid":`drill-show-in-sessions`,className:`drill-show-in-sessions`,onClick:()=>{H({type:`SET_FILTER`,text:n.key}),H({type:`CLOSE_MODAL`})},children:`Show in Sessions →`})]})]})]})]})}var uc=(e,t)=>e<t?-1:+(e>t),dc=[{id:`project`,label:`Project`,defaultDirection:`asc`,compare:(e,t)=>uc(e.key,t.key),className:`project`},{id:`sessions`,label:`Sessions`,defaultDirection:`desc`,numeric:!0,compare:(e,t)=>e.sessionsCount-t.sessionsCount},{id:`first_seen`,label:`First seen`,defaultDirection:`asc`,nullKey:e=>e.firstSeenAt,compare:(e,t)=>uc(e.firstSeenAt,t.firstSeenAt),className:`started`},{id:`last_seen`,label:`Last seen`,defaultDirection:`desc`,nullKey:e=>e.lastSeenAt,compare:(e,t)=>uc(e.lastSeenAt,t.lastSeenAt),className:`started`},{id:`cost`,label:`Cost`,defaultDirection:`desc`,numeric:!0,compare:(e,t)=>e.windowCost-t.windowCost},{id:`used_pct`,label:`Used %`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.windowPct,compare:(e,t)=>e.windowPct-t.windowPct},{id:`share_of_window`,label:`% of week`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.shareOfWindow,compare:(e,t)=>e.shareOfWindow-t.shareOfWindow}],fc=[{column:`cost`,direction:`desc`,label:`cost`,arrow:`↓`},{column:`sessions`,direction:`desc`,label:`sessions`,arrow:`↓`},{column:`used_pct`,direction:`desc`,label:`used`,arrow:`↓`},{column:`share_of_window`,direction:`desc`,label:`share`,arrow:`↓`},{column:`first_seen`,direction:`asc`,label:`first`,arrow:`↑`},{column:`last_seen`,direction:`desc`,label:`last`,arrow:`↓`},{column:`project`,direction:`asc`,label:`project`,arrow:`↑`}],pc=[1,4,8,12];function mc(){let e=W(),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=(0,_.useSyncExternalStore)(V,()=>B().openProjectKey),i=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsWindowWeeks),a=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsTrendYMode),o=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsSortOverride),[s,c]=(0,_.useState)(r??null),[l,u]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(r){c(r);return}s||c(e?.projects?.current_week?.rows?.[0]?.key??null)},[r,e?.projects?.current_week?.rows]),(0,_.useEffect)(()=>{r||s&&((e?.projects?.trend?.projects??[]).some(e=>e.key===s)||c(e?.projects?.current_week?.rows?.[0]?.key??null))},[r,s,e?.projects?.trend?.projects,e?.projects?.current_week?.rows]);let d=e?.projects?.trend??null,f=i,p=d?.window_weeks??0,m=(e,t)=>{H({type:`SAVE_PREFS`,patch:{[e]:t}})},h=e=>{c(t=>t===e?null:e)},g=(d?.projects??[]).map(e=>{let t=e.weekly_cost.slice(-i),n=e.weekly_pct.slice(-i),r=e.sessions_per_week.slice(-i),a=e.first_seen_per_week.slice(-i),o=e.last_seen_per_week.slice(-i),s=t.reduce((e,t)=>e+t,0),c=n.reduce((e,t)=>t==null?e:(e??0)+t,null),l=r.reduce((e,t)=>e+t,0),u=a.reduce((e,t)=>t==null?e:e==null||t<e?t:e,null),d=o.reduce((e,t)=>t==null?e:e==null||t>e?t:e,null);return{key:e.key,sessionsCount:l,firstSeenAt:u,lastSeenAt:d,windowCost:s,windowPct:c,shareOfWindow:null}}),v=g.reduce((e,t)=>e+t.windowCost,0);for(let e of g)e.shareOfWindow=v>0?e.windowCost/v*100:null;let y=o?se(g,dc,o):se(g,dc,{column:`cost`,direction:`desc`}),b=y.filter(e=>e.windowCost>0).slice(0,10),x=y.length-b.length,S=l?y:b,C=x>0,w=cn(),T=(()=>{if(!o)return 0;let e=fc.findIndex(e=>e.column===o.column&&e.direction===o.direction);return e===-1?0:e})(),E=()=>{let e=fc[(T+1)%fc.length];H({type:`SET_TABLE_SORT`,table:`projects`,override:{column:e.column,direction:e.direction}})},D=fc[T],O=()=>B().shareModal===null&&B().composerModal===null;return Ht([{key:`1`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,1)},{key:`4`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,4)},{key:`8`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,8)},{key:`0`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,12)},{key:`s`,scope:`modal`,when:O,action:()=>m(`projectsTrendYMode`,a===`share`?`absolute`:`share`)},{key:`ArrowUp`,scope:`modal`,when:O,action:()=>{if(S.length===0)return;let e=S.findIndex(e=>e.key===s);c(S[e<=0?S.length-1:e-1].key)}},{key:`ArrowDown`,scope:`modal`,when:O,action:()=>{if(S.length===0)return;let e=S.findIndex(e=>e.key===s);c(S[e===-1||e===S.length-1?0:e+1].key)}},{key:`Enter`,scope:`modal`,when:O,action:()=>{s?c(null):S.length>0&&c(S[0].key)}}]),(0,U.jsx)(ss,{title:`Projects · last ${i}w`,accentClass:`accent-magenta`,headerExtras:(0,U.jsx)(qt,{panel:`projects`,panelLabel:`Projects`,triggerId:`projects-modal`,dataTestId:`share-icon-projects-modal`,onClick:()=>H(R(`projects`,`projects-modal`,{windowWeeks:i}))}),children:(0,U.jsxs)(`div`,{className:`projects-modal-body`,children:[(0,U.jsxs)(`div`,{className:`projects-controls`,role:`radiogroup`,"aria-label":`Window`,children:[pc.map(e=>(0,U.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":i===e,className:`pill ${i===e?`on`:``}`,onClick:()=>m(`projectsWindowWeeks`,e),children:[e,`w`]},`window-${e}`)),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`|`}),(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":a===`share`,className:`pill ${a===`share`?`on`:``}`,onClick:()=>m(`projectsTrendYMode`,`share`),children:`share %`}),(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":a===`absolute`,className:`pill ${a===`absolute`?`on`:``}`,onClick:()=>m(`projectsTrendYMode`,`absolute`),children:`$ absolute`})]}),p>0&&p<f&&(0,U.jsxs)(`div`,{className:`projects-notice`,children:[`Showing `,p,` week`,p===1?``:`s`,` (need more history for the full window).`]}),d?(0,U.jsx)(sc,{trend:d,yMode:a,windowWeeks:i,onProjectSelect:e=>c(e)}):(0,U.jsx)(`div`,{className:`panel-empty`,children:`Projects trend unavailable.`}),w&&(0,U.jsxs)(`button`,{type:`button`,className:`projects-mobile-sort`,"data-testid":`projects-mobile-sort`,onClick:E,"aria-label":`Cycle sort column`,children:[`Sort: `,D.label,` `,D.arrow]}),(0,U.jsxs)(`table`,{className:`projects-table`,children:[(0,U.jsx)(rn,{columns:dc,override:o,onChange:e=>H({type:`SET_TABLE_SORT`,table:`projects`,override:e}),accentVar:`--accent-magenta`}),(0,U.jsx)(`tbody`,{children:S.map(e=>(0,U.jsxs)(_.Fragment,{children:[(0,U.jsxs)(`tr`,{"data-testid":`projects-table-row`,"data-cost":e.windowCost,"data-sessions":e.sessionsCount,"aria-expanded":s===e.key,className:s===e.key?`selected`:``,onClick:()=>h(e.key),children:[(0,U.jsx)(`td`,{className:`project`,children:e.key}),(0,U.jsx)(`td`,{children:e.sessionsCount}),(0,U.jsx)(`td`,{className:`started first-seen`,children:A.dateShort(e.firstSeenAt,n)??`—`}),(0,U.jsx)(`td`,{className:`started last-seen`,children:A.dateShort(e.lastSeenAt,n)??`—`}),(0,U.jsx)(`td`,{className:fn(e.windowCost),children:A.usd2(e.windowCost)}),(0,U.jsx)(`td`,{children:e.windowPct==null?`—`:A.pct0(e.windowPct)}),(0,U.jsx)(`td`,{children:e.shareOfWindow==null?`—`:A.pct0(e.shareOfWindow)})]}),w&&s===e.key&&(0,U.jsx)(`tr`,{className:`projects-drill-row`,"aria-hidden":`false`,children:(0,U.jsx)(`td`,{colSpan:7,children:(0,U.jsx)(lc,{projectKey:e.key,windowWeeks:i})})})]},e.key))})]}),C&&(0,U.jsx)(`button`,{type:`button`,className:`projects-table-toggle`,"data-testid":`projects-table-toggle`,"aria-expanded":l,onClick:()=>u(e=>!e),children:l?`Show top 10 active`:`Show all ${y.length} projects (+${x})`}),!w&&s&&(0,U.jsx)(lc,{projectKey:s,windowWeeks:i}),(0,U.jsxs)(`div`,{className:`projects-modal-footer-hint`,"data-testid":`projects-modal-footer-hint`,"aria-live":`off`,children:[(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`1`}),`/`,(0,U.jsx)(`kbd`,{children:`4`}),`/`,(0,U.jsx)(`kbd`,{children:`8`}),`/`,(0,U.jsx)(`kbd`,{children:`0`}),` window`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`↑↓`}),` row`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`Enter`}),` drill`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`s`}),` share/$`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`Esc`}),` close`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsx)(vt,{})]})]})})}function hc({cr:e}){let t=e.today.baseline_daily_row_count<5,n=e.today.anomaly_triggered&&!t,r;r=t?{text:`~ Building baseline · ${e.today.baseline_daily_row_count}/5 days`,cls:`thin`}:n?{text:`⚠ Anomaly`,cls:``}:{text:`✓ Healthy`,cls:`ok`};let i=e.today.baseline_median_percent,a=e.today.delta_pp,o;if(a===null)o=`—`;else{let e=A.pctFloor(Math.abs(a));o=`${a<0?`−`:`+`}${e}pp`}return(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-spotlight`,children:[`Today's spotlight`,(0,U.jsxs)(`span`,{className:`meta`,children:[e.today.date,` · `,e.days.length,` days observed`]})]}),(0,U.jsxs)(`div`,{className:`crm-spotlight${n?` anom`:``}`,children:[(0,U.jsxs)(`div`,{className:`crm-spotlight-row`,children:[(0,U.jsx)(`span`,{className:`pill${r.cls?` `+r.cls:``}`,children:r.text}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache hit`}),` `,(0,U.jsxs)(`strong`,{children:[A.pctFloor(e.today.cache_hit_percent),`%`]})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`14d median`}),` `,(0,U.jsx)(`strong`,{children:i===null?`—`:`${A.pctFloor(i)}%`})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Δ`}),` `,(0,U.jsx)(`strong`,{children:o})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Net`}),` `,(0,U.jsx)(`strong`,{children:A.usdSigned(e.today.net_usd)})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Saved / Wasted`}),` `,(0,U.jsxs)(`strong`,{children:[`$`,e.today.saved_usd.toFixed(2),` / $`,e.today.wasted_usd.toFixed(2)]})]})]}),n&&e.today.anomaly_reasons.length>0&&(0,U.jsxs)(`div`,{className:`reasons`,children:[`Reasons:`,` `,e.today.anomaly_reasons.map((e,t)=>(0,U.jsxs)(`span`,{children:[t>0&&` · `,(0,U.jsx)(`code`,{children:e})]},e)),` | `,`thresholds: `,e.anomaly_threshold_pp,`pp drop, net < 0`]})]})]})}function gc(e,t=28){if(e.length<=t)return e;let n=e.split(`/`).filter(Boolean);if(n.length<=2)return e;let r=`/`+n[0],i=`${r}/…/${n.slice(-2).join(`/`)}`;return i.length<=t||(i=`${r}/…/${n[n.length-1]}`,i.length<=t)?i:`…/${n[n.length-1]}`}function q({kind:e,rows:t}){let n=e===`projects`?`bd-projects`:`bd-models`,r=e===`projects`?`By project`:`By model`,i=e===`projects`?`No project activity in this window`:`No model activity in this window`,a=e===`projects`;return(0,U.jsxs)(`div`,{className:`crm-bd-card ${n}`,"data-bd-kind":e,children:[(0,U.jsx)(`div`,{className:`crm-bd-head`,children:r}),t.length===0?(0,U.jsx)(`div`,{className:`empty`,children:i}):(0,U.jsx)(`table`,{children:(0,U.jsx)(`tbody`,{children:t.map(e=>{let t=a?gc(e.key):e.key,n=t!==e.key;return(0,U.jsxs)(`tr`,{"data-testid":`crm-bd-row`,"data-bd-key":e.key,children:[(0,U.jsx)(`td`,{className:`bd-key`,title:n?e.key:void 0,children:t}),(0,U.jsxs)(`td`,{children:[A.pctFloor(e.cache_hit_percent),`%`]}),(0,U.jsx)(`td`,{className:e.net_usd>=0?`net-pos`:`net-neg`,children:A.usdSigned(e.net_usd)})]},e.key)})})})]})}function _c({current_threshold_pp:e,onClose:t}){let[n,r]=(0,_.useState)(String(e)),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),u=(0,_.useRef)(null);(0,_.useEffect)(()=>{function e(e){let n=e.target;n&&n.closest(`[data-cr-settings-toggle]`)||u.current&&!u.current.contains(e.target)&&t()}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t]),(0,_.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopPropagation(),t())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[t]);async function d(){l(!1);let e=n.trim(),t=/^-?\d+$/.test(e)?parseInt(e,10):NaN;if(!Number.isInteger(t)||t<1||t>100){a(`Must be an integer between 1 and 100`);return}s(!0),a(null);try{let e=await fetch(`/api/settings`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cache_report:{anomaly_threshold_pp:t}})});if(e.ok)l(!0),setTimeout(()=>l(!1),1500);else{let t=await e.json().catch(()=>({}));a(typeof t.error==`string`?t.error:`HTTP ${e.status}`)}}catch(e){a(String(e))}finally{s(!1)}}return(0,U.jsxs)(`div`,{ref:u,className:`crm-settings-popover`,role:`dialog`,"aria-label":`Cache Report settings`,children:[(0,U.jsx)(`h4`,{children:`Cache Report settings`}),(0,U.jsx)(`label`,{htmlFor:`cr-threshold`,children:`Anomaly threshold (pp)`}),(0,U.jsx)(`input`,{id:`cr-threshold`,type:`number`,inputMode:`numeric`,min:1,max:100,value:n,onChange:e=>{r(e.target.value),a(null),l(!1)},className:i?`invalid`:``}),i&&(0,U.jsx)(`div`,{className:`err`,children:i}),c&&(0,U.jsx)(`div`,{className:`saved`,children:`Saved · next sync will re-evaluate`}),(0,U.jsxs)(`div`,{className:`actions`,children:[(0,U.jsx)(`button`,{onClick:t,type:`button`,children:`Close`}),(0,U.jsx)(`button`,{className:`primary`,onClick:d,disabled:o,type:`button`,children:o?`Saving…`:`Save`})]})]})}function vc(){let e=W()?.cache_report,[t,n]=(0,_.useState)(!1);if(!e)return(0,U.jsx)(ss,{title:`Cache Report`,accentClass:`accent-teal`,children:(0,U.jsx)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:`Loading…`})});if(e.is_empty)return(0,U.jsx)(ss,{title:`Cache Report`,accentClass:`accent-teal`,children:(0,U.jsxs)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:[`No Claude activity in the last `,e.window_days,` days.`]})});let r=(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`span`,{className:`sub`,style:{marginRight:12,color:`var(--text-dim)`},children:[`Last `,e.window_days,` days · `,e.anomaly_window_days,`d baseline · Claude only`]}),(0,U.jsx)(`button`,{type:`button`,"aria-label":`Cache Report settings`,"data-cr-settings-toggle":!0,onClick:e=>{e.stopPropagation(),n(e=>!e)},style:{background:`transparent`,border:0,color:`var(--text-dim)`,cursor:`pointer`,fontSize:18,padding:`0 8px`},children:`⚙`})]}),i=e.today.baseline_daily_row_count<5,a=e.today.anomaly_triggered&&!i,o=a?`var(--accent-amber)`:`var(--accent-green)`,s=a?`accent-amber`:`accent-teal`,c=Math.round(e.fourteen_day_efficiency_ratio*100);return(0,U.jsxs)(ss,{title:`Cache Report`,accentClass:s,headerExtras:r,children:[t&&(0,U.jsx)(_c,{current_threshold_pp:e.anomaly_threshold_pp,onClose:()=>n(!1)}),(0,U.jsx)(hc,{cr:e}),(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-timeline`,children:[`Cache hit % — `,e.window_days,`-day timeline`,(0,U.jsxs)(`span`,{className:`meta`,children:[`band = `,e.anomaly_window_days,`d median ±`,5,`pp`]})]}),(0,U.jsx)(`div`,{className:`crm-chart-frame timeline`,children:(0,U.jsx)(Rn,{days:e.days,baseline_median_percent:e.today.baseline_median_percent,today_marker_color:o,size:`large`})})]}),(0,U.jsx)(Bn,{days:e.days,size:`large`}),(0,U.jsxs)(`div`,{className:`crm-counterfactual`,children:[`Without caching, you'd have paid`,` `,(0,U.jsxs)(`strong`,{children:[`+$`,e.fourteen_day_counterfactual_usd.toFixed(2),` more`]}),` `,`over the last `,e.window_days,` days · cache efficiency`,` `,(0,U.jsxs)(`span`,{title:`saved / (saved + |wasted|) = ${c}%`,children:[c,`%`]})]}),(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-table`,children:[`Daily rows · `,e.window_days,` days`,(0,U.jsxs)(`span`,{className:`meta`,children:[e.days.length,` days observed`]})]}),(0,U.jsxs)(`table`,{className:`ch-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{className:`c-date`,children:`Date`}),(0,U.jsx)(`th`,{className:`c-hit num`,children:`Cache %`}),(0,U.jsx)(`th`,{className:`c-tokens num`,children:`Tok In`}),(0,U.jsx)(`th`,{className:`c-tokens num`,children:`Tok Out`}),(0,U.jsx)(`th`,{className:`c-saved num`,children:`Saved`}),(0,U.jsx)(`th`,{className:`c-wasted num`,children:`Wasted`}),(0,U.jsx)(`th`,{className:`c-net num`,children:`Net`}),(0,U.jsx)(`th`,{className:`c-flag num`,children:`Flag`})]})}),(0,U.jsx)(`tbody`,{children:e.days.map(t=>{let n=t.date===e.today.date,r=e.today.baseline_median_percent!==null,i=r&&e.today.baseline_median_percent!==null&&t.cache_hit_percent<e.today.baseline_median_percent-5,a=t.net_usd<0;return(0,U.jsxs)(`tr`,{className:n?`cur`:``,"data-testid":`crm-daily-row`,"data-date":t.date,children:[(0,U.jsx)(`td`,{children:t.date}),(0,U.jsxs)(`td`,{className:`num ${r?i?`hit-bad`:`hit-good`:``}`.trim(),children:[A.pctFloor(t.cache_hit_percent),`%`]}),(0,U.jsx)(`td`,{className:`num`,children:A.compact(t.input_tokens,{upper:!0})}),(0,U.jsx)(`td`,{className:`num`,children:A.compact(t.output_tokens,{upper:!0})}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(t.saved_usd)}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(t.wasted_usd)}),(0,U.jsx)(`td`,{className:`num ${a?`net-neg`:`net-pos`}`,children:A.usdSigned(t.net_usd)}),(0,U.jsx)(`td`,{className:`num ${t.anomaly_triggered?`flag-warn`:`flag-ok`}`,children:t.anomaly_triggered?`⚠`:`✓`})]},t.date)})})]})]}),(0,U.jsx)(`div`,{className:`crm-section`,children:(0,U.jsxs)(`div`,{className:`crm-breakdowns`,children:[(0,U.jsx)(q,{kind:`projects`,rows:e.by_project}),(0,U.jsx)(q,{kind:`models`,rows:e.by_model})]})})]})}var yc=100;function bc({alert:e,ctx:t}){if(e.axis===`weekly`){let n=e.context.week_start_date?A.weekStart(e.context.week_start_date,t):null,r=e.context.dollars_per_percent;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--weekly`,children:[n?`Week of ${n}`:`Week —`,r!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[`$`,r.toFixed(2),`/1%`]})]})]})}if(e.axis===`budget`){let n=Mn(e.context.period),r=e.context.period_start_at??e.context.week_start_at,i=r?A.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`codex_budget`){let n=Mn(e.context.period),r=e.context.period_start_at,i=r?A.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--codex_budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`project_budget`){let t=e.context.project??`(project)`,n=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--project_budget`,children:[t,n!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(n),`% of budget`]})]})]})}return e.axis===`projected`?(0,U.jsx)(`span`,{className:`alert-context alert-context--projected`,children:Pn(e)??`Projected —`}):(0,U.jsxs)(`span`,{className:`alert-context alert-context--five-hour`,children:[`Block `,e.context.block_start_at?A.timeOnly(e.context.block_start_at,t):`—`]})}function xc({alert:e}){if(e.axis===`projected`)return(0,U.jsx)(`span`,{className:`num`,children:`—`});let t;return t=e.axis===`weekly`?e.context.cumulative_cost_usd:e.axis===`budget`||e.axis===`project_budget`||e.axis===`codex_budget`?e.context.spent_usd:e.context.block_cost_usd,(0,U.jsx)(`span`,{className:`num`,children:A.usd2(t??null)})}function Sc(){let e=(0,_.useSyncExternalStore)(V,()=>B().alerts),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e.slice(0,yc);return r.length===0?(0,U.jsx)(ss,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No alerts yet. Alerts appear when usage crosses 90% or 95%.`})}):(0,U.jsx)(ss,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,U.jsxs)(`div`,{className:`alerts-modal-body`,children:[(0,U.jsxs)(`table`,{className:`alerts-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{scope:`col`,children:`%`}),(0,U.jsx)(`th`,{scope:`col`,children:`Axis`}),(0,U.jsx)(`th`,{scope:`col`,children:`Cost`}),(0,U.jsx)(`th`,{scope:`col`,children:`Context`}),(0,U.jsx)(`th`,{scope:`col`,children:`Alerted`})]})}),(0,U.jsx)(`tbody`,{children:r.map(e=>{let t=Nn(e);return(0,U.jsxs)(`tr`,{className:`alert-modal-row`,children:[(0,U.jsxs)(`td`,{className:`alert-threshold severity-${t} ${t} num`,children:[e.threshold,`%`]}),(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`chip chip--${e.axis}`,children:An[e.axis]})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(xc,{alert:e})}),(0,U.jsx)(`td`,{children:(0,U.jsx)(bc,{alert:e,ctx:n})}),(0,U.jsx)(`td`,{className:`alert-when`,children:A.relativeOrAbsolute(e.alerted_at,n)})]},e.id)})})]}),e.length>yc&&(0,U.jsxs)(`div`,{className:`alerts-modal-foot`,children:[`Showing `,yc,` of `,e.length,` most recent`]})]})})}function Cc(){let e=(0,_.useSyncExternalStore)(V,()=>B().openModal);if(!e)return null;switch(e){case`current-week`:return(0,U.jsx)(ms,{});case`forecast`:return(0,U.jsx)(bs,{});case`trend`:return(0,U.jsx)(ks,{});case`session`:return(0,U.jsx)(Ms,{});case`weekly`:return(0,U.jsx)(zs,{});case`monthly`:return(0,U.jsx)(Bs,{});case`block`:return(0,U.jsx)(Xs,{});case`daily`:return(0,U.jsx)(ec,{});case`projects`:return(0,U.jsx)(mc,{});case`alerts`:return(0,U.jsx)(Sc,{});case`cache-report`:return(0,U.jsx)(vc,{})}}var wc=class extends Error{code;constructor(e,t,n,r){super(n),this.status=e,this.field=t,this.code=r}};async function Tc(e){if(!e.ok){let t={};try{t=await e.json()}catch{}throw new wc(e.status,t.field,t.error??`HTTP ${e.status}`,t.code)}return e.json()}async function Ec(e,t){return Tc(await fetch(`/api/share/templates?panel=${encodeURIComponent(e)}`,{signal:t?.signal}))}async function Dc(e,t){return Tc(await fetch(`/api/share/render`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}var Oc=[{id:`recap`,label:`Recap`,placeholderDescription:`Text + tiny chart`},{id:`visual`,label:`Visual`,placeholderDescription:`Coming in M2`},{id:`detail`,label:`Detail`,placeholderDescription:`Coming in M2`}];function kc(e){return e.endsWith(`-recap`)?`recap`:e.endsWith(`-visual`)?`visual`:e.endsWith(`-detail`)?`detail`:null}function Ac({panel:e,templates:t,error:n,selectedTemplateId:r,onSelect:i}){if(n)return(0,U.jsx)(`div`,{className:`share-gallery-error`,role:`alert`,children:n});let a={};for(let e of t??[]){let t=kc(e.id);t&&(a[t]=e)}return(0,U.jsx)(`div`,{className:`share-gallery`,role:`radiogroup`,"aria-label":`Report template`,children:Oc.map(e=>{let n=a[e.id];if(t==null)return(0,U.jsxs)(`div`,{className:`share-tile share-tile-skeleton`,"aria-hidden":`true`,children:[(0,U.jsx)(`div`,{className:`share-tile-skeleton-bar`}),(0,U.jsx)(`div`,{className:`share-tile-skeleton-bar short`})]},e.id);if(!n)return(0,U.jsxs)(`button`,{type:`button`,className:`share-tile share-tile-disabled`,disabled:!0,"aria-disabled":`true`,role:`radio`,"aria-checked":`false`,title:`${e.label} — ${e.placeholderDescription}`,children:[(0,U.jsx)(`div`,{className:`share-tile-label`,children:e.label}),(0,U.jsx)(`div`,{className:`share-tile-desc`,children:e.placeholderDescription})]},e.id);let o=n.id===r;return(0,U.jsxs)(`button`,{type:`button`,className:`share-tile`+(o?` share-tile-selected`:``),role:`radio`,"aria-checked":o,"data-template-id":n.id,onClick:()=>i(n.id),children:[(0,U.jsx)(`div`,{className:`share-tile-label`,children:n.label}),(0,U.jsx)(`div`,{className:`share-tile-desc`,children:n.description})]},e.id)})})}function jc({options:e,onChange:t}){let n=n=>t({...e,...n}),r=n=>t({...e,period:{...e.period,...n}}),i=e=>{if(e===``){n({top_n:null});return}let t=Number.parseInt(e,10);Number.isNaN(t)||n({top_n:Math.max(1,t)})};return(0,U.jsxs)(`div`,{className:`share-knobs`,children:[(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`label`,{htmlFor:`share-knob-period`,children:`Period`}),(0,U.jsxs)(`select`,{id:`share-knob-period`,value:e.period.kind,onChange:e=>r({kind:e.target.value}),children:[(0,U.jsx)(`option`,{value:`current`,children:`This week`}),(0,U.jsx)(`option`,{value:`previous`,children:`Previous week`}),(0,U.jsx)(`option`,{value:`custom`,children:`Custom`})]}),e.period.kind===`custom`?(0,U.jsxs)(`div`,{className:`share-knob-period-custom`,children:[(0,U.jsxs)(`label`,{className:`share-knob-sublabel`,children:[(0,U.jsx)(`span`,{children:`Start`}),(0,U.jsx)(`input`,{type:`date`,value:e.period.start?.slice(0,10)??``,onChange:e=>r({start:e.target.value}),"aria-label":`Custom period start date`})]}),(0,U.jsxs)(`label`,{className:`share-knob-sublabel`,children:[(0,U.jsx)(`span`,{children:`End`}),(0,U.jsx)(`input`,{type:`date`,value:e.period.end?.slice(0,10)??``,onChange:e=>r({end:e.target.value}),"aria-label":`Custom period end date`})]})]}):null]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`span`,{className:`share-knob-label`,children:`Theme`}),(0,U.jsxs)(`div`,{className:`share-knob-radiogroup`,role:`radiogroup`,"aria-label":`Theme`,children:[(0,U.jsxs)(`label`,{className:`share-knob-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-theme`,value:`light`,checked:e.theme===`light`,onChange:()=>n({theme:`light`})}),(0,U.jsx)(`span`,{children:`Light`})]}),(0,U.jsxs)(`label`,{className:`share-knob-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-theme`,value:`dark`,checked:e.theme===`dark`,onChange:()=>n({theme:`dark`})}),(0,U.jsx)(`span`,{children:`Dark`})]})]})]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`label`,{htmlFor:`share-knob-topn`,children:`Top-N`}),(0,U.jsx)(`input`,{id:`share-knob-topn`,type:`number`,min:1,step:1,inputMode:`numeric`,value:e.top_n??``,onChange:e=>i(e.target.value),"aria-label":`Top-N`})]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`span`,{className:`share-knob-label`,children:`Projects`}),(0,U.jsx)(`button`,{type:`button`,className:`share-knob-allowlist-stub`,disabled:!0,"aria-disabled":`true`,title:`Project allowlist — coming in M3+`,children:`All projects`})]}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:e.show_chart,onChange:e=>n({show_chart:e.target.checked}),"aria-label":`Include chart in export`}),(0,U.jsx)(`span`,{children:`Show chart`})]})}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:e.show_table,onChange:e=>n({show_table:e.target.checked}),"aria-label":`Include table in export`}),(0,U.jsx)(`span`,{children:`Show table`})]})}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:!e.reveal_projects,onChange:e=>n({reveal_projects:!e.target.checked}),"aria-label":`Anonymize project names on export`}),(0,U.jsx)(`span`,{children:`Anon on export`})]})})]})}var Mc=200,Nc={status:`idle`,body:``,contentType:``,errorMessage:null,errorField:null};function Pc({panel:e,templateId:t,options:n}){let[r,i]=(0,_.useState)(Nc),a=(0,_.useRef)(null),o=(0,_.useRef)(0);return(0,_.useEffect)(()=>{if(!t){i(Nc);return}i(e=>({...e,status:`loading`}));let r=++o.current,s=setTimeout(()=>{a.current?.abort();let s=new AbortController;a.current=s,Dc({panel:e,template_id:t,options:{...n,reveal_projects:!0}},{signal:s.signal}).then(e=>{r===o.current&&i({status:`ready`,body:e.body,contentType:e.content_type,errorMessage:null,errorField:null})}).catch(e=>{if(r===o.current&&!(e&&typeof e==`object`&&e.name===`AbortError`)){if(e instanceof wc){i({status:`error`,body:``,contentType:``,errorMessage:e.message??`HTTP ${e.status}`,errorField:e.field??null});return}i({status:`error`,body:``,contentType:``,errorMessage:e.message??`Unknown error`,errorField:null})}})},Mc);return()=>{clearTimeout(s)}},[e,t,n]),(0,_.useEffect)(()=>()=>{a.current?.abort()},[]),t?r.status===`error`?(0,U.jsxs)(`div`,{className:`share-preview share-preview-error`,role:`alert`,children:[(0,U.jsx)(`div`,{className:`share-preview-error-title`,children:`Preview failed`}),(0,U.jsxs)(`div`,{className:`share-preview-error-message`,children:[r.errorMessage,r.errorField?(0,U.jsxs)(`span`,{className:`share-preview-error-field`,children:[` `,`(field: `,r.errorField,`)`]}):null]})]}):r.status===`loading`||r.status===`idle`?(0,U.jsx)(`div`,{className:`share-preview share-preview-loading`,"aria-busy":`true`,children:`Rendering preview…`}):n.format===`md`?(0,U.jsx)(`pre`,{className:`share-preview share-preview-md`,"aria-label":`Markdown preview`,children:r.body}):(0,U.jsx)(`iframe`,{className:`share-preview share-preview-iframe`,title:`Report preview (decorative)`,tabIndex:-1,sandbox:`allow-same-origin`,srcDoc:r.body}):(0,U.jsx)(`div`,{className:`share-preview share-preview-empty`,children:`Select a template to preview.`})}var Fc={"current-week":`Current week`,trend:`Trend`,weekly:`Weekly`,daily:`Daily`,monthly:`Monthly`,blocks:`5-hour blocks`,forecast:`Forecast`,sessions:`Sessions`,projects:`Projects`};function Ic(e){return Fc[e]}function Lc(e){switch(e){case`md`:return`md`;case`html`:return`html`;case`svg`:return`svg`}}async function Rc(e){if(!e.ok){let t={};try{t=await e.json()}catch{}throw new wc(e.status,t.field,t.error??`HTTP ${e.status}`)}return e.json()}async function zc(e){return Rc(await fetch(`/api/share/presets`,{signal:e?.signal}))}async function Bc(e,t){return Rc(await fetch(`/api/share/presets`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}async function Vc(e,t,n){let r=await fetch(`/api/share/presets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`,signal:n?.signal});if(!r.ok){let e={};try{e=await r.json()}catch{}throw new wc(r.status,void 0,e.error??`HTTP ${r.status}`)}}async function Hc(e){return Rc(await fetch(`/api/share/history`,{signal:e?.signal}))}async function Uc(e,t){return Rc(await fetch(`/api/share/history`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}function Wc({panel:e,templateId:t,options:n,onSaved:r,onCancel:i}){let[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(null);async function d(){let i=a.trim();if(!i){u(`Name is required`);return}if(i.length>64){u(`Name must be 64 characters or fewer`);return}if(i.includes(`/`)){u(`Name cannot contain '/'`);return}c(!0),u(null);try{await Bc({panel:e,name:i,template_id:t,options:n}),H({type:`SHOW_STATUS_TOAST`,text:`Saved preset "${i}"`}),r()}catch(e){u((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Save failed`)}finally{c(!1)}}return(0,U.jsxs)(`div`,{className:`share-save-popover`,role:`dialog`,"aria-label":`Save preset`,children:[(0,U.jsxs)(`label`,{className:`share-save-label`,children:[`Preset name`,(0,U.jsx)(`input`,{type:`text`,className:`share-save-input`,autoFocus:!0,value:a,maxLength:64,disabled:s,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),d()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i())}})]}),l?(0,U.jsx)(`div`,{className:`share-save-error`,role:`alert`,children:l}):null,(0,U.jsxs)(`div`,{className:`share-save-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:i,disabled:s,children:`Cancel`}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>void d(),disabled:s,children:s?`Saving…`:`Save`})]})]})}async function Gc(e,t,n){let r=new Blob([e],{type:`image/svg+xml`}),i=URL.createObjectURL(r);try{let e=new Image;e.src=i,await e.decode();let r=document.createElement(`canvas`);r.width=e.naturalWidth*t,r.height=e.naturalHeight*t;let a=r.getContext(`2d`);if(!a)throw Error(`Could not acquire 2D canvas context`);a.fillStyle=n,a.fillRect(0,0,r.width,r.height),a.scale(t,t),a.drawImage(e,0,0);let o=await new Promise(e=>{r.toBlob(t=>e(t),`image/png`)});if(o)return o;let s=r.toDataURL(`image/png`);return(await fetch(s)).blob()}finally{URL.revokeObjectURL(i)}}function J(e){let t=document.createElement(`iframe`);t.setAttribute(`aria-hidden`,`true`),t.style.cssText=`position:fixed;right:0;bottom:0;width:0;height:0;border:0`,document.body.appendChild(t);let n=t.contentDocument;if(!n)throw Error(`iframe contentDocument unavailable`);n.open(),n.write(e),n.close();try{t.contentWindow?.focus(),t.contentWindow?.print()}catch{let t=window.open(``,`_blank`,`noopener,noreferrer`);t&&(t.document.open(),t.document.write(e),t.document.close())}setTimeout(()=>t.remove(),1e3)}function Kc(e){Uc({panel:e.panel,template_id:e.template_id,options:e.options,format:e.options.format,destination:e.destination}).catch(()=>{})}function qc(e){return e===`light`?`#ffffff`:`#0f172a`}function Jc(e,t){return`cctally-${e}-${new Date().toISOString().slice(0,10).replaceAll(`-`,``)}.${Lc(t)}`}function Yc(e){switch(e){case`md`:return`text/markdown;charset=utf-8`;case`html`:return`text/html;charset=utf-8`;case`svg`:return`image/svg+xml;charset=utf-8`}}function Xc(e,t){let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.style.display=`none`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),0)}function Zc({panel:e,templateId:t,options:n,onOptionsChange:r}){let[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(!1),u=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{u.current!=null&&clearTimeout(u.current)},[]);let[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!d)return;function e(e){let t=p.current;t&&(t.contains(e.target)||f(!1))}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[d]),(0,_.useEffect)(()=>{s(null)},[n.format,t]);let m=t==null||i!=null,h=e=>H({type:`SHOW_STATUS_TOAST`,text:e}),g=async()=>{if(!t)throw Error(`no template selected`);return{body:(await Dc({panel:e,template_id:t,options:n})).body,format:n.format}},v=async()=>{if(!(m||!t)){a(`copy`),s(null);try{let{body:r}=await g();if(!navigator.clipboard||typeof navigator.clipboard.writeText!=`function`)throw Error(`Clipboard API unavailable in this browser`);await navigator.clipboard.writeText(r),h(`Copied`),Kc({panel:e,template_id:t,options:n,destination:`copy`})}catch(e){s(`Copy failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},y=async()=>{if(!(m||!t)){a(`download`),s(null);try{let{body:r,format:i}=await g(),a=new Blob([r],{type:Yc(i)});Xc(Jc(e,i),a),h(`Downloaded`),Kc({panel:e,template_id:t,options:n,destination:`download`})}catch(e){s(`Download failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},b=async()=>{if(!(m||!t)){a(`basket`),s(null);try{let r=await Dc({panel:e,template_id:t,options:n}),i=_e({panel:e,template_id:t,options:n,added_at:new Date().toISOString(),data_digest_at_add:r.snapshot.data_digest,kernel_version:r.snapshot.kernel_version,label_hint:Ic(e)});H({type:`BASKET_ADD`,item:i});let a=B().basket;if(a.rejectedReason===`capacity`)return;l(!0),u.current!=null&&clearTimeout(u.current),u.current=setTimeout(()=>l(!1),800),H({type:`SHOW_STATUS_TOAST`,text:`Added ${i.label_hint} to basket (${a.items.length})`})}catch(e){s(`Add to basket failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},x=async()=>{if(!(m||!t)){a(`open`),s(null);try{let{body:r,format:i}=await g(),a=new Blob([r],{type:Yc(i)}),o=URL.createObjectURL(a);window.open(o,`_blank`,`noopener,noreferrer`),Kc({panel:e,template_id:t,options:n,destination:`open`})}catch(e){s(`Open failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},S=async()=>{if(!(!t||n.format!==`svg`||m)){a(`png`),s(null);try{let{body:r}=await g(),i=await Gc(r,2,qc(n.theme));Xc(Jc(e,`svg`).replace(/\.svg$/,`.png`),i),h(`PNG downloaded`),Kc({panel:e,template_id:t,options:n,destination:`png`})}catch(e){s(`PNG export failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},C=async()=>{if(!(!t||n.format!==`html`||m)){a(`print`),s(null);try{let{body:r}=await g();J(r),Kc({panel:e,template_id:t,options:n,destination:`print`})}catch(e){s(`Print failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},w=n.format===`md`&&!m,T=(n.format===`html`||n.format===`svg`)&&!m,E=n.format===`svg`&&!m,D=n.format===`html`&&!m;return(0,U.jsxs)(`div`,{className:`share-actions`,children:[(0,U.jsxs)(`div`,{className:`share-format-row`,role:`radiogroup`,"aria-label":`Export format`,children:[(0,U.jsx)(`span`,{className:`share-format-label`,children:`Format:`}),[`md`,`html`,`svg`].map(e=>(0,U.jsxs)(`label`,{className:`share-format-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-format`,value:e,checked:n.format===e,onChange:()=>r({...n,format:e})}),(0,U.jsx)(`span`,{children:e})]},e))]}),(0,U.jsxs)(`div`,{className:`share-action-row`,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-copy`,onClick:v,disabled:!w,title:n.format===`md`?i===`copy`?`Copying…`:`Copy to clipboard`:`Copy is available for Markdown only`,children:i===`copy`?`Copying…`:`Copy`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-download`,onClick:y,disabled:m,title:i===`download`?`Downloading…`:`Download file`,children:i===`download`?`Downloading…`:`Download`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-open`,onClick:x,disabled:!T,title:n.format===`html`||n.format===`svg`?i===`open`?`Opening…`:`Open in new tab`:`Open is available for HTML/SVG`,children:i===`open`?`Opening…`:`Open`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-png`,onClick:S,disabled:!E,title:n.format===`svg`?i===`png`?`Rasterizing…`:`Download PNG (rasterized from SVG)`:`PNG export — available for SVG format only`,children:i===`png`?`Rasterizing…`:`PNG`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-print`,onClick:C,disabled:!D,title:n.format===`html`?i===`print`?`Opening print dialog…`:`Open the browser print dialog (save as PDF)`:`Print → PDF — available for HTML format only`,children:i===`print`?`Printing…`:`Print → PDF`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-basket${c?` share-action-basket-added`:``}`,onClick:b,disabled:m,title:m&&t==null?`Pick a template first`:i===`basket`?`Adding to basket…`:`Add this section to the report basket`,children:c?`✓ Added`:i===`basket`?`Adding…`:`+ Basket`})]}),(0,U.jsxs)(`div`,{className:`share-save-preset-row`,ref:p,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-save-preset`,disabled:t==null||i!=null,onClick:()=>f(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":d,title:t==null?`Pick a template first`:`Save the current recipe as a named preset`,children:`Save preset…`}),d&&t?(0,U.jsx)(Wc,{panel:e,templateId:t,options:n,onSaved:()=>f(!1),onCancel:()=>f(!1)}):null]}),o?(0,U.jsx)(`div`,{className:`share-action-error`,role:`alert`,children:o}):null]})}function Qc(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function $c({panel:e,onPick:t,onManage:n}){let[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)({}),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!r)return;let t=new AbortController;return u(null),Promise.all([zc({signal:t.signal}),Hc({signal:t.signal})]).then(([t,n])=>{o(t.presets[e]??{}),c(n.history.filter(t=>t.panel===e).slice().reverse())}).catch(e=>{e?.name!==`AbortError`&&u((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Failed to load presets`)}),()=>t.abort()},[r,e]),(0,_.useEffect)(()=>{if(!r)return;function e(e){let t=d.current;t&&(t.contains(e.target)||i(!1))}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[r]);let f=Object.keys(a).sort();return(0,U.jsxs)(`div`,{className:`share-presets-dropdown`,ref:d,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-presets-trigger`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>i(e=>!e),children:`presets ▾`}),r?(0,U.jsxs)(`div`,{className:`share-presets-menu`,role:`menu`,children:[l?(0,U.jsx)(`div`,{className:`share-presets-error`,role:`alert`,children:l}):null,f.length===0&&!l?(0,U.jsx)(`div`,{className:`share-presets-empty`,children:`No saved presets yet.`}):null,f.length>0?(0,U.jsx)(`ul`,{className:`share-presets-list`,children:f.map(e=>(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-item`,onClick:()=>{t(a[e].template_id,a[e].options),i(!1)},children:e})},e))}):null,s.length>0?(0,U.jsxs)(`div`,{className:`share-presets-history`,children:[(0,U.jsx)(`div`,{className:`share-presets-history-heading`,role:`presentation`,children:`Recent shares`}),(0,U.jsx)(`ul`,{className:`share-presets-history-list`,children:s.map(e=>(0,U.jsx)(`li`,{children:(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-history-item`,onClick:()=>{t(e.template_id,e.options),i(!1)},title:`${e.template_id} · ${e.format??`unknown`} · ${e.exported_at}`,children:[(0,U.jsx)(`span`,{className:`share-presets-history-template`,children:e.template_id}),(0,U.jsxs)(`span`,{className:`share-presets-history-meta`,children:[` · `,e.format??`unknown`,` · `,Qc(e.exported_at)]})]})},e.recipe_id))})]}):null,(0,U.jsx)(`div`,{className:`share-presets-footer`,children:(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-manage`,onClick:()=>{n(),i(!1)},children:`Manage presets…`})})]}):null]})}var el=`share-manage-presets-title`;function tl({open:e,onClose:t}){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null);Ht((0,_.useMemo)(()=>e?[{key:`Escape`,scope:`modal`,action:t}]:[],[e,t]));let c=(0,_.useRef)(null),l=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(e)l.current||(l.current=!0,c.current=document.activeElement);else if(l.current){l.current=!1;let e=c.current;if(c.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=!1;return s(null),(async()=>{try{let e=await zc();if(t)return;let n=[];for(let[t,r]of Object.entries(e.presets))for(let[e,i]of Object.entries(r))n.push({panel:t,name:e,record:i});n.sort((e,t)=>e.panel===t.panel?e.name.localeCompare(t.name):e.panel.localeCompare(t.panel)),r(n)}catch(e){if(t)return;s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Failed to load presets`)}})(),()=>{t=!0}},[e]);async function u(e){a(!0),s(null);try{await Vc(e.panel,e.name),r(t=>t.filter(t=>!(t.panel===e.panel&&t.name===e.name))),H({type:`SHOW_STATUS_TOAST`,text:`Deleted preset "${e.name}"`})}catch(e){s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Delete failed`)}finally{a(!1)}}async function d(e,t){a(!0),s(null);try{await Bc({panel:e.panel,name:t,template_id:e.record.template_id,options:e.record.options}),await Vc(e.panel,e.name),r(n=>n.map(n=>n.panel===e.panel&&n.name===e.name?{...n,name:t}:n)),H({type:`SHOW_STATUS_TOAST`,text:`Renamed to "${t}"`})}catch(e){s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Rename failed`)}finally{a(!1)}}return e?(0,U.jsxs)(`div`,{className:`share-manage-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":el,onClick:e=>e.stopPropagation(),children:[(0,U.jsxs)(`div`,{className:`share-manage-header`,children:[(0,U.jsx)(`h2`,{id:el,children:`Manage presets`}),(0,U.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`share-manage-close`,children:`⤬`})]}),o?(0,U.jsx)(`div`,{className:`share-manage-error`,role:`alert`,children:o}):null,n.length===0&&!o?(0,U.jsx)(`p`,{className:`share-manage-empty`,children:`No saved presets yet.`}):null,n.length>0?(0,U.jsxs)(`table`,{className:`share-manage-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`Panel`}),(0,U.jsx)(`th`,{children:`Name`}),(0,U.jsx)(`th`,{children:`Saved at`}),(0,U.jsx)(`th`,{})]})}),(0,U.jsx)(`tbody`,{children:n.map(e=>(0,U.jsx)(nl,{row:e,busy:i,onDelete:()=>void u(e),onRename:t=>void d(e,t)},`${e.panel}/${e.name}`))})]}):null]}):null}function nl({row:e,busy:t,onDelete:n,onRename:r}){let[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(e.name),c=()=>{let t=o.trim();if(!t||t===e.name){s(e.name),a(!1);return}r(t),a(!1)};return(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:Ic(e.panel)}),(0,U.jsx)(`td`,{children:i?(0,U.jsx)(`input`,{className:`share-manage-name-input`,autoFocus:!0,value:o,disabled:t,maxLength:64,onChange:e=>s(e.target.value),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),c()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),s(e.name),a(!1))}}):(0,U.jsx)(`span`,{children:e.name})}),(0,U.jsx)(`td`,{children:e.record.saved_at}),(0,U.jsxs)(`td`,{className:`share-manage-actions`,children:[(0,U.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>{i?(s(e.name),a(!1)):a(!0)},children:i?`Cancel`:`Rename`}),(0,U.jsx)(`button`,{type:`button`,disabled:t,onClick:n,children:`Delete`})]})]})}function rl(){return{format:`md`,theme:`light`,reveal_projects:!1,no_branding:!1,top_n:5,period:{kind:`current`},project_allowlist:null,show_chart:!0,show_table:!0}}function il(e,t){if(!t)return e;let n={...e,...t};return t.period&&(n.period={...e.period,...t.period}),n}function al({panel:e,onClose:t,initialParams:n}){let r=Ic(e),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(()=>{let e=rl();return n?.windowWeeks==null?e:{...e,windowWeeks:n.windowWeeks}}),f=(0,_.useRef)(!1),[p,m]=(0,_.useState)(!1),h=`share-modal-title`;Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`overlay`,layer:200,when:()=>!p&&B().composerModal===null,action:t}],[t,p])),(0,_.useEffect)(()=>{let t=!1;return a(null),s(null),Ec(e).then(e=>{if(t)return;a(e.templates);let n=e.templates[0];n&&(l(n.id),f.current||d(e=>il(e,n.default_options)))}).catch(e=>{t||s(e instanceof wc?`Couldn't load templates: ${e.message??`HTTP ${e.status}`}`:`Couldn't load templates: ${e.message}`)}),()=>{t=!0}},[e]),(0,_.useEffect)(()=>{if(!i||!c||f.current)return;let e=i.find(e=>e.id===c);e&&d(t=>il(t,e.default_options))},[c,i]);let g=e=>{f.current=!0,d(e)};return(0,U.jsxs)(`div`,{className:`share-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":h,onClick:e=>e.stopPropagation(),children:[(0,U.jsx)(`header`,{className:`share-modal-header`,children:(0,U.jsxs)(`h2`,{id:h,children:[`Share `,r,` report`]})}),(0,U.jsxs)(`div`,{className:`share-modal-body`,children:[(0,U.jsxs)(`section`,{className:`share-section share-gallery-section`,"aria-label":`Template gallery`,children:[(0,U.jsx)(`div`,{className:`share-gallery-header`,children:(0,U.jsx)($c,{panel:e,onPick:(e,t)=>{l(e),f.current=!0,d(e=>({...e,...t}))},onManage:()=>m(!0)})}),(0,U.jsx)(Ac,{panel:e,templates:i,error:o,selectedTemplateId:c,onSelect:e=>l(e)})]}),(0,U.jsxs)(`section`,{className:`share-section share-main-section`,children:[(0,U.jsx)(`div`,{className:`share-knobs-col`,"aria-label":`Render options`,children:(0,U.jsx)(jc,{options:u,onChange:g})}),(0,U.jsx)(`div`,{className:`share-preview-col`,"aria-label":`Live preview`,children:(0,U.jsx)(Pc,{panel:e,templateId:c,options:u})})]})]}),(0,U.jsx)(`footer`,{className:`share-modal-footer`,children:(0,U.jsx)(Zc,{panel:e,templateId:c,options:u,onOptionsChange:g})}),(0,U.jsx)(`button`,{type:`button`,className:`share-modal-close`,"aria-label":`Close share modal`,onClick:t,children:`⤬`}),(0,U.jsx)(tl,{open:p,onClose:()=>m(!1)})]})}function ol(e,t){return{title:t.title,theme:t.theme,format:t.format,no_branding:t.no_branding,reveal_projects:t.reveal_projects,sections:e.map(e=>({snapshot:{panel:e.panel,template_id:e.template_id,options:e.options,data_digest_at_add:e.data_digest_at_add,kernel_version:e.kernel_version}}))}}async function sl(e,t){let n=await fetch(`/api/share/compose`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal});if(!n.ok){let e={};try{e=await n.json()}catch{}throw new wc(n.status,e.field,e.error??`HTTP ${n.status}`,e.code)}return n.json()}function cl({items:e,results:t,kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a}){let o=Xr(Yr(Zi,{activationConstraint:{distance:4}}),Yr(Ki,{coordinateGetter:wo}));function s(t){if(!t.over||t.active.id===t.over.id)return;let n=e.findIndex(e=>e.id===t.active.id),r=e.findIndex(e=>e.id===t.over.id);n<0||r<0||H({type:`BASKET_REORDER`,fromIdx:n,toIdx:r})}return(0,U.jsx)(Ja,{sensors:o,collisionDetection:ii,onDragEnd:s,children:(0,U.jsx)(fo,{items:e.map(e=>e.id),strategy:co,children:(0,U.jsx)(`ul`,{className:`composer-section-list`,children:e.map((e,o)=>(0,U.jsx)(ll,{item:e,result:t[o],kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a},e.id))})})})}function ll({item:e,result:t,kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a}){let{attributes:o,listeners:s,setNodeRef:c,transform:l,transition:u,isDragging:d}=bo({id:e.id}),f=jo(),p={transform:Pr.Transform.toString(l),transition:f?void 0:u,opacity:d?.4:1},[m,h]=(0,_.useState)(!1),g=t?.drift_detected,v=e.kernel_version!==n,y=!!(g||v);return(0,U.jsxs)(`li`,{ref:c,style:p,className:`composer-section-row`,children:[(0,U.jsx)(`button`,{className:`composer-drag-handle`,"aria-label":`Reorder ${e.label_hint}`,type:`button`,...o,...s,children:`≡`}),(0,U.jsx)(`span`,{className:`composer-section-label`,children:e.label_hint}),y?(0,U.jsx)(`span`,{className:`composer-outdated-badge`,title:g&&v?`Data and kernel both shifted since add-time. Refresh to update.`:g?`Data has changed since this section was added. Refresh to update.`:`Kernel updated since this section was added. Refresh to re-render at the new version.`,children:`Outdated`}):null,(0,U.jsxs)(`div`,{className:`composer-section-actions`,children:[(0,U.jsx)(`button`,{type:`button`,"aria-haspopup":`menu`,"aria-expanded":m,onClick:()=>h(e=>!e),"aria-label":`Actions for ${e.label_hint}`,children:`⋯`}),m?(0,U.jsxs)(`ul`,{role:`menu`,className:`composer-section-menu`,children:[(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{a(e.id),h(!1)},children:`Preview only this`})}),(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{r(e.id),h(!1)},children:`Refresh from current data`})}),(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{i(e.id),h(!1)},"aria-label":`Remove ${e.label_hint}`,children:`Remove`})})]}):null]})]})}function ul(e,t){return t&&e>0}function dl(e){return`cctally-report-${new Date().toISOString().slice(0,10).replaceAll(`-`,``)}.${e===`md`?`md`:e}`}function fl(e){switch(e){case`md`:return`text/markdown;charset=utf-8`;case`html`:return`text/html;charset=utf-8`;case`svg`:return`image/svg+xml;charset=utf-8`}}function pl(e){return e===`light`?`#ffffff`:`#0f172a`}function ml(e,t){let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.style.display=`none`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),0)}var hl=200;function gl(){return B().composerModal}function _l(){return B().basket}var vl=`composer-modal-title`;function yl(){let e=(0,_.useSyncExternalStore)(V,gl),t=(0,_.useSyncExternalStore)(V,_l),n=cn(),r=(0,_.useRef)(null),i=(0,_.useRef)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(`light`),[l,u]=(0,_.useState)(`html`),[d,f]=(0,_.useState)(!0),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(!1),S=(0,_.useRef)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(null);(0,_.useEffect)(()=>{E(null)},[l,s,d,p]),Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`overlay`,layer:210,when:()=>B().composerModal!==null,action:()=>H(me())}],[])),(0,_.useEffect)(()=>{e?.open&&a===``&&o(`cctally report — ${new Date().toISOString().slice(0,10)}`)},[e?.open,a]),(0,_.useEffect)(()=>{if(e?.open)i.current||(i.current=!0,r.current=document.activeElement);else if(i.current){i.current=!1;let e=r.current;if(r.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e?.open]),(0,_.useEffect)(()=>{if(!e?.open||t.items.length===0||a===``)return;let n=setTimeout(()=>{S.current?.abort();let e=new AbortController;S.current=e,x(!0),y(null),sl(ol(t.items,{title:a,theme:s,format:l,no_branding:p,reveal_projects:!d}),{signal:e.signal}).then(t=>{e.signal.aborted||g(t)}).catch(t=>{t?.name!==`AbortError`&&(e.signal.aborted||y(t instanceof wc?t.message??`HTTP ${t.status}`:t.message))}).finally(()=>{e.signal.aborted||x(!1)})},hl);return()=>clearTimeout(n)},[e?.open,t.items,a,s,l,d,p]);async function D(e){let n=t.items.findIndex(t=>t.id===e);if(n<0)return;let r=t.items[n];try{let t=await Dc({panel:r.panel,template_id:r.template_id,options:{...r.options,reveal_projects:!d}}),i=_e({panel:r.panel,template_id:r.template_id,options:r.options,added_at:new Date().toISOString(),data_digest_at_add:t.snapshot.data_digest,kernel_version:t.snapshot.kernel_version,label_hint:r.label_hint,id:r.id});H({type:`BASKET_REMOVE`,id:e}),H({type:`BASKET_ADD`,item:i});let a=B().basket.items.length-1;a!==n&&H({type:`BASKET_REORDER`,fromIdx:a,toIdx:n})}catch(e){y(`Refresh failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}}let O=async e=>{let n=await sl(ol(t.items,{title:a,theme:s,format:e,no_branding:p,reveal_projects:!d}));return{body:n.body,content_type:n.content_type}},k=e=>H({type:`SHOW_STATUS_TOAST`,text:e}),A=async(e,t,n)=>{if(C==null){w(e),E(null);try{await t()}catch(e){E(`${n} failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{w(null)}}},j=()=>A(`copy`,async()=>{let{body:e}=await O(`md`);if(!navigator.clipboard||typeof navigator.clipboard.writeText!=`function`)throw Error(`Clipboard API unavailable in this browser`);await navigator.clipboard.writeText(e),k(`Copied`)},`Copy`),M=()=>A(`download`,async()=>{let{body:e}=await O(l),t=new Blob([e],{type:fl(l)});ml(dl(l),t),k(`Downloaded`)},`Download`),N=()=>A(`open`,async()=>{let{body:e}=await O(l),t=new Blob([e],{type:fl(l)}),n=URL.createObjectURL(t);window.open(n,`_blank`,`noopener,noreferrer`)},`Open`),P=()=>A(`png`,async()=>{let{body:e}=await O(`svg`),t=await Gc(e,2,pl(s));ml(dl(`svg`).replace(/\.svg$/,`.png`),t),k(`PNG downloaded`)},`PNG export`),F=()=>A(`print`,async()=>{let{body:e}=await O(`html`);J(e)},`Print`),ee=C==null&&l===`md`&&t.items.length>0,te=C==null&&t.items.length>0,ne=C==null&&(l===`html`||l===`svg`)&&t.items.length>0,I=C==null&&l===`svg`&&t.items.length>0,re=C==null&&l===`html`&&t.items.length>0,ie=!d,ae=ul(t.items.length,ie),oe=ie?t.items.length:0;return e?.open?t.items.length===0?(0,U.jsxs)(`div`,{className:`composer-modal composer-modal-empty${n?` composer-modal-mobile`:``}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":vl,children:[(0,U.jsxs)(`header`,{className:`composer-modal-header`,children:[(0,U.jsx)(`h2`,{id:vl,children:`Compose report`}),(0,U.jsx)(`button`,{type:`button`,className:`composer-modal-close`,onClick:()=>H(me()),"aria-label":`Close`,children:`⤬`})]}),(0,U.jsx)(`p`,{className:`composer-empty-message`,children:`Basket is empty. Open any panel's share menu and pick + Basket to add a section.`})]}):(0,U.jsxs)(`div`,{className:`composer-modal${n?` composer-modal-mobile`:``}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":vl,children:[(0,U.jsxs)(`header`,{className:`composer-modal-header`,children:[(0,U.jsx)(`h2`,{id:vl,children:`Compose report`}),(0,U.jsx)(`button`,{type:`button`,className:`composer-modal-close`,onClick:()=>H(me()),"aria-label":`Close`,children:`⤬`})]}),(0,U.jsxs)(`div`,{className:`composer-knobs`,children:[(0,U.jsxs)(`label`,{children:[`Title`,(0,U.jsx)(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value)})]}),(0,U.jsxs)(`label`,{children:[`Theme`,(0,U.jsxs)(`select`,{value:s,onChange:e=>c(e.target.value),children:[(0,U.jsx)(`option`,{value:`light`,children:`light`}),(0,U.jsx)(`option`,{value:`dark`,children:`dark`})]})]}),(0,U.jsxs)(`label`,{children:[`Format`,(0,U.jsxs)(`select`,{value:l,onChange:e=>u(e.target.value),children:[(0,U.jsx)(`option`,{value:`html`,children:`html`}),(0,U.jsx)(`option`,{value:`md`,children:`md`}),(0,U.jsx)(`option`,{value:`svg`,children:`svg`})]})]}),(0,U.jsxs)(`label`,{children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Anon on export`]}),(0,U.jsxs)(`label`,{children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),`No branding`]})]}),ae?(0,U.jsxs)(`div`,{className:`composer-anon-banner`,role:`status`,"aria-live":`polite`,children:[(0,U.jsxs)(`span`,{children:[oe,` section`,oe===1?``:`s`,` contain real project names. They will appear in the export.`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>f(!0),children:`Anonymize all`})]}):null,(0,U.jsxs)(`div`,{className:`composer-body`,children:[(0,U.jsx)(cl,{items:t.items,results:h?.snapshot.section_results??[],kernelVersion:h?.snapshot.kernel_version??1,onRefresh:e=>{D(e)},onRemove:e=>H({type:`BASKET_REMOVE`,id:e}),onPreviewOnly:e=>{}}),(0,U.jsx)(`iframe`,{className:`composer-preview`,title:`Combined preview`,tabIndex:-1,sandbox:`allow-same-origin`,srcDoc:h?.body??`<p>Composing&hellip;</p>`})]}),b?(0,U.jsx)(`div`,{className:`composer-busy`,children:`Composing…`}):null,v?(0,U.jsx)(`div`,{className:`composer-error`,role:`alert`,children:v}):null,T?(0,U.jsx)(`div`,{className:`composer-error`,role:`alert`,children:T}):null,(0,U.jsxs)(`footer`,{className:`composer-actions`,children:[(0,U.jsxs)(`div`,{className:`composer-export-row`,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-copy`,onClick:j,disabled:!ee,title:l===`md`?C===`copy`?`Copying…`:`Copy composed report to clipboard`:`Copy is available for Markdown only`,children:C===`copy`?`Copying…`:`Copy`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-download`,onClick:M,disabled:!te,title:C===`download`?`Downloading…`:`Download composed report`,children:C===`download`?`Downloading…`:`Download`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-open`,onClick:N,disabled:!ne,title:l===`html`||l===`svg`?C===`open`?`Opening…`:`Open composed report in new tab`:`Open is available for HTML/SVG`,children:C===`open`?`Opening…`:`Open`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-png`,onClick:P,disabled:!I,title:l===`svg`?C===`png`?`Rasterizing…`:`Download composed report as PNG`:`PNG export — available for SVG format only`,children:C===`png`?`Rasterizing…`:`PNG`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-print`,onClick:F,disabled:!re,title:l===`html`?C===`print`?`Opening print dialog…`:`Open the browser print dialog (save as PDF)`:`Print → PDF — available for HTML format only`,children:C===`print`?`Printing…`:`Print → PDF`})]}),(0,U.jsx)(`button`,{type:`button`,className:`composer-clear-all`,onClick:()=>H({type:`BASKET_CLEAR`}),children:`Clear all`})]})]}):null}function bl(){let e=(0,_.useSyncExternalStore)(V,()=>B().shareModal),t=(0,_.useRef)(null),n=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(e)n.current||(n.current=!0,t.current=(e.triggerId?document.getElementById(e.triggerId):null)??document.activeElement);else if(n.current){n.current=!1;let e=t.current;if(t.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e]);let r=()=>H(fe());return(0,U.jsxs)(U.Fragment,{children:[e?(0,U.jsx)(`div`,{id:`share-modal-root`,className:`share-overlay`,onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&r()},children:(0,U.jsx)(al,{panel:e.panel,initialParams:e.params,onClose:r})}):null,(0,U.jsx)(yl,{})]})}var xl=class extends Error{constructor(e){super(`HTTP ${e}`),this.status=e,this.name=`HttpError`}};function Sl(e){return e?.name===`AbortError`}async function Cl(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw new xl(n.status);return await n.json()}function wl(e){let[t,n]=(0,_.useState)(null),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=(0,_.useRef)(e),c=(0,_.useRef)(null),l=(0,_.useRef)(!1),u=(0,_.useRef)(!1),d=(0,_.useCallback)(async()=>{if(l.current){u.current=!0;return}let e=s.current;if(e){l.current=!0;try{let t=await Cl(`/api/conversation/${encodeURIComponent(e)}/outline`);if(s.current!==e)return;c.current=t,n(t),o(null),i(!1)}catch{if(s.current!==e)return;o(`Couldn't load the outline.`),i(!1)}finally{l.current=!1,u.current&&(u.current=!1,d())}}},[]);return(0,_.useEffect)(()=>{if(s.current=e,c.current=null,l.current=!1,u.current=!1,n(null),o(null),!e){i(!1);return}i(!0),d()},[e,d]),(0,_.useEffect)(()=>{c.current&&d()},[W()?.generated_at??``]),{outline:t,loading:r,error:a}}var Tl=50;function El(){let[e,t]=(0,_.useState)([]),[n,r]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(0),c=W()?.generated_at??``,l=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(l.current||e.length>Tl)return;let n=new AbortController;return Cl(`/api/conversations?sort=recent&limit=${Tl}&offset=0`,n.signal).then(e=>{t(e.conversations),s(e.page.next_offset),a(null),r(!1)}).catch(e=>{Sl(e)||(a(`Couldn't load conversations.`),r(!1))}),()=>n.abort()},[c]);let u=(0,_.useCallback)(async()=>{if(!(o==null||l.current)){l.current=!0;try{let e=await Cl(`/api/conversations?sort=recent&limit=${Tl}&offset=${o}`);t(t=>[...t,...e.conversations]),s(e.page.next_offset)}catch{}finally{l.current=!1}}},[o]);return{rows:e,loading:n,error:i,hasMore:o!=null,loadMore:u}}function Dl(e,t,n=e){let[r,i]=(0,_.useState)(n);return(0,_.useEffect)(()=>{let n=setTimeout(()=>i(e),t);return()=>clearTimeout(n)},[e,t]),r}var Ol=200;function kl(e,t=`all`){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(0),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),g=e.trim(),v=Dl(g,Ol,``),y=(0,_.useRef)(null),b=(0,_.useRef)(0);b.current=n.length;let x=(0,_.useRef)(0);x.current=o;let S=(0,_.useRef)(!1);S.current=f;let C=(0,_.useCallback)(e=>`/api/conversation/search?q=${encodeURIComponent(v)}&limit=50&offset=${e}&kind=${t}`,[v,t]);(0,_.useEffect)(()=>(g||(r([]),a(null),s(0),l(null),h(null)),()=>{y.current?.abort()}),[g,t]),(0,_.useEffect)(()=>{if(!v){d(!1),p(!1);return}let e=new AbortController;return y.current=e,d(!0),p(!1),Cl(C(0),e.signal).then(e=>{r(e.hits),a(e.mode),s(e.total),l(e.search_depth??`full`),h(null),d(!1)}).catch(e=>{Sl(e)||(h(`Search failed.`),d(!1))}),()=>e.abort()},[v,t,C]);let w=(0,_.useCallback)(()=>{if(S.current||b.current>=x.current)return;let e=b.current,t=new AbortController;y.current=t,p(!0),Cl(C(e),t.signal).then(e=>{r(t=>[...t,...e.hits]),s(e.total),a(e.mode),l(e.search_depth??`full`),p(!1)}).catch(e=>{Sl(e)||(h(`Search failed.`),p(!1))})},[C]);return{hits:n,mode:i,total:o,loading:g!==``&&(g!==v||u),loadingMore:f,searchDepth:c,error:m,loadMore:w}}function Al(e){let t=[],n=0,r=0;for(;n<e.length;){let i=e.indexOf(`[`,n);if(i===-1){t.push((0,U.jsx)(_.Fragment,{children:e.slice(n)},r++));break}let a=e.indexOf(`]`,i+1);if(a===-1){t.push((0,U.jsx)(_.Fragment,{children:e.slice(n)},r++));break}i>n&&t.push((0,U.jsx)(_.Fragment,{children:e.slice(n,i)},r++)),t.push((0,U.jsx)(`mark`,{children:e.slice(i+1,a)},r++)),n=a+1}return(0,U.jsx)(U.Fragment,{children:t})}var jl=864e5;function Ml(e,t){let[n,r,i]=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).format(new Date(e)).split(`-`).map(Number);return{y:n,m:r,d:i}}function Nl(e,t,n){let r=Date.parse(e),i=Ml(r,t),a=Ml(n,t),o=Date.UTC(i.y,i.m-1,i.d),s=Date.UTC(a.y,a.m-1,a.d),c=Math.round((s-o)/jl);return c<=0?`Today`:c===1?`Yesterday`:c<7?`This Week`:i.y===a.y&&i.m===a.m?`This Month`:new Intl.DateTimeFormat(`en-US`,{timeZone:t,month:`long`,year:`numeric`}).format(new Date(r))}var Pl=[{kind:`all`,label:`All`,needsSplit:!1},{kind:`prompts`,label:`Prompts`,needsSplit:!1},{kind:`assistant`,label:`Assistant`,needsSplit:!1},{kind:`tools`,label:`Tools`,needsSplit:!0},{kind:`thinking`,label:`Thinking`,needsSplit:!0}];function Fl(){let e=(0,_.useSyncExternalStore)(V,()=>B().conversationSearch),t=(0,_.useSyncExternalStore)(V,()=>B().conversationSearchKind),n=(0,_.useSyncExternalStore)(V,()=>B().selectedConversationId),r=Wt(),i={tz:r.resolvedTz,offsetLabel:r.offsetLabel},a=(0,_.useRef)(null),o=e.trim()!==``;return(0,U.jsxs)(`aside`,{className:`conv-rail`,children:[(0,U.jsx)(`div`,{className:`conv-rail-search`,children:(0,U.jsx)(`input`,{ref:a,type:`search`,className:`conv-rail-search-input`,placeholder:`search all conversations…`,value:e,onChange:e=>H({type:`SET_CONVERSATION_SEARCH`,text:e.target.value}),onFocus:()=>H({type:`SET_INPUT_MODE`,mode:`search`}),onBlur:()=>H({type:`SET_INPUT_MODE`,mode:null}),onKeyDown:e=>{e.key===`Escape`&&(H({type:`SET_CONVERSATION_SEARCH`,text:``}),a.current?.blur())}})}),o?(0,U.jsx)(zl,{needle:e,kind:t,ctx:i}):(0,U.jsx)(Il,{selectedId:n,ctx:i})]})}function Il({selectedId:e,ctx:t}){let{rows:n,loading:r,error:i,hasMore:a,loadMore:o}=El();if(i)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:i})});if(r&&n.length===0)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`Loading…`})});if(n.length===0)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`No conversations.`})});let s=null,c=Date.now();return(0,U.jsxs)(`div`,{className:`conv-rail-list`,children:[n.map(n=>{let r=Nl(n.started_utc,t.tz,c),i=r!==s;return i&&(s=r),(0,U.jsxs)(_.Fragment,{children:[i&&(0,U.jsx)(`div`,{className:`conv-rail-sec`,children:r}),(0,U.jsx)(Ll,{row:n,ctx:t,active:n.session_id===e})]},n.session_id)}),a&&(0,U.jsx)(`button`,{type:`button`,className:`conv-rail-more`,onClick:()=>void o(),children:`Load more`})]})}function Ll({row:e,ctx:t,active:n}){return(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-row${n?` is-active`:``}`,onClick:()=>H({type:`SELECT_CONVERSATION`,sessionId:e.session_id}),children:[(0,U.jsx)(`div`,{className:`conv-rail-row-title`,children:e.title}),(0,U.jsxs)(`div`,{className:`conv-rail-row-meta`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-project`,children:e.project_label||`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-branch`,children:e.git_branch??`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-when`,children:A.startedShort(e.started_utc,t,{noSuffix:!0})}),(0,U.jsx)(`span`,{className:`conv-rail-row-cost`,children:A.usd2(e.cost_usd)}),(0,U.jsxs)(`span`,{className:`conv-rail-row-msgs`,children:[e.msg_count,` msgs`]})]})]})}function Rl({kind:e,proseOnly:t}){return(0,U.jsx)(`div`,{className:`conv-rail-chips`,role:`radiogroup`,"aria-label":`Search kind`,children:Pl.map(n=>{let r=n.needsSplit&&t,i=e===n.kind;return(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":i,disabled:r,title:r?`indexing…`:void 0,className:`conv-rail-chip${i?` is-on`:``}`,onClick:()=>H({type:`SET_CONVERSATION_SEARCH_KIND`,kind:n.kind}),children:n.label},n.kind)})})}function zl({needle:e,kind:t,ctx:n}){let{hits:r,mode:i,total:a,loading:o,loadingMore:s,searchDepth:c,error:l,loadMore:u}=kl(e,t),d=c===`prose-only`,f=a-r.length,p=d&&(t===`tools`||t===`thinking`),m=(a===0?`No results`:`${a} results${i===`like`?` · basic search`:``}`)+(p?` · indexing…`:``);return(0,U.jsxs)(`div`,{className:`conv-rail-list`,children:[(0,U.jsx)(Rl,{kind:t,proseOnly:d}),l?(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:l}):o&&r.length===0?(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`Searching…`}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`conv-rail-count`,"aria-live":`polite`,children:m}),r.map((e,t)=>(0,U.jsx)(Bl,{hit:e,ctx:n},`${e.session_id}-${e.uuid}-${t}`)),r.length<a&&(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-more`,disabled:s,onClick:()=>u(),children:[`Load `,Math.min(50,f),` more (`,f,` remaining)`]})]})]})}function Bl({hit:e,ctx:t}){let n=e.match_kinds??[];return(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-row conv-rail-row--hit`,onClick:()=>H({type:`OPEN_CONVERSATION`,sessionId:e.session_id,jump:{session_id:e.session_id,uuid:e.uuid}}),children:[(0,U.jsxs)(`div`,{className:`conv-rail-row-title conv-rail-row-title--hit`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-title-text`,children:e.title}),n.length>0&&(0,U.jsx)(`span`,{className:`conv-rail-kindbs`,children:n.map(e=>(0,U.jsx)(`span`,{className:`conv-rail-kindb`,children:e},e))})]}),(0,U.jsxs)(`div`,{className:`conv-rail-row-meta`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-project`,children:e.project_label||`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-when`,children:A.startedShort(e.ts,t,{noSuffix:!0})}),(0,U.jsx)(`span`,{className:`conv-rail-row-cost`,children:A.usd2(e.cost_usd)})]}),(0,U.jsx)(`div`,{className:`conv-rail-row-snippet`,children:Al(e.snippet)})]})}var Vl=500;function Hl(e){let[t,n]=(0,_.useState)(null),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(!1),h=(0,_.useRef)(null),g=(0,_.useCallback)(e=>{n(t=>{let n=typeof e==`function`?e(t):e;return h.current=n,n})},[]);(0,_.useEffect)(()=>{if(d.current=e,!e){g(null),c(null),i(!1),o(null),l.current=null;return}i(!0),o(null),g(null),l.current=null;let t=new AbortController;return Cl(`/api/conversation/${encodeURIComponent(e)}?limit=${Vl}`,t.signal).then(t=>{g(t),c(e),l.current=t.page.next_after,i(!1)}).catch(e=>{if(!Sl(e)){if(e instanceof xl&&e.status===404){o(`Conversation not found.`),i(!1);return}o(`Couldn't load the conversation.`),i(!1)}}),()=>t.abort()},[e,g]);let v=(0,_.useCallback)(async()=>{let e=l.current,t=d.current;if(e==null||t==null||u.current)return!1;u.current=!0;try{let n;try{n=await Cl(`/api/conversation/${encodeURIComponent(t)}?limit=${Vl}&after=${e}`)}catch{return!1}return d.current===t?(g(e=>e?{...e,items:[...e.items,...n.items],page:n.page,subagent_meta:n.subagent_meta??e.subagent_meta}:n),l.current=n.page.next_after,n.page.next_after!=null):!1}finally{u.current=!1}},[g]),y=(0,_.useCallback)(async()=>{await v()},[v]),b=(0,_.useCallback)(async e=>{let t=()=>{let t=h.current;return!!t&&t.items.some(t=>t.member_uuids.includes(e))};for(let e=0;e<20;e++)if(t()||!await v())return},[v]),x=t!=null&&s===e,S=x?t:null,C=e!=null&&!x&&a==null?!0:r,w=S?.page?.next_after!=null;f.current=w;let T=(0,_.useCallback)(async()=>{if(p.current){m.current=!0;return}let e=d.current;if(!(!e||f.current||u.current)){p.current=!0;try{for(let t=0;t<50;t++){let t=h.current?.items.at(-1);if(!t)break;let n;try{n=await Cl(`/api/conversation/${encodeURIComponent(e)}?limit=${Vl}&after=${t.anchor.id}`)}catch{break}if(d.current!==e)return;if(g(e=>e&&{...e,items:n.items.length?[...e.items,...n.items]:e.items,cost_usd:n.cost_usd,models:n.models,title:n.title??e.title,git_branch:n.git_branch,project_label:n.project_label,subagent_meta:n.subagent_meta??e.subagent_meta,page:e.page}),!n.items.length||n.page.next_after==null)break}}finally{p.current=!1,m.current&&(m.current=!1,T())}}},[g]);return(0,_.useEffect)(()=>{h.current&&!f.current&&T()},[W()?.generated_at??``]),{detail:S,loading:C,error:a,hasMore:w,loadMore:y,loadUntil:b}}function Ul(e){let t=[],n=[],r=()=>{n.length>=2?t.push({kind:`tool_result_run`,items:n}):n.length===1&&t.push({kind:`item`,item:n[0]}),n=[]};for(let i of e){if(i.kind===`item`&&i.item.kind===`tool_result`){n.push(i.item);continue}r(),t.push(i)}return r(),t}function Wl(e){let t=new Map,n=new Map;for(let r of e){let e=r.subagent_key;if(e!=null){let n=t.get(e);n?n.push(r):t.set(e,[r])}else for(let e of r.member_uuids)n.set(e,r)}let r=new Set,i=new Map;for(let[e,a]of t){let t=(a.find(e=>e.kind!==`meta`)??a[0]).parent_uuid,o=t==null?void 0:n.get(t);if(o){r.add(e);let t=o.anchor.uuid,n=i.get(t);n?n.push(e):i.set(t,[e])}}let a=[],o=new Set,s=e=>{a.push({kind:`subagent`,subagentKey:e,items:t.get(e),nested:r.has(e)}),o.add(e)};for(let t of e)if(t.subagent_key==null){a.push({kind:`item`,item:t});let e=i.get(t.anchor.uuid);if(e)for(let t of e)o.has(t)||s(t)}else{let e=t.subagent_key;if(o.has(e)||r.has(e))continue;s(e)}for(let e of t.keys())o.has(e)||s(e);return Ul(a)}var Gl=RegExp(`^\\s*(?:<(${[`command-name`,`command-message`,`command-args`,`local-command-caveat`,`local-command-stdout`,`local-command-stderr`].join(`|`)})>(?:(?!</\\1>)[\\s\\S])*</\\1>\\s*)+$`);function Kl(e){return e?Gl.test(e):!1}var ql=200;function Jl(e,t){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(0),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=t.trim(),h=Dl(m,ql,``),g=(0,_.useRef)(null);return(0,_.useEffect)(()=>(m||(r([]),a(0),s(!1),l(null),p(null)),()=>{g.current?.abort()}),[m]),(0,_.useEffect)(()=>{if(!h){d(!1);return}let t=new AbortController;return g.current=t,d(!0),Cl(`/api/conversation/${encodeURIComponent(e)}/find?q=${encodeURIComponent(h)}`,t.signal).then(e=>{r(e.anchors),a(e.total),s(e.anchors_truncated),l(e.mode),p(null),d(!1)}).catch(e=>{Sl(e)||(r([]),a(0),s(!1),l(null),p(`Find failed.`),d(!1))}),()=>t.abort()},[e,h]),{anchors:n,total:i,truncated:o,mode:c,loading:m!==``&&(m!==h||u),error:f}}function Yl({sessionId:e,onClose:t,onTermsChange:n,stepRef:r}){let[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(0),{anchors:c,total:l,truncated:u,mode:d,loading:f,error:p}=Jl(e,i),m=(0,_.useRef)(null);(0,_.useEffect)(()=>{m.current?.focus()},[]);let h=Dl(i.trim(),200,``);(0,_.useEffect)(()=>{n(h)},[h,n]),(0,_.useEffect)(()=>{s(0)},[c]);let g=t=>{if(c.length===0)return;let n=((o+t)%c.length+c.length)%c.length;s(n);let r=c[n];H({type:`OPEN_CONVERSATION`,sessionId:e,jump:{session_id:e,uuid:r.uuid,expand_details:r.match_kinds.length>0}})};r&&(r.current=g),(0,_.useEffect)(()=>()=>{r&&(r.current=null)},[r]);let v=()=>{H({type:`CLOSE_CONV_FIND`}),t()},y=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),g(e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),v())},b=c.length>0,x=b?c[o]:null,S=`${b?o+1:0} / ${l}`;return(0,U.jsxs)(`div`,{className:`conv-findbar`,role:`search`,"aria-label":`Find within this conversation`,children:[(0,U.jsx)(`input`,{ref:m,className:`conv-findbar-input`,type:`text`,"aria-label":`Find in conversation`,placeholder:`Find…`,value:i,onChange:e=>a(e.target.value),onKeyDown:y}),(0,U.jsxs)(`span`,{className:`conv-findbar-count`,"aria-live":`polite`,children:[S,u&&(0,U.jsx)(`span`,{className:`conv-findbar-note`,children:` · first 500`})]}),x&&x.match_kinds.length>0&&(0,U.jsx)(`span`,{className:`conv-findbar-kind`,children:x.match_kinds.join(` `)}),d===`like`&&(0,U.jsx)(`span`,{className:`conv-findbar-hint`,children:`basic search`}),p&&(0,U.jsx)(`span`,{className:`conv-findbar-hint`,children:`find failed`}),f&&(0,U.jsx)(`span`,{className:`conv-findbar-spin`,"aria-hidden":`true`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-nav`,"aria-label":`Previous match`,title:`Previous match (Shift+Enter)`,disabled:!b,onClick:()=>g(-1),children:`‹`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-nav`,"aria-label":`Next match`,title:`Next match (Enter)`,disabled:!b,onClick:()=>g(1),children:`›`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-close`,"aria-label":`Close find`,title:`Close (Esc)`,onClick:v,children:`✕`})]})}var Xl=(0,_.createContext)(null);function Zl(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function Ql(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var $l=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eu=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tu={};function nu(e,t){return((t||tu).jsx?eu:$l).test(e)}var ru=/[ \t\n\f\r]/g;function iu(e){return typeof e==`object`?e.type===`text`?au(e.value):!1:au(e)}function au(e){return e.replace(ru,``)===``}var ou=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};ou.prototype.normal={},ou.prototype.property={},ou.prototype.space=void 0;function su(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new ou(n,r,t)}function cu(e){return e.toLowerCase()}var lu=class{constructor(e,t){this.attribute=t,this.property=e}};lu.prototype.attribute=``,lu.prototype.booleanish=!1,lu.prototype.boolean=!1,lu.prototype.commaOrSpaceSeparated=!1,lu.prototype.commaSeparated=!1,lu.prototype.defined=!1,lu.prototype.mustUseProperty=!1,lu.prototype.number=!1,lu.prototype.overloadedBoolean=!1,lu.prototype.property=``,lu.prototype.spaceSeparated=!1,lu.prototype.space=void 0;var uu=s({boolean:()=>Y,booleanish:()=>fu,commaOrSpaceSeparated:()=>gu,commaSeparated:()=>hu,number:()=>X,overloadedBoolean:()=>pu,spaceSeparated:()=>mu}),du=0,Y=_u(),fu=_u(),pu=_u(),X=_u(),mu=_u(),hu=_u(),gu=_u();function _u(){return 2**++du}var vu=Object.keys(uu),yu=class extends lu{constructor(e,t,n,r){let i=-1;if(super(e,t),bu(this,`space`,r),typeof n==`number`)for(;++i<vu.length;){let e=vu[i];bu(this,vu[i],(n&uu[e])===uu[e])}}};yu.prototype.defined=!0;function bu(e,t,n){n&&(e[t]=n)}function xu(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new yu(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[cu(r)]=r,n[cu(a.attribute)]=r}return new ou(t,n,e.space)}var Su=xu({properties:{ariaActiveDescendant:null,ariaAtomic:fu,ariaAutoComplete:null,ariaBusy:fu,ariaChecked:fu,ariaColCount:X,ariaColIndex:X,ariaColSpan:X,ariaControls:mu,ariaCurrent:null,ariaDescribedBy:mu,ariaDetails:null,ariaDisabled:fu,ariaDropEffect:mu,ariaErrorMessage:null,ariaExpanded:fu,ariaFlowTo:mu,ariaGrabbed:fu,ariaHasPopup:null,ariaHidden:fu,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:mu,ariaLevel:X,ariaLive:null,ariaModal:fu,ariaMultiLine:fu,ariaMultiSelectable:fu,ariaOrientation:null,ariaOwns:mu,ariaPlaceholder:null,ariaPosInSet:X,ariaPressed:fu,ariaReadOnly:fu,ariaRelevant:null,ariaRequired:fu,ariaRoleDescription:mu,ariaRowCount:X,ariaRowIndex:X,ariaRowSpan:X,ariaSelected:fu,ariaSetSize:X,ariaSort:null,ariaValueMax:X,ariaValueMin:X,ariaValueNow:X,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function Cu(e,t){return t in e?e[t]:t}function wu(e,t){return Cu(e,t.toLowerCase())}var Tu=xu({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:hu,acceptCharset:mu,accessKey:mu,action:null,allow:null,allowFullScreen:Y,allowPaymentRequest:Y,allowUserMedia:Y,alpha:Y,alt:null,as:null,async:Y,autoCapitalize:null,autoComplete:mu,autoFocus:Y,autoPlay:Y,blocking:mu,capture:null,charSet:null,checked:Y,cite:null,className:mu,closedBy:null,colorSpace:null,cols:X,colSpan:X,command:null,commandFor:null,content:null,contentEditable:fu,controls:Y,controlsList:mu,coords:X|hu,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Y,defer:Y,dir:null,dirName:null,disabled:Y,download:pu,draggable:fu,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Y,formTarget:null,headers:mu,height:X,hidden:pu,high:X,href:null,hrefLang:null,htmlFor:mu,httpEquiv:mu,id:null,imageSizes:null,imageSrcSet:null,inert:Y,inputMode:null,integrity:null,is:null,isMap:Y,itemId:null,itemProp:mu,itemRef:mu,itemScope:Y,itemType:mu,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Y,low:X,manifest:null,max:null,maxLength:X,media:null,method:null,min:null,minLength:X,multiple:Y,muted:Y,name:null,nonce:null,noModule:Y,noValidate:Y,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Y,optimum:X,pattern:null,ping:mu,placeholder:null,playsInline:Y,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Y,referrerPolicy:null,rel:mu,required:Y,reversed:Y,rows:X,rowSpan:X,sandbox:mu,scope:null,scoped:Y,seamless:Y,selected:Y,shadowRootClonable:Y,shadowRootCustomElementRegistry:Y,shadowRootDelegatesFocus:Y,shadowRootMode:null,shadowRootSerializable:Y,shape:null,size:X,sizes:null,slot:null,span:X,spellCheck:fu,src:null,srcDoc:null,srcLang:null,srcSet:null,start:X,step:null,style:null,tabIndex:X,target:null,title:null,translate:null,type:null,typeMustMatch:Y,useMap:null,value:fu,width:X,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:mu,axis:null,background:null,bgColor:null,border:X,borderColor:null,bottomMargin:X,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Y,declare:Y,event:null,face:null,frame:null,frameBorder:null,hSpace:X,leftMargin:X,link:null,longDesc:null,lowSrc:null,marginHeight:X,marginWidth:X,noResize:Y,noHref:Y,noShade:Y,noWrap:Y,object:null,profile:null,prompt:null,rev:null,rightMargin:X,rules:null,scheme:null,scrolling:fu,standby:null,summary:null,text:null,topMargin:X,valueType:null,version:null,vAlign:null,vLink:null,vSpace:X,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:Y,disablePictureInPicture:Y,disableRemotePlayback:Y,exportParts:hu,part:mu,prefix:null,property:null,results:X,security:null,unselectable:null},space:`html`,transform:wu}),Eu=xu({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:gu,accentHeight:X,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:X,amplitude:X,arabicForm:null,ascent:X,attributeName:null,attributeType:null,azimuth:X,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:X,by:null,calcMode:null,capHeight:X,className:mu,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:X,diffuseConstant:X,direction:null,display:null,dur:null,divisor:X,dominantBaseline:null,download:Y,dx:null,dy:null,edgeMode:null,editable:null,elevation:X,enableBackground:null,end:null,event:null,exponent:X,externalResourcesRequired:null,fill:null,fillOpacity:X,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:hu,g2:hu,glyphName:hu,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:X,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:X,horizOriginX:X,horizOriginY:X,id:null,ideographic:X,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:X,k:X,k1:X,k2:X,k3:X,k4:X,kernelMatrix:gu,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:X,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:X,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:X,overlineThickness:X,paintOrder:null,panose1:null,path:null,pathLength:X,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:mu,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:X,pointsAtY:X,pointsAtZ:X,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:gu,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:gu,rev:gu,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:gu,requiredFeatures:gu,requiredFonts:gu,requiredFormats:gu,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:X,specularExponent:X,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:X,strikethroughThickness:X,string:null,stroke:null,strokeDashArray:gu,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:X,strokeOpacity:X,strokeWidth:null,style:null,surfaceScale:X,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:gu,tabIndex:X,tableValues:null,target:null,targetX:X,targetY:X,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:gu,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:X,underlineThickness:X,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:X,values:null,vAlphabetic:X,vMathematical:X,vectorEffect:null,vHanging:X,vIdeographic:X,version:null,vertAdvY:X,vertOriginX:X,vertOriginY:X,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:X,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:Cu}),Du=xu({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),Ou=xu({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:wu}),ku=xu({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),Au={classId:`classID`,dataType:`datatype`,itemId:`itemID`,strokeDashArray:`strokeDasharray`,strokeDashOffset:`strokeDashoffset`,strokeLineCap:`strokeLinecap`,strokeLineJoin:`strokeLinejoin`,strokeMiterLimit:`strokeMiterlimit`,typeOf:`typeof`,xLinkActuate:`xlinkActuate`,xLinkArcRole:`xlinkArcrole`,xLinkHref:`xlinkHref`,xLinkRole:`xlinkRole`,xLinkShow:`xlinkShow`,xLinkTitle:`xlinkTitle`,xLinkType:`xlinkType`,xmlnsXLink:`xmlnsXlink`},ju=/[A-Z]/g,Mu=/-[a-z]/g,Nu=/^data[-\w.:]+$/i;function Pu(e,t){let n=cu(t),r=t,i=lu;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&Nu.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(Mu,Iu);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!Mu.test(e)){let n=e.replace(ju,Fu);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=yu}return new i(r,t)}function Fu(e){return`-`+e.toLowerCase()}function Iu(e){return e.charAt(1).toUpperCase()}var Lu=su([Su,Tu,Du,Ou,ku],`html`),Ru=su([Su,Eu,Du,Ou,ku],`svg`);function zu(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function Bu(e){return e.join(` `).trim()}var Vu=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=`
18
+ `]},t))})]}):(0,U.jsx)(`p`,{className:`update-manual-note`,children:e.errorMessage??`See ~/.local/share/cctally/update.log for the full failure log.`}),(0,U.jsxs)(`p`,{className:`update-stream-cap`,children:[`Full log: `,(0,U.jsx)(`code`,{children:`~/.local/share/cctally/update.log`})]}),(0,U.jsxs)(`div`,{className:`update-actions`,children:[(0,U.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,onClick:o,children:`Retry`}),(0,U.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:s,disabled:!r,children:t===`ok`?`Copied!`:t===`err`?`Copy failed`:`Copy command`}),(0,U.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>it.close(),children:`Close`})]})]})}var is={idle:`Update available`,running:`Updating cctally`,success:`Update complete`,failed:`Update failed`},as={idle:`accent-amber`,running:`accent-amber`,success:`accent-green`,failed:`accent-red`};function os(){let e=(0,_.useSyncExternalStore)(V,()=>B().update),t=()=>H({type:`CLOSE_UPDATE_MODAL`});if(Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:t,when:()=>B().update.modalOpen}],[])),!e.modalOpen||!e.state)return null;let n=e.status,r=as[n]??`accent-amber`,i=is[n]??`Update`;n===`running`&&e.state.latest_version?i=`Updating cctally → ${e.state.latest_version}`:n===`success`&&e.state.latest_version&&(i=`Update complete → ${e.state.latest_version}`);let a;switch(n){case`running`:a=(0,U.jsx)(Zo,{});break;case`success`:a=(0,U.jsx)(es,{});break;case`failed`:a=(0,U.jsx)(rs,{});break;default:a=(0,U.jsx)(Ko,{});break}return(0,U.jsxs)(`div`,{id:`update-modal-root`,className:`update-modal-root`,children:[(0,U.jsx)(`div`,{className:`modal-backdrop`,onClick:t}),(0,U.jsxs)(`div`,{className:`modal-card update-modal-card ${r}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-modal-title`,children:[(0,U.jsx)(`div`,{className:`modal-handle`,"aria-hidden":`true`}),(0,U.jsxs)(`header`,{className:`modal-header`,children:[(0,U.jsx)(`h2`,{id:`update-modal-title`,children:i}),(0,U.jsx)(`button`,{className:`modal-close`,"aria-label":`Close`,onClick:t,children:`×`})]}),(0,U.jsx)(`div`,{className:`modal-body`,children:a})]})]})}function ss({title:e,accentClass:t,children:n,headerExtras:r}){let i=()=>H({type:`CLOSE_MODAL`});return Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:i}],[])),(0,U.jsxs)(`div`,{id:`modal-root`,children:[(0,U.jsx)(`div`,{className:`modal-backdrop`,onClick:i}),(0,U.jsxs)(`div`,{className:`modal-card ${t}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`modal-title`,children:[(0,U.jsx)(`div`,{className:`modal-handle`,"aria-hidden":`true`}),(0,U.jsxs)(`header`,{className:`modal-header`,children:[(0,U.jsx)(`h2`,{id:`modal-title`,children:e}),r,(0,U.jsx)(`button`,{className:`modal-close`,"aria-label":`Close`,onClick:i,children:`×`})]}),(0,U.jsx)(`div`,{id:`modal-body`,className:`modal-body`,children:n})]})]})}function cs(e){return e==null||!isFinite(e)?0:Math.max(0,Math.min(100,e))}function ls(e,t,n){let r=A.dateShort(t,n);return e&&r?`${e} → ${r}`:e||(r?`→ ${r}`:`—`)}function us(e){if(e==null||!isFinite(e))return[`—`,``];let t=(+e).toFixed(1),n=t.indexOf(`.`);return n===-1?[t,`.0%`]:[t.slice(0,n),t.slice(n)+`%`]}function ds(e){let t=[],n=[...e].sort((e,t)=>(e.percent??0)-(t.percent??0));for(let e of n)e.percent!=null&&(t.length&&e.percent-(t[t.length-1].percent??0)<3||t.push(e));return t}function fs(e){if(!Array.isArray(e)||e.length<2)return null;let t=e.map(e=>e.marginal_usd).filter(e=>e!=null&&isFinite(e)),n=t.length?t.reduce((e,t)=>e+t,0)/t.length:null,r=e[e.length-1].percent,i=[];return n!=null&&i.push(`avg marginal $`+n.toFixed(2)),r!=null&&i.push(`latest at `+r+`%`),i.length?i.join(` · `):null}function ps(e,t){let n=[];for(let t of e)n.push({kind:`milestone`,ts:t.captured_at_utc,data:t});for(let e of t)n.push({kind:`credit`,ts:e.effective_reset_at_utc,data:e});return n.sort((e,t)=>e.ts.localeCompare(t.ts)),n}function ms(){let e=W(),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e?.current_week??null,i=e?.header??null,a=Array.isArray(r?.milestones)?r.milestones:[],o=Array.isArray(r?.five_hour_milestones)?r.five_hour_milestones:[],s=ps(o,Array.isArray(r?.five_hour_block?.credits)?r.five_hour_block.credits:[]),c=cs(r?.used_pct),[l,u]=us(r?.used_pct),d=r?ls(i?.week_label,r.reset_at_utc,n):`—`,f=ds(a),p=fs(a);return(0,U.jsx)(ss,{title:`Current Week — per-percent milestones`,accentClass:`accent-green`,headerExtras:(0,U.jsx)(qt,{panel:`current-week`,panelLabel:`Current week`,triggerId:`current-week-modal`,onClick:()=>H(R(`current-week`,`current-week-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-current-week`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,id:`mcw-badges`,children:(0,U.jsx)(`span`,{className:`m-pill accent-green`,id:`mcw-week-pill`,children:d})}),(0,U.jsxs)(`div`,{className:`mcw-herobar`,children:[(0,U.jsxs)(`div`,{className:`mcw-bignum`,id:`mcw-bignum`,children:[(0,U.jsx)(`span`,{className:`int`,children:l}),(0,U.jsx)(`span`,{className:`unit`,children:u})]}),(0,U.jsxs)(`div`,{className:`mcw-pbar-wrap`,children:[(0,U.jsxs)(`div`,{className:`mcw-pbar`,children:[(0,U.jsx)(`div`,{className:`fill`,id:`mcw-fill`,style:{width:c+`%`}}),(0,U.jsx)(`div`,{className:`ticks`,id:`mcw-ticks`,children:f.map(e=>(0,U.jsx)(`div`,{className:`tick`,"data-p":String(e.percent),style:{left:cs(e.percent)+`%`}},e.percent))}),(0,U.jsx)(`div`,{className:`marker`,id:`mcw-marker`,style:{left:c+`%`}})]}),(0,U.jsxs)(`div`,{className:`mcw-pscale`,children:[(0,U.jsx)(`span`,{children:`0%`}),(0,U.jsx)(`span`,{children:`25%`}),(0,U.jsx)(`span`,{children:`50%`}),(0,U.jsx)(`span`,{children:`75%`}),(0,U.jsx)(`span`,{children:`100%`})]})]}),(0,U.jsxs)(`div`,{className:`mcw-mini`,id:`mcw-mini`,children:[(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`spent`}),(0,U.jsx)(`span`,{className:`v v-magenta`,id:`mcw-spent`,children:A.usd2(r?.spent_usd)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`$ / 1%`}),(0,U.jsx)(`span`,{className:`v v-cyan`,id:`mcw-dpp`,children:A.usd3(r?.dollar_per_pct)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`reset`}),(0,U.jsx)(`span`,{className:`v`,id:`mcw-reset`,children:A.datetimeShortZ(r?.reset_at_utc,n)})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-ms`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Milestones`]}),(0,U.jsxs)(`div`,{className:`mcw-mshead`,children:[(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mcw-ms-count`,children:[a.length,` crossed`]}),(0,U.jsx)(`span`,{className:`mcw-ms-sub`,id:`mcw-ms-sub`,hidden:!p,children:p??``})]}),a.length===0?(0,U.jsx)(`p`,{className:`empty-state`,id:`mcw-empty`,children:`No milestones yet — earliest crosses at 1\xA0%.`}):(0,U.jsxs)(`table`,{className:`m-histable`,id:`mcw-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`%`}),(0,U.jsxs)(`th`,{children:[`Crossed (`,t.offsetLabel,`)`]}),(0,U.jsx)(`th`,{className:`num`,children:`Cumulative $`}),(0,U.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,U.jsx)(`th`,{className:`num`,children:`5h %`})]})}),(0,U.jsx)(`tbody`,{id:`mcw-rows`,children:a.map(e=>(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:e.percent??`—`})}),(0,U.jsx)(`td`,{className:`d`,children:A.startedShort(e.crossed_at_utc,n,{noSuffix:!0})}),(0,U.jsx)(`td`,{className:`num`,children:e.cumulative_usd==null?`—`:`$`+e.cumulative_usd.toFixed(2)}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-marginal`,children:e.marginal_usd==null?`—`:`$`+e.marginal_usd.toFixed(2)})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-fh`,children:e.five_hour_pct_at_cross==null?`—`:Math.round(e.five_hour_pct_at_cross)+`%`})})]},e.percent))})]}),s.length>0&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-ms sec-5h`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`5h milestones`]}),(0,U.jsx)(`div`,{className:`mcw-mshead`,children:(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mcw-5h-count`,children:[o.length,` crossed`]})}),(0,U.jsxs)(`table`,{className:`m-histable mcw-5h-table`,id:`mcw-5h-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`%`}),(0,U.jsxs)(`th`,{children:[`When (`,t.offsetLabel,`)`]}),(0,U.jsx)(`th`,{className:`num`,children:`Block $`}),(0,U.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,U.jsx)(`th`,{className:`num`,children:`7d %`})]})}),(0,U.jsx)(`tbody`,{children:s.map((e,t)=>{if(e.kind===`credit`)return(0,U.jsx)(`tr`,{className:`mcw-5h-credit-row`,children:(0,U.jsxs)(`td`,{colSpan:5,className:`mcw-5h-credit-cell`,children:[`⚡ CREDIT\xA0`,` `,e.data.delta_pp>0?`+`:``,e.data.delta_pp.toFixed(0),`pp\xA0@`,` `,A.startedShort(e.ts,n,{noSuffix:!0})]})},`credit-${t}-${e.ts}`);let r=e.data;return(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:r.percent_threshold})}),(0,U.jsx)(`td`,{className:`d`,children:A.startedShort(r.captured_at_utc,n,{noSuffix:!0})}),(0,U.jsx)(`td`,{className:`num`,children:`$`+r.block_cost_usd.toFixed(2)}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-marginal`,children:r.marginal_cost_usd==null?`—`:`$`+r.marginal_cost_usd.toFixed(2)})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(`span`,{className:`m-fh`,children:r.seven_day_pct_at_crossing==null?`—`:Math.round(r.seven_day_pct_at_crossing)+`%`})})]},`fhms-${r.percent_threshold}-${r.reset_event_id}`)})})]})]})]})})}function hs(e){if(!e)return`—`;let t=e.elapsed_hours,n=e.remaining_hours;if(t==null||n==null)return`—`;let r=t+n;if(r<=0)return`—`;let i=t/r*100;return Math.min(100,i).toFixed(1)+`%`}function gs(e){return e==null||!isFinite(e)?null:e<0?0:e>110?110:e}function _s(e){return e==null||!isFinite(e)?`—`:e<0?`~`+(+e).toFixed(1)+`%`:(+e).toFixed(1)+`%`}function vs(e,t){for(let t of e)t.trueXPct=t.pos/110*100;if(e.length<2||t<=0){for(let t of e)t.resolvedXPct=t.trueXPct;return}let n=e.slice().sort((e,t)=>e.trueXPct-t.trueXPct),r=n[0],i=n[1],a=r.pillWidthPx/2/t*100,o=i.pillWidthPx/2/t*100,s=8/t*100,c=a+o+s,l=2*c;if(i.trueXPct-r.trueXPct<c){let e=(r.trueXPct+i.trueXPct)/2;r.resolvedXPct=e-l/2,i.resolvedXPct=e+l/2;let t=a,n=100-o;r.resolvedXPct<t&&(r.resolvedXPct=t,i.resolvedXPct-r.resolvedXPct<l&&(i.resolvedXPct=Math.min(n,r.resolvedXPct+l))),i.resolvedXPct>n&&(i.resolvedXPct=n,i.resolvedXPct-r.resolvedXPct<l&&(r.resolvedXPct=Math.max(t,i.resolvedXPct-l)))}else r.resolvedXPct=r.trueXPct,i.resolvedXPct=i.trueXPct}function ys(e,t,n){(0,_.useEffect)(()=>{let r=e.current,i=t.current;if(!r||!i||!n)return;let a=r.querySelector(`.mfc-pills`),o=r.querySelector(`.mfc-leaders`),s=i.querySelector(`.mfc-rangeband`);if(!a||!o)return;let c=n.week_avg_projection_pct,l=n.recent_24h_projection_pct,u=gs(c),d=gs(l),f=[];u!=null&&c!=null&&f.push({kind:`wa`,pos:u,raw:c}),d!=null&&l!=null&&f.push({kind:`r24`,pos:d,raw:l});let p=new Set(f.map(e=>e.kind));i.querySelectorAll(`.mfc-chev`).forEach(e=>{let t=e.dataset.kind;(!t||!p.has(t))&&e.remove()}),a.querySelectorAll(`.mfc-pill`).forEach(e=>{let t=e.dataset.kind;(!t||!p.has(t))&&e.remove()});let m=f.map(e=>({...e,trueXPct:0,resolvedXPct:0,pillWidthPx:0}));for(let e of m){let t=e.pos/110*100,n=i.querySelector(`.mfc-chev[data-kind="${e.kind}"]`);n||(n=document.createElement(`div`),n.className=`mfc-chev `+e.kind,n.dataset.kind=e.kind,i.appendChild(n)),n.style.left=t+`%`;let r=a.querySelector(`.mfc-pill[data-kind="${e.kind}"]`),o=_s(e.raw);r?r.textContent!==o&&(r.textContent=o):(r=document.createElement(`div`),r.className=`mfc-pill `+e.kind,r.dataset.kind=e.kind,r.textContent=o,a.appendChild(r)),e.pillEl=r}if(s){let e=!1;if(m.length===2){let t=m[0].pos/110*100,n=m[1].pos/110*100,r=Math.min(t,n),i=Math.max(t,n)-r;i>=.5&&(s.style.left=r+`%`,s.style.width=i+`%`,e=!0)}s.hidden=!e}let h=()=>{for(let e of m)if(!e.pillEl||!e.pillEl.isConnected)return;let e=r.clientWidth;if(e<=0){requestAnimationFrame(h);return}for(let e of m)e.pillWidthPx=e.pillEl.getBoundingClientRect().width;vs(m,e);for(let e of m)e.pillEl.style.left=e.resolvedXPct+`%`;for(;o.firstChild;)o.removeChild(o.firstChild);for(let e of m){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`class`,e.kind),t.setAttribute(`vector-effect`,`non-scaling-stroke`),t.setAttribute(`d`,`M ${e.resolvedXPct} 0 C ${e.resolvedXPct} 10, ${e.trueXPct} 8, ${e.trueXPct} 18`),o.appendChild(t)}};h()},[e,t,n])}function bs(){let e=W()?.forecast??null,t=e?.explain??null,n=(0,_.useRef)(null),r=(0,_.useRef)(null);ys(n,r,e);let i=(0,U.jsx)(qt,{panel:`forecast`,panelLabel:`Forecast`,triggerId:`forecast-modal`,onClick:()=>H(R(`forecast`,`forecast-modal`))});if(!e)return(0,U.jsx)(ss,{title:`Forecast — explain`,accentClass:`accent-purple`,headerExtras:i,children:(0,U.jsx)(`section`,{className:`modal-forecast`,children:(0,U.jsx)(`p`,{className:`empty-state`,id:`mfc-empty`,children:`No forecast data yet.`})})});let a=Ct(e.verdict),o=a?`m-pill ${a.accent}`:`m-pill`,s=a?`${a.glyph} ${a.label}`:`—`,c=`m-pill`,l=`—`,u=!0;e.confidence===`high`?(c=`m-pill accent-blue`,l=`high confidence`,u=!1):e.confidence===`low`&&(c=`m-pill accent-red`,l=`low confidence`,u=!1);let d=t?.rates,f=t?.week;return(0,U.jsx)(ss,{title:`Forecast — explain`,accentClass:`accent-purple`,headerExtras:i,children:(0,U.jsxs)(`section`,{className:`modal-forecast`,children:[(0,U.jsxs)(`div`,{className:`m-chipstrip`,id:`mfc-chips`,children:[(0,U.jsx)(`span`,{className:o,id:`mfc-verdict`,children:s}),(0,U.jsx)(`span`,{className:c,id:`mfc-confidence`,hidden:u,children:l})]}),(0,U.jsxs)(`div`,{className:`m-hero cols-2`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-wa`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#gauge`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mfc-wa-pct`,children:A.pct1(e.week_avg_projection_pct)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Week-avg projection`}),(0,U.jsx)(`div`,{className:`sub`,id:`mfc-wa-sub`,children:A.ratePctPerHour(d?.week_average_pct_per_hour)})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-r24`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#zap`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mfc-r24-pct`,children:A.pct1(e.recent_24h_projection_pct)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Recent-24h projection`}),(0,U.jsx)(`div`,{className:`sub`,id:`mfc-r24-sub`,children:A.ratePctPerHour(d?.recent_24h_pct_per_hour)})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-range`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#bar-chart`})}),`Range vs. caps`]}),(0,U.jsxs)(`div`,{className:`mfc-rangewrap`,id:`mfc-rangewrap`,ref:n,children:[(0,U.jsx)(`div`,{className:`mfc-pills`,id:`mfc-pills`}),(0,U.jsx)(`svg`,{className:`mfc-leaders`,id:`mfc-leaders`,viewBox:`0 0 100 18`,preserveAspectRatio:`none`,"aria-hidden":`true`}),(0,U.jsxs)(`div`,{className:`mfc-rangetrack`,id:`mfc-rangetrack`,ref:r,children:[(0,U.jsx)(`div`,{className:`mfc-zone safe`}),(0,U.jsx)(`div`,{className:`mfc-zone warn`}),(0,U.jsx)(`div`,{className:`mfc-zone over`}),(0,U.jsx)(`div`,{className:`mfc-rangeband`,id:`mfc-rangeband`,hidden:!0}),(0,U.jsx)(`div`,{className:`mfc-bound b90`,children:(0,U.jsx)(`div`,{className:`lbl`,children:`90%`})}),(0,U.jsx)(`div`,{className:`mfc-bound b100`,children:(0,U.jsx)(`div`,{className:`lbl`,children:`100%`})})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-rates`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`Rates`]}),(0,U.jsxs)(`div`,{className:`mfc-kvgrid`,children:[(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`$ / 1%`}),(0,U.jsx)(`span`,{className:`v v-cyan`,id:`mfc-dpp`,children:A.usd3(d?.dollars_per_percent)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`week done`}),(0,U.jsx)(`span`,{className:`v v-green`,id:`mfc-wkdone`,children:hs(f)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`elapsed`}),(0,U.jsx)(`span`,{className:`v v-green`,id:`mfc-elapsed`,children:A.hours1(f?.elapsed_hours)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`remaining`}),(0,U.jsx)(`span`,{className:`v`,id:`mfc-remain`,children:A.hours1(f?.remaining_hours)})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-bud`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),`Daily budgets to stay under`]}),(0,U.jsxs)(`div`,{className:`mfc-kvgrid mfc-kvgrid-single`,children:[(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`@ 100% cap`}),(0,U.jsx)(`span`,{className:`v v-magenta`,id:`mfc-bud100`,children:A.usd2PerDay(e.budget_100_per_day_usd)})]}),(0,U.jsxs)(`div`,{className:`mfc-krow`,children:[(0,U.jsx)(`span`,{className:`l`,children:`@ 90% cap`}),(0,U.jsx)(`span`,{className:`v v-amber`,id:`mfc-bud90`,children:A.usd2PerDay(e.budget_90_per_day_usd)})]})]})]})})}function xs(e){let t=Math.max(1,Math.round(e/4));return`${e} week${e===1?``:`s`} · ${t} month${t===1?``:`s`}`}function Ss(e){let t=e.findIndex(e=>e&&e.is_current);return t>=0?t:e.length-1}function Cs(e,t){let n=e.filter((e,n)=>n!==t).map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e));if(n.length<4)return null;let r=n.slice(-4).sort((e,t)=>e-t);return(r[1]+r[2])/2}function ws(e){if(!e.length)return null;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function Ts(e,t){let n=[];if(!e.length)return n;let r={left:44,right:14,top:12,bottom:22},i=600-r.left-r.right,a=140-r.top-r.bottom,o=e.length,s=e=>r.left+(o===1?i:e/(o-1)*i),c=e.map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e)),l=c.length?Math.min(...c)*.96:0,u=c.length?Math.max(...c)*1.04:1;u-l<1e-6&&(l-=.01,u+=.01);let d=e=>r.top+a*(1-(e-l)/(u-l)),f=e.map(e=>e.used_pct).filter(e=>e!=null&&isFinite(e)),p=f.length?Math.min(...f)*.96:0,m=f.length?Math.max(...f)*1.04:100;m-p<1e-6&&(--p,m+=1);let h=e=>r.top+a*(1-(e-p)/(m-p));if(n.push({el:`line`,attrs:{class:`mtr-axis`,x1:r.left,y1:r.top+a,x2:600-r.right,y2:r.top+a},key:`axis`}),c.length){let e=ws(c);e!=null&&(n.push({el:`line`,attrs:{class:`mtr-hl`,x1:r.left,y1:d(e),x2:600-r.right,y2:d(e)},key:`med-line`}),n.push({el:`text`,attrs:{class:`mtr-medlabel`,x:r.left+2,y:d(e)-3},text:`median $`+e.toFixed(2),key:`med-label`}))}{let t=[];e.forEach((e,n)=>{e.used_pct!=null&&isFinite(e.used_pct)&&t.push(`${s(n)},${h(e.used_pct)}`)}),t.length>=2&&n.push({el:`polyline`,attrs:{class:`mtr-trendline-dim`,points:t.join(` `)},key:`poly-used`})}{let t=[];e.forEach((e,n)=>{e.dollar_per_pct!=null&&isFinite(e.dollar_per_pct)&&t.push(`${s(n)},${d(e.dollar_per_pct)}`)}),t.length>=2&&n.push({el:`polyline`,attrs:{class:`mtr-trendline`,points:t.join(` `)},key:`poly-dpp`})}e.forEach((e,r)=>{if(e.dollar_per_pct==null||!isFinite(e.dollar_per_pct))return;let i=r===t;n.push({el:`circle`,attrs:{class:`mtr-trenddot`+(i?` cur`:``),cx:s(r),cy:d(e.dollar_per_pct),r:i?5:3},key:`dot-${r}`})}),c.length&&(n.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:r.top+8},text:`$`+(u/1.04).toFixed(2),key:`ymax`}),n.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:r.top+a},text:`$`+(l/.96).toFixed(2),key:`ymin`}));let g=e[t];return g&&g.dollar_per_pct!=null&&isFinite(g.dollar_per_pct)&&n.push({el:`text`,attrs:{class:`mtr-curlabel`,x:Math.max(r.left+4,s(t)-22),y:Math.min(138,d(g.dollar_per_pct)+16)},text:`$`+g.dollar_per_pct.toFixed(2),key:`curlabel`}),n}function Es(e,t){return t===0?`Now`+(e.label?` · `+e.label:``):`W−`+t+(e.label?` · `+e.label:``)}function Ds(e){return e==null||!isFinite(e)?{cls:`flat`,text:`—`}:e>5e-4?{cls:`up`,text:`+`+e.toFixed(2)}:e<-5e-4?{cls:`down`,text:e.toFixed(2)}:{cls:`flat`,text:`0.00`}}function Os(e){return e==null||!isFinite(e)?{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`—`}:e<-5e-4?{cls:`delta-down`,iconHref:`/static/icons.svg#trending-down`,text:`−$`+Math.abs(e).toFixed(3)}:e>5e-4?{cls:`delta-up`,iconHref:`/static/icons.svg#trending-up`,text:`+$`+e.toFixed(3)}:{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`$0.000`}}function ks(){let e=W(),t=ne(e),n=(0,U.jsx)(qt,{panel:`trend`,panelLabel:`Trend`,triggerId:`trend-modal`,onClick:()=>H(R(`trend`,`trend-modal`))});if(!t.length)return(0,U.jsx)(ss,{title:`Trend — 12-week history`,accentClass:`accent-amber`,headerExtras:n,children:(0,U.jsx)(`section`,{className:`modal-trend`,children:(0,U.jsx)(`p`,{className:`empty-state`,id:`mtr-empty`,children:`No history data yet.`})})});let r=Ss(t),i=t[r],a=e?.trend?.history_median_dpp,o=a!=null&&isFinite(a)?a:Cs(t,r),s=Os(i&&i.dollar_per_pct!=null&&o!=null?i.dollar_per_pct-o:null),c=Ts(t,r),l=t.some(e=>e.used_pct!=null&&isFinite(e.used_pct)),u=t.length;return(0,U.jsx)(ss,{title:`Trend — 12-week history`,accentClass:`accent-amber`,headerExtras:n,children:(0,U.jsxs)(`section`,{className:`modal-trend`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,children:(0,U.jsx)(`span`,{className:`m-pill accent-amber`,id:`mtr-weeks-pill`,children:xs(u)})}),(0,U.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-cur`,children:i&&i.dollar_per_pct!=null?`$`+i.dollar_per_pct.toFixed(3):`—`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Current $ / 1%`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-med`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#minus`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-med`,children:o==null?`—`:`$`+o.toFixed(3)}),(0,U.jsx)(`div`,{className:`lbl`,children:`4-week median`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-delta ${s.cls}`,id:`mtr-delta-kv`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:s.iconHref})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`mtr-delta`,children:s.text}),(0,U.jsx)(`div`,{className:`lbl`,children:`vs median`})]})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-spark`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#trending-down`})}),`12-week history · $/1%`,(0,U.jsxs)(`span`,{className:`mtr-legend`+(l?``:` legend-no-used`),"aria-hidden":`true`,children:[(0,U.jsx)(`span`,{className:`sw sw-dpp`}),(0,U.jsx)(`span`,{className:`sw-lbl`,children:`$/1%`}),(0,U.jsx)(`span`,{className:`sw sw-used`}),(0,U.jsx)(`span`,{className:`sw-lbl`,children:`used %`})]})]}),(0,U.jsxs)(`div`,{className:`mtr-sparkhero`,children:[(0,U.jsx)(`svg`,{id:`mtr-svg`,viewBox:`0 0 600 140`,preserveAspectRatio:`none`,"aria-hidden":`true`,children:c.map(e=>{let{el:t,attrs:n,text:r,key:i}=e,a={};for(let e in n)a[e===`class`?`className`:e]=n[e];return t===`line`?(0,U.jsx)(`line`,{...a},i):t===`polyline`?(0,U.jsx)(`polyline`,{...a},i):t===`circle`?(0,U.jsx)(`circle`,{...a},i):(0,U.jsx)(`text`,{...a,children:r},i)})}),(0,U.jsx)(`div`,{className:`mtr-sparkaxis`,id:`mtr-sparkaxis`,children:u>0?(0,U.jsxs)(_.Fragment,{children:[(0,U.jsxs)(`span`,{children:[`W−`,u-1]}),(0,U.jsxs)(`span`,{children:[`W−`,Math.floor((u-1)/2)]}),(0,U.jsx)(`span`,{children:`Now`})]}):null})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tbl`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Weekly detail`]}),(0,U.jsxs)(`div`,{className:`mtr-tbl-head`,children:[(0,U.jsxs)(`span`,{className:`m-pill accent-purple`,id:`mtr-tbl-count`,children:[u,` weeks`]}),(0,U.jsx)(`span`,{className:`mtr-tbl-sub`,children:`current row highlighted · negative Δ = $/1% down vs prior week`})]}),(0,U.jsxs)(`table`,{className:`m-histable`,id:`mtr-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`Week`}),(0,U.jsx)(`th`,{className:`num`,children:`Used %`}),(0,U.jsx)(`th`,{className:`num`,children:`$ / 1%`}),(0,U.jsx)(`th`,{className:`num`,children:`Δ $/1%`})]})}),(0,U.jsx)(`tbody`,{id:`mtr-rows`,children:t.map((e,t)=>{let n=Es(e,u-1-t),r=e.used_pct==null?`—`:Math.round(e.used_pct)+`%`,i=e.dollar_per_pct==null?`—`:`$`+e.dollar_per_pct.toFixed(2),a=Ds(e.delta);return(0,U.jsxs)(`tr`,{className:e.is_current?`cur`:void 0,children:[(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`wlab`,children:n})}),(0,U.jsx)(`td`,{className:`num usedpct`,children:r}),(0,U.jsx)(`td`,{className:`num dpp`,children:i}),(0,U.jsx)(`td`,{className:`num delta ${a.cls}`,children:a.text})]},e.label+`|`+t)})})]})]})})}var As=/(^|\/)(subagents\/|agent-)/;function js(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Ms(){let e=(0,_.useSyncExternalStore)(V,()=>B().openSessionId),t=js(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!0),[o,s]=(0,_.useState)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(!1),u=(0,_.useRef)(null);return(0,_.useEffect)(()=>{u.current=e??B().snapshot?.sessions?.rows?.[0]?.session_id??null,l.current=!1},[e]),(0,_.useEffect)(()=>{let e=u.current;if(!e){a(!1),s(`No session available.`),r(null),c.current=null;return}let t=c.current!==e||n==null;c.current=e,t&&(a(!0),s(null),r(null));let i=new AbortController;return fetch(`/api/session/${encodeURIComponent(e)}`,{signal:i.signal}).then(async e=>{if(e.status===404){(t||l.current)&&(a(!1),s(`Session not found (the cache may have rolled forward).`),r(null)),l.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();l.current=!1,r(n),s(null),a(!1)}).catch(e=>{e.name!==`AbortError`&&(l.current=!1,t&&(s(`Failed to load: `+e.message),a(!1)))}),()=>i.abort()},[e,t]),(0,U.jsx)(ss,{title:`Session detail`,accentClass:`accent-orange`,headerExtras:(0,U.jsx)(qt,{panel:`sessions`,panelLabel:`Session`,triggerId:`session-modal`,onClick:()=>H(R(`sessions`,`session-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-sessions`,children:[i?(0,U.jsx)(`div`,{className:`modal-loading`,id:`msess-loading`,children:`Loading session detail…`}):null,o?(0,U.jsx)(`div`,{className:`modal-error`,id:`msess-error`,children:o}):null,!i&&!o&&n?(0,U.jsx)(Ns,{detail:n}):null]})})}function Ns({detail:e}){let t=Array.isArray(e.source_paths)?e.source_paths:[],n=[],r=[];t.forEach(e=>{As.test(e)?r.push(e):n.push(e)});let i=e.cost_total_usd??0,a=[[`Input`,e.input_tokens,null],[`Output`,e.output_tokens,null],[`Cache creation`,e.cache_creation_tokens,null],[`Cache read`,e.cache_read_tokens,null],[`Cache hit %`,e.cache_hit_pct,`cache-hit`]].filter(e=>e[1]!=null),o=!e.models||e.models.length===0,s=!e.cost_per_model||e.cost_per_model.length===0;return(0,U.jsxs)(`div`,{className:`modal-content`,id:`msess-content`,children:[(0,U.jsx)(`div`,{className:`m-chipstrip`,children:(0,U.jsx)(`span`,{className:`msess-badge`,id:`msess-id`,"aria-label":`Session ID`,children:e.session_id??`—`})}),(0,U.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-cost`,children:e.cost_total_usd==null?`—`:`$`+e.cost_total_usd.toFixed(2)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-dur`,children:e.duration_min==null?`—`:e.duration_min+` min`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Duration`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#folder`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,id:`msess-project`,title:e.project_path??``,"aria-label":`Project`,children:e.project_label??e.project_path??`—`}),(0,U.jsx)(`div`,{className:`lbl`,children:`Project`})]})]})]}),(0,U.jsxs)(`div`,{className:`msess-ts`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`started`}),(0,U.jsx)(`span`,{className:`v`,id:`msess-started`,children:e.started_utc??`—`})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`last activity`}),(0,U.jsx)(`span`,{className:`v`,id:`msess-last`,children:e.last_activity_utc??`—`})]})]}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,U.jsx)(`div`,{className:`msess-tok-grid`,id:`msess-tokens`,children:a.map(([e,t,n])=>(0,U.jsxs)(`div`,{className:`msess-tok-tile`+(n?` `+n:``),children:[(0,U.jsx)(`div`,{className:`lbl`,children:e}),(0,U.jsx)(`div`,{className:`n`,children:n===`cache-hit`?t.toFixed(1)+`%`:t.toLocaleString(`en-US`)}),n===`cache-hit`?(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:Math.max(0,Math.min(t,100))+`%`}})}):null]},e))}),o?null:(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-mod`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#sparkles`})}),`Models`]}),(0,U.jsx)(`div`,{className:`m-chipstrip`,id:`msess-models`,children:(e.models||[]).map(e=>(0,U.jsx)(`span`,{className:`chip `+dn(e.name),children:e.name},e.name))})]}),s?null:(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,U.jsxs)(`div`,{className:`msess-costm`,children:[(0,U.jsx)(`div`,{className:`bar`,id:`msess-cost-bar`,children:(e.cost_per_model||[]).map(e=>{let t=i>0&&e.cost_usd!=null?e.cost_usd/i*100:0;return(0,U.jsx)(`div`,{className:`seg `+dn(e.model),style:{width:t+`%`}},e.model)})}),(0,U.jsx)(`div`,{className:`legend`,id:`msess-cost-legend`,children:(e.cost_per_model||[]).map(e=>{let t=i>0&&e.cost_usd!=null?e.cost_usd/i*100:0;return(0,U.jsxs)(`div`,{className:`lg`,children:[(0,U.jsx)(`span`,{className:`sw `+dn(e.model)}),(0,U.jsx)(`span`,{className:`name`,children:e.model}),(0,U.jsx)(`span`,{className:`v`,children:e.cost_usd==null?`—`:`$`+e.cost_usd.toFixed(3)}),(0,U.jsxs)(`span`,{className:`pct`,children:[Math.round(t),`%`]})]},e.model)})})]})]}),t.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-src`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#file-text`})}),`Source files`]}),(0,U.jsxs)(`div`,{className:`msess-src`,id:`msess-src`,children:[(0,U.jsxs)(`div`,{className:`src-head`,children:[(0,U.jsxs)(`span`,{className:`count-pill`,children:[t.length,` file`,t.length===1?``:`s`]}),(0,U.jsxs)(`span`,{className:`sub`,children:[n.length,` primary`,r.length>0?(0,U.jsxs)(U.Fragment,{children:[` `,(0,U.jsx)(`span`,{className:`dot`,children:`·`}),` `,(0,U.jsxs)(`span`,{className:`subcount`,children:[r.length,` subagent`,r.length===1?``:`s`]})]}):null]})]}),n.length>0?n.map(e=>(0,U.jsx)(`div`,{className:`primary-path`,children:e},e)):r.length>0?(0,U.jsxs)(`div`,{className:`src-empty-primary`,children:[`No primary path resolved · `,r.length,` subagent path`,r.length===1?``:`s`,` below`]}):null,r.length>0?(0,U.jsxs)(`details`,{className:`subagents`,open:n.length===0,children:[(0,U.jsxs)(`summary`,{children:[`Show `,r.length,` subagent path`,r.length===1?``:`s`]}),(0,U.jsx)(`ul`,{className:`paths`,children:r.map(e=>(0,U.jsx)(`li`,{children:e},e))})]}):null]})]}):null]})}function Ps({row:e,variant:t,accentClass:n}){let r=Wt(),i={tz:r.resolvedTz,offsetLabel:r.offsetLabel},a=(e,t)=>`${A.datetimeShort(e,i)} → ${A.datetimeShort(t,i)}`,o=e.delta_cost_pct==null?`flat`:e.delta_cost_pct>0?`up`:e.delta_cost_pct<0?`down`:`flat`,s=t===`weekly`?`week`:t===`monthly`?`month`:`day`,c=t===`daily`?`Today`:`Now`;return(0,U.jsxs)(`div`,{className:`detail-card ${n}`,children:[(0,U.jsxs)(`div`,{className:`head`,children:[(0,U.jsxs)(`div`,{className:`big`,children:[e.label,e.is_current&&(0,U.jsx)(`span`,{className:`pill-current`,children:c})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`cost`,style:{color:`var(--text)`,fontWeight:700},children:A.usd2(e.cost_usd)}),` `,e.delta_cost_pct==null?(0,U.jsx)(`span`,{className:`delta flat`,children:`—`}):(0,U.jsxs)(`span`,{className:`delta ${o}`,children:[A.deltaPct(e.delta_cost_pct),` vs prior `,s]})]})]}),t===`weekly`&&e.week_start_at&&e.week_end_at&&(0,U.jsxs)(`div`,{className:`window`,children:[`Subscription window: `,a(e.week_start_at,e.week_end_at)]}),(0,U.jsx)(`div`,{className:`model-stack`,role:`presentation`,children:e.models.map(e=>(0,U.jsx)(`span`,{className:e.chip,style:{width:`${e.cost_pct}%`}},e.model))}),(0,U.jsx)(`div`,{className:`chips`,children:e.models.map(e=>(0,U.jsxs)(`span`,{className:`chip ${e.chip}`,children:[e.display,` `,Math.round(e.cost_pct),`% · `,A.usd2(e.cost_usd)]},e.model))}),(0,U.jsxs)(`div`,{className:`tokens-row`,children:[(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Input`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.input_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Output`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.output_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache+`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.cache_creation_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache-read`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.cache_read_tokens)})]}),(0,U.jsxs)(`div`,{className:`t`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Total`}),(0,U.jsx)(`span`,{className:`v`,children:A.compact(e.total_tokens)})]}),e.cache_hit_pct!=null&&(0,U.jsxs)(`div`,{className:`t cache`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache hit`}),(0,U.jsxs)(`span`,{className:`v`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:`${Math.min(100,Math.max(0,e.cache_hit_pct))}%`}})})]})]}),t===`weekly`&&(0,U.jsxs)(`div`,{className:`stats2`,children:[(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Used %`}),(0,U.jsx)(`span`,{className:`v`,children:A.pct0(e.used_pct)})]}),(0,U.jsxs)(`div`,{className:`s`,children:[(0,U.jsx)(`span`,{className:`k`,children:`$/1%`}),(0,U.jsx)(`span`,{className:`v`,children:A.usd2(e.dollar_per_pct)})]})]})]})}function Fs(e){return e==null||e===0?`num`:e>0?`num delta-up`:`num delta-down`}function Is(e){let t=new Set,n=[];for(let r of e.models)t.has(r.chip)||(t.add(r.chip),n.push(r.chip));return n}function Ls({row:e}){let t=Is(e),n=t.slice(0,3),r=t.length>3?t.length-3:0;return(0,U.jsxs)(`span`,{className:`models-chips`,children:[n.map(e=>(0,U.jsx)(`span`,{className:`chip ${e}`,children:e},e)),r>0&&(0,U.jsxs)(`span`,{className:`models-chips-more`,children:[`…+`,r]})]})}function Rs({rows:e,variant:t,accentClass:n,selectedIndex:r,onSelect:i}){return(0,U.jsxs)(`table`,{className:`history-table history-table--${t} ${n}`,role:`grid`,"aria-rowcount":e.length,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:t===`weekly`?`Week`:`Month`}),(0,U.jsx)(`th`,{children:`Models`}),(0,U.jsx)(`th`,{className:`num`,children:`Cost (USD)`}),t===`weekly`&&(0,U.jsx)(`th`,{className:`num`,children:`Used %`}),t===`weekly`&&(0,U.jsx)(`th`,{className:`num`,children:`$/1%`}),(0,U.jsx)(`th`,{className:`num`,children:`Δ`})]})}),(0,U.jsx)(`tbody`,{children:e.map((e,n)=>(0,U.jsxs)(`tr`,{className:n===r?`selected`:void 0,"aria-rowindex":n+1,"aria-selected":n===r,onClick:()=>i(n),children:[(0,U.jsxs)(`td`,{children:[e.label,n===r?` ▶`:``]}),(0,U.jsx)(`td`,{children:(0,U.jsx)(Ls,{row:e})}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(e.cost_usd)}),t===`weekly`&&(0,U.jsx)(`td`,{className:`num`,children:A.pct0(e.used_pct)}),t===`weekly`&&(0,U.jsx)(`td`,{className:`num`,children:A.usd2(e.dollar_per_pct)}),(0,U.jsx)(`td`,{className:Fs(e.delta_cost_pct),children:A.deltaPct(e.delta_cost_pct)})]},e.label))})]})}function zs(){let e=W()?.weekly?.rows??[],[t,n]=(0,_.useState)(0),r=e.length;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`weekly`,action:()=>n(e=>Math.min(e+1,Math.max(0,r-1)))},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`weekly`,action:()=>n(e=>Math.max(e-1,0))}]),[r]);let i=(0,U.jsx)(qt,{panel:`weekly`,panelLabel:`Weekly`,triggerId:`weekly-modal`,onClick:()=>H(R(`weekly`,`weekly-modal`))});if(r===0)return(0,U.jsx)(ss,{title:`Weekly history · last 12`,accentClass:`accent-cyan`,headerExtras:i,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let a=e[Math.min(t,r-1)];return(0,U.jsxs)(ss,{title:`Weekly history · last 12`,accentClass:`accent-cyan`,headerExtras:i,children:[(0,U.jsx)(Ps,{row:a,variant:`weekly`,accentClass:`accent-cyan`}),(0,U.jsx)(Rs,{rows:e,variant:`weekly`,accentClass:`accent-cyan`,selectedIndex:t,onSelect:n})]})}function Bs(){let e=W()?.monthly?.rows??[],[t,n]=(0,_.useState)(0),r=e.length;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`monthly`,action:()=>n(e=>Math.min(e+1,Math.max(0,r-1)))},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`monthly`,action:()=>n(e=>Math.max(e-1,0))}]),[r]);let i=(0,U.jsx)(qt,{panel:`monthly`,panelLabel:`Monthly`,triggerId:`monthly-modal`,onClick:()=>H(R(`monthly`,`monthly-modal`))});if(r===0)return(0,U.jsx)(ss,{title:`Monthly history · last 12`,accentClass:`accent-pink`,headerExtras:i,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let a=e[Math.min(t,r-1)];return(0,U.jsxs)(ss,{title:`Monthly history · last 12`,accentClass:`accent-pink`,headerExtras:i,children:[(0,U.jsx)(Ps,{row:a,variant:`monthly`,accentClass:`accent-pink`}),(0,U.jsx)(Rs,{rows:e,variant:`monthly`,accentClass:`accent-pink`,selectedIndex:t,onSelect:n})]})}var Vs=720,Hs=180,Us={left:46,right:20,top:18,bottom:20};function Ws(e){return e===0?`$0`:e<10?`$`+e.toFixed(2):`$`+Math.round(e).toString()}function Gs(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Ks({detail:e}){let t=Gs(),n=Wt(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},i=Date.parse(e.start_at),a=Date.parse(e.end_at)-i||1,o=e=>Us.left+(Date.parse(e)-i)/a*(Vs-Us.left-Us.right),s=Math.max(e.cost_usd,e.projection?.total_cost_usd??0),c=e=>{let t=Us.top,n=Hs-Us.bottom;return s<=0?n:n-e/s*(n-t)},l=[];for(let e=0;e<=5;e++)l.push(new Date(i+e*36e5).toISOString());let u=e.samples.length>0?e.samples[e.samples.length-1].cum:0,d=e.is_active?t||new Date().toISOString():null,f=[];if(e.samples.length>0){f.push([o(e.start_at),c(0)]);for(let t of e.samples)f.push([o(t.t),c(t.cum)]);d&&f.push([o(d),c(u)])}let p=f.map(([e,t])=>`${e.toFixed(1)},${t.toFixed(1)}`).join(` `),m=f.length>0?`M ${p.replace(/ /g,` L `)} L ${f[f.length-1][0].toFixed(1)},${c(0).toFixed(1)} Z`:``,h=s<=0?[0]:[0,s/2,s];return(0,U.jsx)(`div`,{className:`mblock-timeline`,children:(0,U.jsxs)(`svg`,{viewBox:`0 0 ${Vs} ${Hs}`,style:{width:`100%`,height:`auto`},role:`img`,"aria-label":`Cumulative cost over the 5-hour block window`,children:[h.map(e=>(0,U.jsx)(`text`,{x:8,y:c(e)+4,fill:`var(--text-dim)`,fontSize:10,children:Ws(e)},e)),(0,U.jsx)(`line`,{x1:Us.left,y1:Us.top,x2:Us.left,y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),(0,U.jsx)(`line`,{x1:Us.left,y1:Hs-Us.bottom,x2:Vs-Us.right,y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),l.slice(1,-1).map(e=>(0,U.jsx)(`line`,{x1:o(e),y1:Us.top,x2:o(e),y2:Hs-Us.bottom,stroke:`var(--border-soft)`,strokeDasharray:`2 3`,strokeWidth:.5},e)),l.map(e=>(0,U.jsx)(`text`,{x:o(e)-14,y:Hs-5,fill:`var(--text-dim)`,fontSize:9,children:A.timeHHmm(e,r,{noSuffix:!0})},e)),f.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`path`,{d:m,fill:`var(--accent-green)`,opacity:.12}),(0,U.jsx)(`polyline`,{points:p,fill:`none`,stroke:`var(--accent-green)`,strokeWidth:2}),(0,U.jsx)(`circle`,{cx:f[f.length-1][0],cy:f[f.length-1][1],r:3,fill:`var(--accent-green)`})]}):(0,U.jsx)(`text`,{x:Vs/2,y:Hs/2,fill:`var(--text-faint)`,fontSize:11,textAnchor:`middle`,children:`No spend recorded yet in this block.`}),e.is_active&&e.projection&&d&&f.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`polyline`,{points:`${o(d).toFixed(1)},${c(u).toFixed(1)} ${o(e.end_at).toFixed(1)},${c(e.projection.total_cost_usd).toFixed(1)}`,fill:`none`,stroke:`var(--accent-amber)`,strokeWidth:1.5,strokeDasharray:`5 4`,opacity:.85}),(0,U.jsx)(`circle`,{cx:o(e.end_at),cy:c(e.projection.total_cost_usd),r:3,fill:`var(--accent-amber)`,opacity:.85}),(0,U.jsxs)(`text`,{x:o(e.end_at)-50,y:c(e.projection.total_cost_usd)-6,fill:`var(--accent-amber)`,fontSize:9,children:[`proj $`,e.projection.total_cost_usd.toFixed(2)]}),(0,U.jsx)(`line`,{x1:o(d),y1:Us.top,x2:o(d),y2:Hs-Us.bottom,stroke:`var(--accent-amber)`,strokeWidth:1.2}),(0,U.jsx)(`text`,{x:o(d)+4,y:Us.top+10,fill:`var(--accent-amber)`,fontSize:9,children:`now`})]}):null]})})}function qs(){return(0,_.useSyncExternalStore)(V,()=>B().snapshot?.generated_at??``)}function Js(e,t){let n=Date.parse(e.start_at),r=e.is_active?Date.parse(t)||Date.now():e.actual_end_at?Date.parse(e.actual_end_at):Date.parse(e.end_at),i=Math.max(0,Math.floor((r-n)/6e4)),a=Math.floor(i/60),o=i%60;return`${a}h ${String(o).padStart(2,`0`)}m`}function Ys(e,t,n){return`${A.timeHHmm(e,n)} → ${A.timeHHmm(t,n)}`}function Xs(){let e=(0,_.useSyncExternalStore)(V,()=>B().openBlockStartAt),t=qs(),n=Wt(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(!1),f=(0,_.useRef)(null);return(0,_.useEffect)(()=>{f.current=e??null,d.current=!1},[e]),(0,_.useEffect)(()=>{let e=f.current;if(!e){s(!1),l(`No block bound.`),a(null),u.current=null;return}let t=u.current!==e||i==null;u.current=e,t&&(s(!0),l(null),a(null));let n=new AbortController;return fetch(`/api/block/${encodeURIComponent(e)}`,{signal:n.signal}).then(async e=>{if(e.status===404){(t||d.current)&&(s(!1),l(`Block not found (the cache may have rolled forward).`),a(null)),d.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();d.current=!1,a(n),l(null),s(!1)}).catch(e=>{e.name!==`AbortError`&&(d.current=!1,t&&(l(`Failed to load: `+e.message),s(!1)))}),()=>n.abort()},[e,t]),(0,U.jsx)(ss,{title:i?`${i.anchor===`heuristic`?`~ `:``}Block · ${i.label}`:`Block`,accentClass:`accent-blue`,headerExtras:(0,U.jsx)(qt,{panel:`blocks`,panelLabel:`5-hour block`,triggerId:`block-modal`,onClick:()=>H(R(`blocks`,`block-modal`))}),children:(0,U.jsxs)(`section`,{className:`modal-block`,children:[o?(0,U.jsx)(`div`,{className:`modal-loading`,children:`Loading block detail…`}):null,c?(0,U.jsx)(`div`,{className:`modal-error`,children:c}):null,!o&&!c&&i?(0,U.jsx)(Zs,{detail:i,generatedAt:t,ctx:r}):null]})})}function Zs({detail:e,generatedAt:t,ctx:n}){let r=e.cost_usd??0;return(0,U.jsxs)(`div`,{className:`modal-content`,children:[(0,U.jsxs)(`div`,{className:`m-chipstrip`,children:[e.is_active?(0,U.jsx)(`span`,{className:`m-pill accent-green`,children:`● Active`}):null,e.anchor===`heuristic`?(0,U.jsx)(`span`,{className:`m-pill accent-amber`,children:`~ heuristic anchor`}):null,(0,U.jsx)(`span`,{className:`m-pill accent-blue`,children:Ys(e.start_at,e.end_at,n)}),(0,U.jsxs)(`span`,{className:`m-pill`,children:[e.entries_count.toLocaleString(`en-US`),` `,e.entries_count===1?`entry`:`entries`]})]}),(0,U.jsxs)(`div`,{className:`m-hero `+(e.is_active?`cols-4`:`cols-3`),children:[(0,U.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:A.usd2(e.cost_usd)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:Js(e,t)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Elapsed`})]})]}),(0,U.jsxs)(`div`,{className:`m-kv`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:e.total_tokens.toLocaleString(`en-US`)}),(0,U.jsx)(`div`,{className:`lbl`,children:`Total tokens`})]})]}),e.is_active?(0,U.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`v`,children:e.projection?A.usd2(e.projection.total_cost_usd):`—`}),(0,U.jsxs)(`div`,{className:`lbl`,children:[`Projected`,e.projection?` · ${e.projection.remaining_minutes}m left`:``]})]})]}):null]}),(0,U.jsx)(Ks,{detail:e}),(0,U.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,U.jsxs)(`div`,{className:`msess-tok-grid mblock-tok-grid`,children:[(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Input`}),(0,U.jsx)(`div`,{className:`n`,children:e.input_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Output`}),(0,U.jsx)(`div`,{className:`n`,children:e.output_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache create`}),(0,U.jsx)(`div`,{className:`n`,children:e.cache_creation_tokens.toLocaleString(`en-US`)})]}),(0,U.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache read`}),(0,U.jsx)(`div`,{className:`n`,children:e.cache_read_tokens.toLocaleString(`en-US`)})]}),e.cache_hit_pct==null?null:(0,U.jsxs)(`div`,{className:`msess-tok-tile cache-hit`,children:[(0,U.jsx)(`div`,{className:`lbl`,children:`Cache hit %`}),(0,U.jsxs)(`div`,{className:`n`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,U.jsx)(`div`,{className:`bar`,children:(0,U.jsx)(`div`,{className:`fill`,style:{width:Math.min(100,Math.max(0,e.cache_hit_pct))+`%`}})})]})]}),e.models.length>0?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,U.jsxs)(`div`,{className:`msess-costm`,children:[(0,U.jsx)(`div`,{className:`bar`,children:e.models.map(e=>{let t=r>0?e.cost_usd/r*100:0;return(0,U.jsx)(`div`,{className:`seg `+dn(e.model),style:{width:t+`%`}},e.model)})}),(0,U.jsx)(`div`,{className:`legend`,children:e.models.map(e=>{let t=r>0?e.cost_usd/r*100:0;return(0,U.jsxs)(`div`,{className:`lg`,children:[(0,U.jsx)(`span`,{className:`sw `+dn(e.model)}),(0,U.jsx)(`span`,{className:`name`,children:e.display}),(0,U.jsxs)(`span`,{className:`v`,children:[`$`,e.cost_usd.toFixed(2)]}),(0,U.jsxs)(`span`,{className:`pct`,children:[Math.round(t),`%`]})]},e.model)})})]})]}):null,e.is_active&&e.burn_rate&&e.projection?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`h3`,{className:`m-sec sec-burn`,children:[(0,U.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,U.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),`Burn rate & projection`]}),(0,U.jsxs)(`div`,{className:`mblock-burn`,children:[(0,U.jsxs)(`div`,{className:`row`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Burn rate`}),(0,U.jsx)(`span`,{className:`v amber`,children:A.usd2(e.burn_rate.cost_per_hour)}),(0,U.jsx)(`span`,{className:`dim`,children:`/ hr`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsx)(`span`,{className:`v cyan`,children:Math.round(e.burn_rate.tokens_per_minute).toLocaleString(`en-US`)}),(0,U.jsx)(`span`,{className:`dim`,children:`tok / min`})]}),(0,U.jsxs)(`div`,{className:`row`,children:[(0,U.jsx)(`span`,{className:`k`,children:`Projection`}),(0,U.jsx)(`span`,{className:`v amber`,children:A.usd2(e.projection.total_cost_usd)}),(0,U.jsx)(`span`,{className:`dim`,children:`total`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsx)(`span`,{className:`v cyan`,children:e.projection.total_tokens.toLocaleString(`en-US`)}),(0,U.jsx)(`span`,{className:`dim`,children:`tok`}),(0,U.jsx)(`span`,{className:`sep`,children:`·`}),(0,U.jsxs)(`span`,{className:`v`,children:[e.projection.remaining_minutes,` min`]}),(0,U.jsx)(`span`,{className:`dim`,children:`remaining`})]})]})]}):null]})}function Qs({rows:e,selectedDate:t,onSelect:n}){let r=[...e].reverse(),i=r.reduce((e,t)=>Math.max(e,t.cost_usd),0),a=r.length>0?$s(r[0].date):``,o=r.length>0?$s(r[r.length-1].date):``,s=r.find(e=>e.is_today),c=s?`${$s(s.date)} · today`:``;return(0,U.jsxs)(`section`,{className:`daily-modal-bars`,"aria-label":`30-day cost`,children:[(0,U.jsxs)(`div`,{className:`daily-modal-bars-head`,children:[(0,U.jsxs)(`span`,{children:[`30-day cost · selected: `,t?$s(t):`—`]}),(0,U.jsx)(`span`,{className:`hint`,children:`↑↓ navigate · click any bar`})]}),(0,U.jsx)(`div`,{className:`daily-modal-bars-grid`,role:`img`,"aria-label":`30-day cost histogram`,children:r.map(e=>{let r=e.cost_usd<=0,a=e.date===t,o=r?4:i>0?e.cost_usd/i*100:0,s=[`bar`,r?`zero`:``,a?`sel`:``,e.is_today?`today`:``].filter(Boolean).join(` `);return(0,U.jsx)(`button`,{"data-date":e.date,className:s,style:{height:`${o}%`},disabled:r,"aria-pressed":a,"aria-label":`${e.label} cost ${e.cost_usd>0?A.usd2(e.cost_usd):`no usage`}`,title:e.cost_usd>0?`${e.label} · ${A.usd2(e.cost_usd)}`:`${e.label} · —`,onClick:()=>{r||n(e.date)}},e.date)})}),r.length>0&&(0,U.jsxs)(`div`,{className:`daily-modal-bars-axis`,children:[(0,U.jsx)(`span`,{children:a}),c&&(0,U.jsx)(`span`,{children:c}),(0,U.jsx)(`span`,{children:o})]})]})}function $s(e){let t=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],n=e.split(`-`).map(Number);return`${t[n[1]-1]} ${n[2]}`}function ec(){let e=W()?.daily?.rows??[],t=(0,_.useSyncExternalStore)(V,()=>B().openDailyDate),[n,r]=(0,_.useState)(null);(0,_.useEffect)(()=>{t&&r(t)},[]);let i=new Set(e.map(e=>e.date)),a=e[0]?.date??null,o=n&&i.has(n)?n:a;(0,_.useEffect)(()=>Bt([{key:`ArrowDown`,scope:`modal`,when:()=>B().openModal===`daily`,action:()=>{let t=o;if(!t)return;let n=e.findIndex(e=>e.date===t);n<0||n>=e.length-1||r(e[n+1].date)}},{key:`ArrowUp`,scope:`modal`,when:()=>B().openModal===`daily`,action:()=>{let t=o;if(!t)return;let n=e.findIndex(e=>e.date===t);n<=0||r(e[n-1].date)}}]),[e,o]);let s=(0,U.jsx)(qt,{panel:`daily`,panelLabel:`Daily`,triggerId:`daily-modal`,onClick:()=>H(R(`daily`,`daily-modal`))});if(e.length===0)return(0,U.jsx)(ss,{title:`Daily history · last 30`,accentClass:`accent-indigo`,headerExtras:s,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`})});let c=e.findIndex(e=>e.date===o),l=c>=0?c:0,u=e[l],d=e[l+1],f=tc(u,d);return(0,U.jsxs)(ss,{title:`Daily history · last 30`,accentClass:`accent-indigo`,headerExtras:s,children:[(0,U.jsx)(Qs,{rows:e,selectedDate:o,onSelect:r}),(0,U.jsx)(Ps,{row:f,variant:`daily`,accentClass:`accent-indigo`})]})}function tc(e,t){let n=t&&t.cost_usd>0?(e.cost_usd-t.cost_usd)/t.cost_usd:null;return{label:e.label,cost_usd:e.cost_usd,total_tokens:e.total_tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cache_creation_tokens:e.cache_creation_tokens,cache_read_tokens:e.cache_read_tokens,used_pct:null,dollar_per_pct:null,delta_cost_pct:n,is_current:e.is_today,models:e.models,cache_hit_pct:e.cache_hit_pct}}var nc=[`#d946ef`,`#c084fc`,`#60a5fa`,`#fbbf24`,`#22d3ee`],rc=`#64748b`,ic=5,ac=400,oc=150;function sc({trend:e,yMode:t,windowWeeks:n,onProjectSelect:r}){let i=(0,_.useMemo)(()=>{let t=Math.max(0,Math.min(n,e.window_weeks)),r=e.weeks.slice(-t),i=e.projects.map(e=>{let n=e.weekly_cost.slice(-t),r=n.reduce((e,t)=>e+t,0);return{key:e.key,weekly:n,cost:r,color:``}}).sort((e,t)=>t.cost-e.cost),a=i.slice(0,ic).map((e,t)=>({...e,color:nc[t]??rc})),o=i.slice(ic),s=r.map((e,t)=>o.reduce((e,n)=>e+(n.weekly[t]??0),0)),c=s.reduce((e,t)=>e+t,0),l=[...a];return o.length>0&&c>0&&l.push({key:`(other)`,weekly:s,cost:c,color:rc}),{weeks:r,series:l}},[e,n]),a=cn();if(i.weeks.length===0||i.series.length===0)return(0,U.jsxs)(`div`,{className:`panel-empty`,children:[`No project activity in the last `,n,` week`,n===1?``:`s`,`.`]});let o=i.weeks.length,s=i.weeks.map((e,t)=>i.series.reduce((e,n)=>e+(n.weekly[t]??0),0)),c=t===`share`?100:Math.max(...s,.01),l=(e,t=`left`)=>o<=1?t===`left`?ac*.1:ac*.9:e/(o-1)*ac,u=Array(o).fill(0),d=i.series.map(e=>{let n=[];for(let e=0;e<o;e++){let t=oc-u[e]/c*oc;n.push(`${l(e,`left`).toFixed(2)},${t.toFixed(2)}`),o===1&&n.push(`${l(e,`right`).toFixed(2)},${t.toFixed(2)}`)}for(let r=o-1;r>=0;r--){let i=s[r]??0,a=t===`share`?i>0?(e.weekly[r]??0)/i*100:0:e.weekly[r]??0;u[r]+=a;let d=oc-u[r]/c*oc;o===1&&n.push(`${l(r,`right`).toFixed(2)},${d.toFixed(2)}`),n.push(`${l(r,`left`).toFixed(2)},${d.toFixed(2)}`)}return{color:e.color,key:e.key,points:n.join(` `)}}),f=i.weeks.map(e=>(0,U.jsx)(`span`,{children:e.week_label},e.week_start_date));return(0,U.jsxs)(`div`,{className:`projects-trend`,children:[(0,U.jsx)(`svg`,{viewBox:`0 0 ${ac} ${oc}`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Stacked area: project ${t===`share`?`share %`:`cost`} over ${o} weeks`,children:d.map(e=>{let t=e.key===`(other)`;return(0,U.jsx)(`polygon`,{fill:e.color,opacity:t?.5:.65,points:e.points,"data-series-key":e.key,onClick:()=>{t||r?.(e.key)},style:{cursor:t?`default`:`pointer`}},e.key)})}),(0,U.jsx)(`div`,{className:`projects-trend-xaxis`,children:f}),(0,U.jsx)(`div`,{className:`projects-trend-legend`,children:i.series.map(e=>{let t=e.key===`(other)`,n=(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{className:`sw`,style:{background:e.color}}),e.key]});return a&&!t?(0,U.jsx)(`button`,{type:`button`,className:`projects-trend-legend-item`,"data-series-key":e.key,onClick:()=>r?.(e.key),children:n},e.key):(0,U.jsx)(`span`,{className:`projects-trend-legend-item`,"data-series-key":e.key,children:n},e.key)})})]})}function cc(e,t){let[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),c=W()?.generated_at??``,l=(0,_.useRef)(0),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(!1);return(0,_.useEffect)(()=>{if(!e){r(null),a(!1),s(null),l.current=0,u.current=null,d.current=null,f.current=!1;return}let i=u.current!==e||d.current!==t,o=i||n==null;if(o&&f.current&&!i)return;o&&(a(!0),s(null)),i&&(l.current=0),u.current=e,d.current=t,f.current=!0;let c=new AbortController,p=`/api/project/${encodeURIComponent(e)}?weeks=${t}`;return fetch(p,{signal:c.signal}).then(async e=>{if(e.status===404){l.current+=1,l.current>=2?(r(null),s(`Project no longer in cache — close this drill.`),a(!1)):o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1));return}if(!e.ok){o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1));return}l.current=0,r(await e.json()),s(null),a(!1)}).catch(e=>{e?.name!==`AbortError`&&o&&(s(`Couldn't load project detail — will retry on next tick.`),a(!1))}).finally(()=>{f.current=!1}),()=>c.abort()},[e,t,c]),{data:n,loading:i,error:o}}function lc({projectKey:e,windowWeeks:t}){let{data:n,loading:r,error:i}=cc(e,t),a=Wt(),o={tz:a.resolvedTz,offsetLabel:a.offsetLabel},s=n!=null&&(n.key!==e||n.window_weeks!==t);if(r&&!n||s)return(0,U.jsx)(`div`,{className:`panel-empty`,children:`Loading…`});if(i&&!n)return(0,U.jsx)(`div`,{className:`panel-empty`,children:i});if(!n)return null;let c=n.models[0]?.cost_usd??0,l=c>0?c:1,u=Math.max(0,n.sessions_total-n.sessions.length);return(0,U.jsxs)(`div`,{className:`projects-drill`,"data-testid":`projects-drill`,"aria-live":`polite`,children:[(0,U.jsx)(`div`,{className:`projects-drill-head`,children:(0,U.jsxs)(`span`,{className:`title`,children:[`▾ `,n.key,` · `,n.sessions_total,` session`,n.sessions_total===1?``:`s`,` · `,A.usd2(n.window_cost_usd),` (`,t,`w)`]})}),(0,U.jsxs)(`div`,{className:`projects-drill-grid`,children:[(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`section-label`,children:`Models (this project)`}),n.models.length===0?(0,U.jsx)(`div`,{className:`muted`,children:`No model data for this window.`}):n.models.map(e=>{let t={"--w":`${e.cost_usd/l*100}%`};return(0,U.jsxs)(`div`,{className:`drill-bar-row`,children:[(0,U.jsx)(`span`,{className:`chip ${dn(e.model)}`,children:e.model}),(0,U.jsx)(`div`,{className:`drill-bar`,style:t}),(0,U.jsx)(`span`,{className:`cost ${fn(e.cost_usd)}`,children:A.usd2(e.cost_usd)})]},e.model)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`section-label`,children:`Recent sessions →`}),n.sessions.length===0?(0,U.jsx)(`div`,{className:`muted`,children:`No sessions for this window.`}):n.sessions.map((e,t)=>(0,U.jsxs)(`button`,{"data-testid":`drill-session-${t}`,className:`drill-session-row`,onClick:()=>H({type:`OPEN_MODAL`,kind:`session`,sessionId:e.session_id}),children:[(0,U.jsx)(`span`,{className:`started`,children:A.datetimeShort(e.last_activity_at,o)}),(0,U.jsx)(`span`,{className:`chip ${dn(e.primary_model)}`,children:e.primary_model}),(0,U.jsx)(`span`,{className:`cost ${fn(e.cost_usd)}`,children:A.usd2(e.cost_usd)})]},e.session_id)),(0,U.jsxs)(`div`,{className:`drill-session-footer`,children:[u>0&&(0,U.jsxs)(`span`,{className:`muted`,children:[`+`,u,` more`]}),(0,U.jsx)(`button`,{type:`button`,"data-testid":`drill-show-in-sessions`,className:`drill-show-in-sessions`,onClick:()=>{H({type:`SET_FILTER`,text:n.key}),H({type:`CLOSE_MODAL`})},children:`Show in Sessions →`})]})]})]})]})}var uc=(e,t)=>e<t?-1:+(e>t),dc=[{id:`project`,label:`Project`,defaultDirection:`asc`,compare:(e,t)=>uc(e.key,t.key),className:`project`},{id:`sessions`,label:`Sessions`,defaultDirection:`desc`,numeric:!0,compare:(e,t)=>e.sessionsCount-t.sessionsCount},{id:`first_seen`,label:`First seen`,defaultDirection:`asc`,nullKey:e=>e.firstSeenAt,compare:(e,t)=>uc(e.firstSeenAt,t.firstSeenAt),className:`started`},{id:`last_seen`,label:`Last seen`,defaultDirection:`desc`,nullKey:e=>e.lastSeenAt,compare:(e,t)=>uc(e.lastSeenAt,t.lastSeenAt),className:`started`},{id:`cost`,label:`Cost`,defaultDirection:`desc`,numeric:!0,compare:(e,t)=>e.windowCost-t.windowCost},{id:`used_pct`,label:`Used %`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.windowPct,compare:(e,t)=>e.windowPct-t.windowPct},{id:`share_of_window`,label:`% of week`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.shareOfWindow,compare:(e,t)=>e.shareOfWindow-t.shareOfWindow}],fc=[{column:`cost`,direction:`desc`,label:`cost`,arrow:`↓`},{column:`sessions`,direction:`desc`,label:`sessions`,arrow:`↓`},{column:`used_pct`,direction:`desc`,label:`used`,arrow:`↓`},{column:`share_of_window`,direction:`desc`,label:`share`,arrow:`↓`},{column:`first_seen`,direction:`asc`,label:`first`,arrow:`↑`},{column:`last_seen`,direction:`desc`,label:`last`,arrow:`↓`},{column:`project`,direction:`asc`,label:`project`,arrow:`↑`}],pc=[1,4,8,12];function mc(){let e=W(),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=(0,_.useSyncExternalStore)(V,()=>B().openProjectKey),i=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsWindowWeeks),a=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsTrendYMode),o=(0,_.useSyncExternalStore)(V,()=>B().prefs.projectsSortOverride),[s,c]=(0,_.useState)(r??null),[l,u]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(r){c(r);return}s||c(e?.projects?.current_week?.rows?.[0]?.key??null)},[r,e?.projects?.current_week?.rows]),(0,_.useEffect)(()=>{r||s&&((e?.projects?.trend?.projects??[]).some(e=>e.key===s)||c(e?.projects?.current_week?.rows?.[0]?.key??null))},[r,s,e?.projects?.trend?.projects,e?.projects?.current_week?.rows]);let d=e?.projects?.trend??null,f=i,p=d?.window_weeks??0,m=(e,t)=>{H({type:`SAVE_PREFS`,patch:{[e]:t}})},h=e=>{c(t=>t===e?null:e)},g=(d?.projects??[]).map(e=>{let t=e.weekly_cost.slice(-i),n=e.weekly_pct.slice(-i),r=e.sessions_per_week.slice(-i),a=e.first_seen_per_week.slice(-i),o=e.last_seen_per_week.slice(-i),s=t.reduce((e,t)=>e+t,0),c=n.reduce((e,t)=>t==null?e:(e??0)+t,null),l=r.reduce((e,t)=>e+t,0),u=a.reduce((e,t)=>t==null?e:e==null||t<e?t:e,null),d=o.reduce((e,t)=>t==null?e:e==null||t>e?t:e,null);return{key:e.key,sessionsCount:l,firstSeenAt:u,lastSeenAt:d,windowCost:s,windowPct:c,shareOfWindow:null}}),v=g.reduce((e,t)=>e+t.windowCost,0);for(let e of g)e.shareOfWindow=v>0?e.windowCost/v*100:null;let y=o?se(g,dc,o):se(g,dc,{column:`cost`,direction:`desc`}),b=y.filter(e=>e.windowCost>0).slice(0,10),x=y.length-b.length,S=l?y:b,C=x>0,w=cn(),T=(()=>{if(!o)return 0;let e=fc.findIndex(e=>e.column===o.column&&e.direction===o.direction);return e===-1?0:e})(),E=()=>{let e=fc[(T+1)%fc.length];H({type:`SET_TABLE_SORT`,table:`projects`,override:{column:e.column,direction:e.direction}})},D=fc[T],O=()=>B().shareModal===null&&B().composerModal===null;return Ht([{key:`1`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,1)},{key:`4`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,4)},{key:`8`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,8)},{key:`0`,scope:`modal`,when:O,action:()=>m(`projectsWindowWeeks`,12)},{key:`s`,scope:`modal`,when:O,action:()=>m(`projectsTrendYMode`,a===`share`?`absolute`:`share`)},{key:`ArrowUp`,scope:`modal`,when:O,action:()=>{if(S.length===0)return;let e=S.findIndex(e=>e.key===s);c(S[e<=0?S.length-1:e-1].key)}},{key:`ArrowDown`,scope:`modal`,when:O,action:()=>{if(S.length===0)return;let e=S.findIndex(e=>e.key===s);c(S[e===-1||e===S.length-1?0:e+1].key)}},{key:`Enter`,scope:`modal`,when:O,action:()=>{s?c(null):S.length>0&&c(S[0].key)}}]),(0,U.jsx)(ss,{title:`Projects · last ${i}w`,accentClass:`accent-magenta`,headerExtras:(0,U.jsx)(qt,{panel:`projects`,panelLabel:`Projects`,triggerId:`projects-modal`,dataTestId:`share-icon-projects-modal`,onClick:()=>H(R(`projects`,`projects-modal`,{windowWeeks:i}))}),children:(0,U.jsxs)(`div`,{className:`projects-modal-body`,children:[(0,U.jsxs)(`div`,{className:`projects-controls`,role:`radiogroup`,"aria-label":`Window`,children:[pc.map(e=>(0,U.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":i===e,className:`pill ${i===e?`on`:``}`,onClick:()=>m(`projectsWindowWeeks`,e),children:[e,`w`]},`window-${e}`)),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`|`}),(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":a===`share`,className:`pill ${a===`share`?`on`:``}`,onClick:()=>m(`projectsTrendYMode`,`share`),children:`share %`}),(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":a===`absolute`,className:`pill ${a===`absolute`?`on`:``}`,onClick:()=>m(`projectsTrendYMode`,`absolute`),children:`$ absolute`})]}),p>0&&p<f&&(0,U.jsxs)(`div`,{className:`projects-notice`,children:[`Showing `,p,` week`,p===1?``:`s`,` (need more history for the full window).`]}),d?(0,U.jsx)(sc,{trend:d,yMode:a,windowWeeks:i,onProjectSelect:e=>c(e)}):(0,U.jsx)(`div`,{className:`panel-empty`,children:`Projects trend unavailable.`}),w&&(0,U.jsxs)(`button`,{type:`button`,className:`projects-mobile-sort`,"data-testid":`projects-mobile-sort`,onClick:E,"aria-label":`Cycle sort column`,children:[`Sort: `,D.label,` `,D.arrow]}),(0,U.jsxs)(`table`,{className:`projects-table`,children:[(0,U.jsx)(rn,{columns:dc,override:o,onChange:e=>H({type:`SET_TABLE_SORT`,table:`projects`,override:e}),accentVar:`--accent-magenta`}),(0,U.jsx)(`tbody`,{children:S.map(e=>(0,U.jsxs)(_.Fragment,{children:[(0,U.jsxs)(`tr`,{"data-testid":`projects-table-row`,"data-cost":e.windowCost,"data-sessions":e.sessionsCount,"aria-expanded":s===e.key,className:s===e.key?`selected`:``,onClick:()=>h(e.key),children:[(0,U.jsx)(`td`,{className:`project`,children:e.key}),(0,U.jsx)(`td`,{children:e.sessionsCount}),(0,U.jsx)(`td`,{className:`started first-seen`,children:A.dateShort(e.firstSeenAt,n)??`—`}),(0,U.jsx)(`td`,{className:`started last-seen`,children:A.dateShort(e.lastSeenAt,n)??`—`}),(0,U.jsx)(`td`,{className:fn(e.windowCost),children:A.usd2(e.windowCost)}),(0,U.jsx)(`td`,{children:e.windowPct==null?`—`:A.pct0(e.windowPct)}),(0,U.jsx)(`td`,{children:e.shareOfWindow==null?`—`:A.pct0(e.shareOfWindow)})]}),w&&s===e.key&&(0,U.jsx)(`tr`,{className:`projects-drill-row`,"aria-hidden":`false`,children:(0,U.jsx)(`td`,{colSpan:7,children:(0,U.jsx)(lc,{projectKey:e.key,windowWeeks:i})})})]},e.key))})]}),C&&(0,U.jsx)(`button`,{type:`button`,className:`projects-table-toggle`,"data-testid":`projects-table-toggle`,"aria-expanded":l,onClick:()=>u(e=>!e),children:l?`Show top 10 active`:`Show all ${y.length} projects (+${x})`}),!w&&s&&(0,U.jsx)(lc,{projectKey:s,windowWeeks:i}),(0,U.jsxs)(`div`,{className:`projects-modal-footer-hint`,"data-testid":`projects-modal-footer-hint`,"aria-live":`off`,children:[(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`1`}),`/`,(0,U.jsx)(`kbd`,{children:`4`}),`/`,(0,U.jsx)(`kbd`,{children:`8`}),`/`,(0,U.jsx)(`kbd`,{children:`0`}),` window`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`↑↓`}),` row`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`Enter`}),` drill`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`s`}),` share/$`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`kbd`,{children:`Esc`}),` close`]}),(0,U.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,U.jsx)(vt,{})]})]})})}function hc({cr:e}){let t=e.today.baseline_daily_row_count<5,n=e.today.anomaly_triggered&&!t,r;r=t?{text:`~ Building baseline · ${e.today.baseline_daily_row_count}/5 days`,cls:`thin`}:n?{text:`⚠ Anomaly`,cls:``}:{text:`✓ Healthy`,cls:`ok`};let i=e.today.baseline_median_percent,a=e.today.delta_pp,o;if(a===null)o=`—`;else{let e=A.pctFloor(Math.abs(a));o=`${a<0?`−`:`+`}${e}pp`}return(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-spotlight`,children:[`Today's spotlight`,(0,U.jsxs)(`span`,{className:`meta`,children:[e.today.date,` · `,e.days.length,` days observed`]})]}),(0,U.jsxs)(`div`,{className:`crm-spotlight${n?` anom`:``}`,children:[(0,U.jsxs)(`div`,{className:`crm-spotlight-row`,children:[(0,U.jsx)(`span`,{className:`pill${r.cls?` `+r.cls:``}`,children:r.text}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Cache hit`}),` `,(0,U.jsxs)(`strong`,{children:[A.pctFloor(e.today.cache_hit_percent),`%`]})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`14d median`}),` `,(0,U.jsx)(`strong`,{children:i===null?`—`:`${A.pctFloor(i)}%`})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Δ`}),` `,(0,U.jsx)(`strong`,{children:o})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Net`}),` `,(0,U.jsx)(`strong`,{children:A.usdSigned(e.today.net_usd)})]}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`span`,{className:`k`,children:`Saved / Wasted`}),` `,(0,U.jsxs)(`strong`,{children:[`$`,e.today.saved_usd.toFixed(2),` / $`,e.today.wasted_usd.toFixed(2)]})]})]}),n&&e.today.anomaly_reasons.length>0&&(0,U.jsxs)(`div`,{className:`reasons`,children:[`Reasons:`,` `,e.today.anomaly_reasons.map((e,t)=>(0,U.jsxs)(`span`,{children:[t>0&&` · `,(0,U.jsx)(`code`,{children:e})]},e)),` | `,`thresholds: `,e.anomaly_threshold_pp,`pp drop, net < 0`]})]})]})}function gc(e,t=28){if(e.length<=t)return e;let n=e.split(`/`).filter(Boolean);if(n.length<=2)return e;let r=`/`+n[0],i=`${r}/…/${n.slice(-2).join(`/`)}`;return i.length<=t||(i=`${r}/…/${n[n.length-1]}`,i.length<=t)?i:`…/${n[n.length-1]}`}function q({kind:e,rows:t}){let n=e===`projects`?`bd-projects`:`bd-models`,r=e===`projects`?`By project`:`By model`,i=e===`projects`?`No project activity in this window`:`No model activity in this window`,a=e===`projects`;return(0,U.jsxs)(`div`,{className:`crm-bd-card ${n}`,"data-bd-kind":e,children:[(0,U.jsx)(`div`,{className:`crm-bd-head`,children:r}),t.length===0?(0,U.jsx)(`div`,{className:`empty`,children:i}):(0,U.jsx)(`table`,{children:(0,U.jsx)(`tbody`,{children:t.map(e=>{let t=a?gc(e.key):e.key,n=t!==e.key;return(0,U.jsxs)(`tr`,{"data-testid":`crm-bd-row`,"data-bd-key":e.key,children:[(0,U.jsx)(`td`,{className:`bd-key`,title:n?e.key:void 0,children:t}),(0,U.jsxs)(`td`,{children:[A.pctFloor(e.cache_hit_percent),`%`]}),(0,U.jsx)(`td`,{className:e.net_usd>=0?`net-pos`:`net-neg`,children:A.usdSigned(e.net_usd)})]},e.key)})})})]})}function _c({current_threshold_pp:e,onClose:t}){let[n,r]=(0,_.useState)(String(e)),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),u=(0,_.useRef)(null);(0,_.useEffect)(()=>{function e(e){let n=e.target;n&&n.closest(`[data-cr-settings-toggle]`)||u.current&&!u.current.contains(e.target)&&t()}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t]),(0,_.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopPropagation(),t())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[t]);async function d(){l(!1);let e=n.trim(),t=/^-?\d+$/.test(e)?parseInt(e,10):NaN;if(!Number.isInteger(t)||t<1||t>100){a(`Must be an integer between 1 and 100`);return}s(!0),a(null);try{let e=await fetch(`/api/settings`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cache_report:{anomaly_threshold_pp:t}})});if(e.ok)l(!0),setTimeout(()=>l(!1),1500);else{let t=await e.json().catch(()=>({}));a(typeof t.error==`string`?t.error:`HTTP ${e.status}`)}}catch(e){a(String(e))}finally{s(!1)}}return(0,U.jsxs)(`div`,{ref:u,className:`crm-settings-popover`,role:`dialog`,"aria-label":`Cache Report settings`,children:[(0,U.jsx)(`h4`,{children:`Cache Report settings`}),(0,U.jsx)(`label`,{htmlFor:`cr-threshold`,children:`Anomaly threshold (pp)`}),(0,U.jsx)(`input`,{id:`cr-threshold`,type:`number`,inputMode:`numeric`,min:1,max:100,value:n,onChange:e=>{r(e.target.value),a(null),l(!1)},className:i?`invalid`:``}),i&&(0,U.jsx)(`div`,{className:`err`,children:i}),c&&(0,U.jsx)(`div`,{className:`saved`,children:`Saved · next sync will re-evaluate`}),(0,U.jsxs)(`div`,{className:`actions`,children:[(0,U.jsx)(`button`,{onClick:t,type:`button`,children:`Close`}),(0,U.jsx)(`button`,{className:`primary`,onClick:d,disabled:o,type:`button`,children:o?`Saving…`:`Save`})]})]})}function vc(){let e=W()?.cache_report,[t,n]=(0,_.useState)(!1);if(!e)return(0,U.jsx)(ss,{title:`Cache Report`,accentClass:`accent-teal`,children:(0,U.jsx)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:`Loading…`})});if(e.is_empty)return(0,U.jsx)(ss,{title:`Cache Report`,accentClass:`accent-teal`,children:(0,U.jsxs)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:[`No Claude activity in the last `,e.window_days,` days.`]})});let r=(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`span`,{className:`sub`,style:{marginRight:12,color:`var(--text-dim)`},children:[`Last `,e.window_days,` days · `,e.anomaly_window_days,`d baseline · Claude only`]}),(0,U.jsx)(`button`,{type:`button`,"aria-label":`Cache Report settings`,"data-cr-settings-toggle":!0,onClick:e=>{e.stopPropagation(),n(e=>!e)},style:{background:`transparent`,border:0,color:`var(--text-dim)`,cursor:`pointer`,fontSize:18,padding:`0 8px`},children:`⚙`})]}),i=e.today.baseline_daily_row_count<5,a=e.today.anomaly_triggered&&!i,o=a?`var(--accent-amber)`:`var(--accent-green)`,s=a?`accent-amber`:`accent-teal`,c=Math.round(e.fourteen_day_efficiency_ratio*100);return(0,U.jsxs)(ss,{title:`Cache Report`,accentClass:s,headerExtras:r,children:[t&&(0,U.jsx)(_c,{current_threshold_pp:e.anomaly_threshold_pp,onClose:()=>n(!1)}),(0,U.jsx)(hc,{cr:e}),(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-timeline`,children:[`Cache hit % — `,e.window_days,`-day timeline`,(0,U.jsxs)(`span`,{className:`meta`,children:[`band = `,e.anomaly_window_days,`d median ±`,5,`pp`]})]}),(0,U.jsx)(`div`,{className:`crm-chart-frame timeline`,children:(0,U.jsx)(Rn,{days:e.days,baseline_median_percent:e.today.baseline_median_percent,today_marker_color:o,size:`large`})})]}),(0,U.jsx)(Bn,{days:e.days,size:`large`}),(0,U.jsxs)(`div`,{className:`crm-counterfactual`,children:[`Without caching, you'd have paid`,` `,(0,U.jsxs)(`strong`,{children:[`+$`,e.fourteen_day_counterfactual_usd.toFixed(2),` more`]}),` `,`over the last `,e.window_days,` days · cache efficiency`,` `,(0,U.jsxs)(`span`,{title:`saved / (saved + |wasted|) = ${c}%`,children:[c,`%`]})]}),(0,U.jsxs)(`div`,{className:`crm-section`,children:[(0,U.jsxs)(`div`,{className:`crm-section-head crm-sh-table`,children:[`Daily rows · `,e.window_days,` days`,(0,U.jsxs)(`span`,{className:`meta`,children:[e.days.length,` days observed`]})]}),(0,U.jsxs)(`table`,{className:`ch-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{className:`c-date`,children:`Date`}),(0,U.jsx)(`th`,{className:`c-hit num`,children:`Cache %`}),(0,U.jsx)(`th`,{className:`c-tokens num`,children:`Tok In`}),(0,U.jsx)(`th`,{className:`c-tokens num`,children:`Tok Out`}),(0,U.jsx)(`th`,{className:`c-saved num`,children:`Saved`}),(0,U.jsx)(`th`,{className:`c-wasted num`,children:`Wasted`}),(0,U.jsx)(`th`,{className:`c-net num`,children:`Net`}),(0,U.jsx)(`th`,{className:`c-flag num`,children:`Flag`})]})}),(0,U.jsx)(`tbody`,{children:e.days.map(t=>{let n=t.date===e.today.date,r=e.today.baseline_median_percent!==null,i=r&&e.today.baseline_median_percent!==null&&t.cache_hit_percent<e.today.baseline_median_percent-5,a=t.net_usd<0;return(0,U.jsxs)(`tr`,{className:n?`cur`:``,"data-testid":`crm-daily-row`,"data-date":t.date,children:[(0,U.jsx)(`td`,{children:t.date}),(0,U.jsxs)(`td`,{className:`num ${r?i?`hit-bad`:`hit-good`:``}`.trim(),children:[A.pctFloor(t.cache_hit_percent),`%`]}),(0,U.jsx)(`td`,{className:`num`,children:A.compact(t.input_tokens,{upper:!0})}),(0,U.jsx)(`td`,{className:`num`,children:A.compact(t.output_tokens,{upper:!0})}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(t.saved_usd)}),(0,U.jsx)(`td`,{className:`num`,children:A.usd2(t.wasted_usd)}),(0,U.jsx)(`td`,{className:`num ${a?`net-neg`:`net-pos`}`,children:A.usdSigned(t.net_usd)}),(0,U.jsx)(`td`,{className:`num ${t.anomaly_triggered?`flag-warn`:`flag-ok`}`,children:t.anomaly_triggered?`⚠`:`✓`})]},t.date)})})]})]}),(0,U.jsx)(`div`,{className:`crm-section`,children:(0,U.jsxs)(`div`,{className:`crm-breakdowns`,children:[(0,U.jsx)(q,{kind:`projects`,rows:e.by_project}),(0,U.jsx)(q,{kind:`models`,rows:e.by_model})]})})]})}var yc=100;function bc({alert:e,ctx:t}){if(e.axis===`weekly`){let n=e.context.week_start_date?A.weekStart(e.context.week_start_date,t):null,r=e.context.dollars_per_percent;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--weekly`,children:[n?`Week of ${n}`:`Week —`,r!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[`$`,r.toFixed(2),`/1%`]})]})]})}if(e.axis===`budget`){let n=Mn(e.context.period),r=e.context.period_start_at??e.context.week_start_at,i=r?A.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`codex_budget`){let n=Mn(e.context.period),r=e.context.period_start_at,i=r?A.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--codex_budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`project_budget`){let t=e.context.project??`(project)`,n=e.context.consumption_pct;return(0,U.jsxs)(`span`,{className:`alert-context alert-context--project_budget`,children:[t,n!=null&&(0,U.jsxs)(U.Fragment,{children:[` · `,(0,U.jsxs)(`span`,{className:`num`,children:[Math.round(n),`% of budget`]})]})]})}return e.axis===`projected`?(0,U.jsx)(`span`,{className:`alert-context alert-context--projected`,children:Pn(e)??`Projected —`}):(0,U.jsxs)(`span`,{className:`alert-context alert-context--five-hour`,children:[`Block `,e.context.block_start_at?A.timeOnly(e.context.block_start_at,t):`—`]})}function xc({alert:e}){if(e.axis===`projected`)return(0,U.jsx)(`span`,{className:`num`,children:`—`});let t;return t=e.axis===`weekly`?e.context.cumulative_cost_usd:e.axis===`budget`||e.axis===`project_budget`||e.axis===`codex_budget`?e.context.spent_usd:e.context.block_cost_usd,(0,U.jsx)(`span`,{className:`num`,children:A.usd2(t??null)})}function Sc(){let e=(0,_.useSyncExternalStore)(V,()=>B().alerts),t=Wt(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e.slice(0,yc);return r.length===0?(0,U.jsx)(ss,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,U.jsx)(`div`,{className:`panel-empty`,children:`No alerts yet. Alerts appear when usage crosses 90% or 95%.`})}):(0,U.jsx)(ss,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,U.jsxs)(`div`,{className:`alerts-modal-body`,children:[(0,U.jsxs)(`table`,{className:`alerts-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{scope:`col`,children:`%`}),(0,U.jsx)(`th`,{scope:`col`,children:`Axis`}),(0,U.jsx)(`th`,{scope:`col`,children:`Cost`}),(0,U.jsx)(`th`,{scope:`col`,children:`Context`}),(0,U.jsx)(`th`,{scope:`col`,children:`Alerted`})]})}),(0,U.jsx)(`tbody`,{children:r.map(e=>{let t=Nn(e);return(0,U.jsxs)(`tr`,{className:`alert-modal-row`,children:[(0,U.jsxs)(`td`,{className:`alert-threshold severity-${t} ${t} num`,children:[e.threshold,`%`]}),(0,U.jsx)(`td`,{children:(0,U.jsx)(`span`,{className:`chip chip--${e.axis}`,children:An[e.axis]})}),(0,U.jsx)(`td`,{className:`num`,children:(0,U.jsx)(xc,{alert:e})}),(0,U.jsx)(`td`,{children:(0,U.jsx)(bc,{alert:e,ctx:n})}),(0,U.jsx)(`td`,{className:`alert-when`,children:A.relativeOrAbsolute(e.alerted_at,n)})]},e.id)})})]}),e.length>yc&&(0,U.jsxs)(`div`,{className:`alerts-modal-foot`,children:[`Showing `,yc,` of `,e.length,` most recent`]})]})})}function Cc(){let e=(0,_.useSyncExternalStore)(V,()=>B().openModal);if(!e)return null;switch(e){case`current-week`:return(0,U.jsx)(ms,{});case`forecast`:return(0,U.jsx)(bs,{});case`trend`:return(0,U.jsx)(ks,{});case`session`:return(0,U.jsx)(Ms,{});case`weekly`:return(0,U.jsx)(zs,{});case`monthly`:return(0,U.jsx)(Bs,{});case`block`:return(0,U.jsx)(Xs,{});case`daily`:return(0,U.jsx)(ec,{});case`projects`:return(0,U.jsx)(mc,{});case`alerts`:return(0,U.jsx)(Sc,{});case`cache-report`:return(0,U.jsx)(vc,{})}}var wc=class extends Error{code;constructor(e,t,n,r){super(n),this.status=e,this.field=t,this.code=r}};async function Tc(e){if(!e.ok){let t={};try{t=await e.json()}catch{}throw new wc(e.status,t.field,t.error??`HTTP ${e.status}`,t.code)}return e.json()}async function Ec(e,t){return Tc(await fetch(`/api/share/templates?panel=${encodeURIComponent(e)}`,{signal:t?.signal}))}async function Dc(e,t){return Tc(await fetch(`/api/share/render`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}var Oc=[{id:`recap`,label:`Recap`,placeholderDescription:`Text + tiny chart`},{id:`visual`,label:`Visual`,placeholderDescription:`Coming in M2`},{id:`detail`,label:`Detail`,placeholderDescription:`Coming in M2`}];function kc(e){return e.endsWith(`-recap`)?`recap`:e.endsWith(`-visual`)?`visual`:e.endsWith(`-detail`)?`detail`:null}function Ac({panel:e,templates:t,error:n,selectedTemplateId:r,onSelect:i}){if(n)return(0,U.jsx)(`div`,{className:`share-gallery-error`,role:`alert`,children:n});let a={};for(let e of t??[]){let t=kc(e.id);t&&(a[t]=e)}return(0,U.jsx)(`div`,{className:`share-gallery`,role:`radiogroup`,"aria-label":`Report template`,children:Oc.map(e=>{let n=a[e.id];if(t==null)return(0,U.jsxs)(`div`,{className:`share-tile share-tile-skeleton`,"aria-hidden":`true`,children:[(0,U.jsx)(`div`,{className:`share-tile-skeleton-bar`}),(0,U.jsx)(`div`,{className:`share-tile-skeleton-bar short`})]},e.id);if(!n)return(0,U.jsxs)(`button`,{type:`button`,className:`share-tile share-tile-disabled`,disabled:!0,"aria-disabled":`true`,role:`radio`,"aria-checked":`false`,title:`${e.label} — ${e.placeholderDescription}`,children:[(0,U.jsx)(`div`,{className:`share-tile-label`,children:e.label}),(0,U.jsx)(`div`,{className:`share-tile-desc`,children:e.placeholderDescription})]},e.id);let o=n.id===r;return(0,U.jsxs)(`button`,{type:`button`,className:`share-tile`+(o?` share-tile-selected`:``),role:`radio`,"aria-checked":o,"data-template-id":n.id,onClick:()=>i(n.id),children:[(0,U.jsx)(`div`,{className:`share-tile-label`,children:n.label}),(0,U.jsx)(`div`,{className:`share-tile-desc`,children:n.description})]},e.id)})})}function jc({options:e,onChange:t}){let n=n=>t({...e,...n}),r=n=>t({...e,period:{...e.period,...n}}),i=e=>{if(e===``){n({top_n:null});return}let t=Number.parseInt(e,10);Number.isNaN(t)||n({top_n:Math.max(1,t)})};return(0,U.jsxs)(`div`,{className:`share-knobs`,children:[(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`label`,{htmlFor:`share-knob-period`,children:`Period`}),(0,U.jsxs)(`select`,{id:`share-knob-period`,value:e.period.kind,onChange:e=>r({kind:e.target.value}),children:[(0,U.jsx)(`option`,{value:`current`,children:`This week`}),(0,U.jsx)(`option`,{value:`previous`,children:`Previous week`}),(0,U.jsx)(`option`,{value:`custom`,children:`Custom`})]}),e.period.kind===`custom`?(0,U.jsxs)(`div`,{className:`share-knob-period-custom`,children:[(0,U.jsxs)(`label`,{className:`share-knob-sublabel`,children:[(0,U.jsx)(`span`,{children:`Start`}),(0,U.jsx)(`input`,{type:`date`,value:e.period.start?.slice(0,10)??``,onChange:e=>r({start:e.target.value}),"aria-label":`Custom period start date`})]}),(0,U.jsxs)(`label`,{className:`share-knob-sublabel`,children:[(0,U.jsx)(`span`,{children:`End`}),(0,U.jsx)(`input`,{type:`date`,value:e.period.end?.slice(0,10)??``,onChange:e=>r({end:e.target.value}),"aria-label":`Custom period end date`})]})]}):null]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`span`,{className:`share-knob-label`,children:`Theme`}),(0,U.jsxs)(`div`,{className:`share-knob-radiogroup`,role:`radiogroup`,"aria-label":`Theme`,children:[(0,U.jsxs)(`label`,{className:`share-knob-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-theme`,value:`light`,checked:e.theme===`light`,onChange:()=>n({theme:`light`})}),(0,U.jsx)(`span`,{children:`Light`})]}),(0,U.jsxs)(`label`,{className:`share-knob-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-theme`,value:`dark`,checked:e.theme===`dark`,onChange:()=>n({theme:`dark`})}),(0,U.jsx)(`span`,{children:`Dark`})]})]})]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`label`,{htmlFor:`share-knob-topn`,children:`Top-N`}),(0,U.jsx)(`input`,{id:`share-knob-topn`,type:`number`,min:1,step:1,inputMode:`numeric`,value:e.top_n??``,onChange:e=>i(e.target.value),"aria-label":`Top-N`})]}),(0,U.jsxs)(`div`,{className:`share-knob`,children:[(0,U.jsx)(`span`,{className:`share-knob-label`,children:`Projects`}),(0,U.jsx)(`button`,{type:`button`,className:`share-knob-allowlist-stub`,disabled:!0,"aria-disabled":`true`,title:`Project allowlist — coming in M3+`,children:`All projects`})]}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:e.show_chart,onChange:e=>n({show_chart:e.target.checked}),"aria-label":`Include chart in export`}),(0,U.jsx)(`span`,{children:`Show chart`})]})}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:e.show_table,onChange:e=>n({show_table:e.target.checked}),"aria-label":`Include table in export`}),(0,U.jsx)(`span`,{children:`Show table`})]})}),(0,U.jsx)(`div`,{className:`share-knob`,children:(0,U.jsxs)(`label`,{className:`share-knob-checkbox`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:!e.reveal_projects,onChange:e=>n({reveal_projects:!e.target.checked}),"aria-label":`Anonymize project names on export`}),(0,U.jsx)(`span`,{children:`Anon on export`})]})})]})}var Mc=200,Nc={status:`idle`,body:``,contentType:``,errorMessage:null,errorField:null};function Pc({panel:e,templateId:t,options:n}){let[r,i]=(0,_.useState)(Nc),a=(0,_.useRef)(null),o=(0,_.useRef)(0);return(0,_.useEffect)(()=>{if(!t){i(Nc);return}i(e=>({...e,status:`loading`}));let r=++o.current,s=setTimeout(()=>{a.current?.abort();let s=new AbortController;a.current=s,Dc({panel:e,template_id:t,options:{...n,reveal_projects:!0}},{signal:s.signal}).then(e=>{r===o.current&&i({status:`ready`,body:e.body,contentType:e.content_type,errorMessage:null,errorField:null})}).catch(e=>{if(r===o.current&&!(e&&typeof e==`object`&&e.name===`AbortError`)){if(e instanceof wc){i({status:`error`,body:``,contentType:``,errorMessage:e.message??`HTTP ${e.status}`,errorField:e.field??null});return}i({status:`error`,body:``,contentType:``,errorMessage:e.message??`Unknown error`,errorField:null})}})},Mc);return()=>{clearTimeout(s)}},[e,t,n]),(0,_.useEffect)(()=>()=>{a.current?.abort()},[]),t?r.status===`error`?(0,U.jsxs)(`div`,{className:`share-preview share-preview-error`,role:`alert`,children:[(0,U.jsx)(`div`,{className:`share-preview-error-title`,children:`Preview failed`}),(0,U.jsxs)(`div`,{className:`share-preview-error-message`,children:[r.errorMessage,r.errorField?(0,U.jsxs)(`span`,{className:`share-preview-error-field`,children:[` `,`(field: `,r.errorField,`)`]}):null]})]}):r.status===`loading`||r.status===`idle`?(0,U.jsx)(`div`,{className:`share-preview share-preview-loading`,"aria-busy":`true`,children:`Rendering preview…`}):n.format===`md`?(0,U.jsx)(`pre`,{className:`share-preview share-preview-md`,"aria-label":`Markdown preview`,children:r.body}):(0,U.jsx)(`iframe`,{className:`share-preview share-preview-iframe`,title:`Report preview (decorative)`,tabIndex:-1,sandbox:`allow-same-origin`,srcDoc:r.body}):(0,U.jsx)(`div`,{className:`share-preview share-preview-empty`,children:`Select a template to preview.`})}var Fc={"current-week":`Current week`,trend:`Trend`,weekly:`Weekly`,daily:`Daily`,monthly:`Monthly`,blocks:`5-hour blocks`,forecast:`Forecast`,sessions:`Sessions`,projects:`Projects`};function Ic(e){return Fc[e]}function Lc(e){switch(e){case`md`:return`md`;case`html`:return`html`;case`svg`:return`svg`}}async function Rc(e){if(!e.ok){let t={};try{t=await e.json()}catch{}throw new wc(e.status,t.field,t.error??`HTTP ${e.status}`)}return e.json()}async function zc(e){return Rc(await fetch(`/api/share/presets`,{signal:e?.signal}))}async function Bc(e,t){return Rc(await fetch(`/api/share/presets`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}async function Vc(e,t,n){let r=await fetch(`/api/share/presets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`,signal:n?.signal});if(!r.ok){let e={};try{e=await r.json()}catch{}throw new wc(r.status,void 0,e.error??`HTTP ${r.status}`)}}async function Hc(e){return Rc(await fetch(`/api/share/history`,{signal:e?.signal}))}async function Uc(e,t){return Rc(await fetch(`/api/share/history`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal}))}function Wc({panel:e,templateId:t,options:n,onSaved:r,onCancel:i}){let[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(null);async function d(){let i=a.trim();if(!i){u(`Name is required`);return}if(i.length>64){u(`Name must be 64 characters or fewer`);return}if(i.includes(`/`)){u(`Name cannot contain '/'`);return}c(!0),u(null);try{await Bc({panel:e,name:i,template_id:t,options:n}),H({type:`SHOW_STATUS_TOAST`,text:`Saved preset "${i}"`}),r()}catch(e){u((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Save failed`)}finally{c(!1)}}return(0,U.jsxs)(`div`,{className:`share-save-popover`,role:`dialog`,"aria-label":`Save preset`,children:[(0,U.jsxs)(`label`,{className:`share-save-label`,children:[`Preset name`,(0,U.jsx)(`input`,{type:`text`,className:`share-save-input`,autoFocus:!0,value:a,maxLength:64,disabled:s,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),d()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i())}})]}),l?(0,U.jsx)(`div`,{className:`share-save-error`,role:`alert`,children:l}):null,(0,U.jsxs)(`div`,{className:`share-save-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:i,disabled:s,children:`Cancel`}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>void d(),disabled:s,children:s?`Saving…`:`Save`})]})]})}async function Gc(e,t,n){let r=new Blob([e],{type:`image/svg+xml`}),i=URL.createObjectURL(r);try{let e=new Image;e.src=i,await e.decode();let r=document.createElement(`canvas`);r.width=e.naturalWidth*t,r.height=e.naturalHeight*t;let a=r.getContext(`2d`);if(!a)throw Error(`Could not acquire 2D canvas context`);a.fillStyle=n,a.fillRect(0,0,r.width,r.height),a.scale(t,t),a.drawImage(e,0,0);let o=await new Promise(e=>{r.toBlob(t=>e(t),`image/png`)});if(o)return o;let s=r.toDataURL(`image/png`);return(await fetch(s)).blob()}finally{URL.revokeObjectURL(i)}}function J(e){let t=document.createElement(`iframe`);t.setAttribute(`aria-hidden`,`true`),t.style.cssText=`position:fixed;right:0;bottom:0;width:0;height:0;border:0`,document.body.appendChild(t);let n=t.contentDocument;if(!n)throw Error(`iframe contentDocument unavailable`);n.open(),n.write(e),n.close();try{t.contentWindow?.focus(),t.contentWindow?.print()}catch{let t=window.open(``,`_blank`,`noopener,noreferrer`);t&&(t.document.open(),t.document.write(e),t.document.close())}setTimeout(()=>t.remove(),1e3)}function Kc(e){Uc({panel:e.panel,template_id:e.template_id,options:e.options,format:e.options.format,destination:e.destination}).catch(()=>{})}function qc(e){return e===`light`?`#ffffff`:`#0f172a`}function Jc(e,t){return`cctally-${e}-${new Date().toISOString().slice(0,10).replaceAll(`-`,``)}.${Lc(t)}`}function Yc(e){switch(e){case`md`:return`text/markdown;charset=utf-8`;case`html`:return`text/html;charset=utf-8`;case`svg`:return`image/svg+xml;charset=utf-8`}}function Xc(e,t){let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.style.display=`none`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),0)}function Zc({panel:e,templateId:t,options:n,onOptionsChange:r}){let[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(!1),u=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{u.current!=null&&clearTimeout(u.current)},[]);let[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!d)return;function e(e){let t=p.current;t&&(t.contains(e.target)||f(!1))}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[d]),(0,_.useEffect)(()=>{s(null)},[n.format,t]);let m=t==null||i!=null,h=e=>H({type:`SHOW_STATUS_TOAST`,text:e}),g=async()=>{if(!t)throw Error(`no template selected`);return{body:(await Dc({panel:e,template_id:t,options:n})).body,format:n.format}},v=async()=>{if(!(m||!t)){a(`copy`),s(null);try{let{body:r}=await g();if(!navigator.clipboard||typeof navigator.clipboard.writeText!=`function`)throw Error(`Clipboard API unavailable in this browser`);await navigator.clipboard.writeText(r),h(`Copied`),Kc({panel:e,template_id:t,options:n,destination:`copy`})}catch(e){s(`Copy failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},y=async()=>{if(!(m||!t)){a(`download`),s(null);try{let{body:r,format:i}=await g(),a=new Blob([r],{type:Yc(i)});Xc(Jc(e,i),a),h(`Downloaded`),Kc({panel:e,template_id:t,options:n,destination:`download`})}catch(e){s(`Download failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},b=async()=>{if(!(m||!t)){a(`basket`),s(null);try{let r=await Dc({panel:e,template_id:t,options:n}),i=_e({panel:e,template_id:t,options:n,added_at:new Date().toISOString(),data_digest_at_add:r.snapshot.data_digest,kernel_version:r.snapshot.kernel_version,label_hint:Ic(e)});H({type:`BASKET_ADD`,item:i});let a=B().basket;if(a.rejectedReason===`capacity`)return;l(!0),u.current!=null&&clearTimeout(u.current),u.current=setTimeout(()=>l(!1),800),H({type:`SHOW_STATUS_TOAST`,text:`Added ${i.label_hint} to basket (${a.items.length})`})}catch(e){s(`Add to basket failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},x=async()=>{if(!(m||!t)){a(`open`),s(null);try{let{body:r,format:i}=await g(),a=new Blob([r],{type:Yc(i)}),o=URL.createObjectURL(a);window.open(o,`_blank`,`noopener,noreferrer`),Kc({panel:e,template_id:t,options:n,destination:`open`})}catch(e){s(`Open failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},S=async()=>{if(!(!t||n.format!==`svg`||m)){a(`png`),s(null);try{let{body:r}=await g(),i=await Gc(r,2,qc(n.theme));Xc(Jc(e,`svg`).replace(/\.svg$/,`.png`),i),h(`PNG downloaded`),Kc({panel:e,template_id:t,options:n,destination:`png`})}catch(e){s(`PNG export failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},C=async()=>{if(!(!t||n.format!==`html`||m)){a(`print`),s(null);try{let{body:r}=await g();J(r),Kc({panel:e,template_id:t,options:n,destination:`print`})}catch(e){s(`Print failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{a(null)}}},w=n.format===`md`&&!m,T=(n.format===`html`||n.format===`svg`)&&!m,E=n.format===`svg`&&!m,D=n.format===`html`&&!m;return(0,U.jsxs)(`div`,{className:`share-actions`,children:[(0,U.jsxs)(`div`,{className:`share-format-row`,role:`radiogroup`,"aria-label":`Export format`,children:[(0,U.jsx)(`span`,{className:`share-format-label`,children:`Format:`}),[`md`,`html`,`svg`].map(e=>(0,U.jsxs)(`label`,{className:`share-format-radio`,children:[(0,U.jsx)(`input`,{type:`radio`,name:`share-format`,value:e,checked:n.format===e,onChange:()=>r({...n,format:e})}),(0,U.jsx)(`span`,{children:e})]},e))]}),(0,U.jsxs)(`div`,{className:`share-action-row`,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-copy`,onClick:v,disabled:!w,title:n.format===`md`?i===`copy`?`Copying…`:`Copy to clipboard`:`Copy is available for Markdown only`,children:i===`copy`?`Copying…`:`Copy`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-download`,onClick:y,disabled:m,title:i===`download`?`Downloading…`:`Download file`,children:i===`download`?`Downloading…`:`Download`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-open`,onClick:x,disabled:!T,title:n.format===`html`||n.format===`svg`?i===`open`?`Opening…`:`Open in new tab`:`Open is available for HTML/SVG`,children:i===`open`?`Opening…`:`Open`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-png`,onClick:S,disabled:!E,title:n.format===`svg`?i===`png`?`Rasterizing…`:`Download PNG (rasterized from SVG)`:`PNG export — available for SVG format only`,children:i===`png`?`Rasterizing…`:`PNG`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-print`,onClick:C,disabled:!D,title:n.format===`html`?i===`print`?`Opening print dialog…`:`Open the browser print dialog (save as PDF)`:`Print → PDF — available for HTML format only`,children:i===`print`?`Printing…`:`Print → PDF`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-basket${c?` share-action-basket-added`:``}`,onClick:b,disabled:m,title:m&&t==null?`Pick a template first`:i===`basket`?`Adding to basket…`:`Add this section to the report basket`,children:c?`✓ Added`:i===`basket`?`Adding…`:`+ Basket`})]}),(0,U.jsxs)(`div`,{className:`share-save-preset-row`,ref:p,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-save-preset`,disabled:t==null||i!=null,onClick:()=>f(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":d,title:t==null?`Pick a template first`:`Save the current recipe as a named preset`,children:`Save preset…`}),d&&t?(0,U.jsx)(Wc,{panel:e,templateId:t,options:n,onSaved:()=>f(!1),onCancel:()=>f(!1)}):null]}),o?(0,U.jsx)(`div`,{className:`share-action-error`,role:`alert`,children:o}):null]})}function Qc(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function $c({panel:e,onPick:t,onManage:n}){let[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)({}),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!r)return;let t=new AbortController;return u(null),Promise.all([zc({signal:t.signal}),Hc({signal:t.signal})]).then(([t,n])=>{o(t.presets[e]??{}),c(n.history.filter(t=>t.panel===e).slice().reverse())}).catch(e=>{e?.name!==`AbortError`&&u((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Failed to load presets`)}),()=>t.abort()},[r,e]),(0,_.useEffect)(()=>{if(!r)return;function e(e){let t=d.current;t&&(t.contains(e.target)||i(!1))}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[r]);let f=Object.keys(a).sort();return(0,U.jsxs)(`div`,{className:`share-presets-dropdown`,ref:d,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-presets-trigger`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>i(e=>!e),children:`presets ▾`}),r?(0,U.jsxs)(`div`,{className:`share-presets-menu`,role:`menu`,children:[l?(0,U.jsx)(`div`,{className:`share-presets-error`,role:`alert`,children:l}):null,f.length===0&&!l?(0,U.jsx)(`div`,{className:`share-presets-empty`,children:`No saved presets yet.`}):null,f.length>0?(0,U.jsx)(`ul`,{className:`share-presets-list`,children:f.map(e=>(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-item`,onClick:()=>{t(a[e].template_id,a[e].options),i(!1)},children:e})},e))}):null,s.length>0?(0,U.jsxs)(`div`,{className:`share-presets-history`,children:[(0,U.jsx)(`div`,{className:`share-presets-history-heading`,role:`presentation`,children:`Recent shares`}),(0,U.jsx)(`ul`,{className:`share-presets-history-list`,children:s.map(e=>(0,U.jsx)(`li`,{children:(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-history-item`,onClick:()=>{t(e.template_id,e.options),i(!1)},title:`${e.template_id} · ${e.format??`unknown`} · ${e.exported_at}`,children:[(0,U.jsx)(`span`,{className:`share-presets-history-template`,children:e.template_id}),(0,U.jsxs)(`span`,{className:`share-presets-history-meta`,children:[` · `,e.format??`unknown`,` · `,Qc(e.exported_at)]})]})},e.recipe_id))})]}):null,(0,U.jsx)(`div`,{className:`share-presets-footer`,children:(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`share-presets-manage`,onClick:()=>{n(),i(!1)},children:`Manage presets…`})})]}):null]})}var el=`share-manage-presets-title`;function tl({open:e,onClose:t}){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null);Ht((0,_.useMemo)(()=>e?[{key:`Escape`,scope:`modal`,action:t}]:[],[e,t]));let c=(0,_.useRef)(null),l=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(e)l.current||(l.current=!0,c.current=document.activeElement);else if(l.current){l.current=!1;let e=c.current;if(c.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=!1;return s(null),(async()=>{try{let e=await zc();if(t)return;let n=[];for(let[t,r]of Object.entries(e.presets))for(let[e,i]of Object.entries(r))n.push({panel:t,name:e,record:i});n.sort((e,t)=>e.panel===t.panel?e.name.localeCompare(t.name):e.panel.localeCompare(t.panel)),r(n)}catch(e){if(t)return;s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Failed to load presets`)}})(),()=>{t=!0}},[e]);async function u(e){a(!0),s(null);try{await Vc(e.panel,e.name),r(t=>t.filter(t=>!(t.panel===e.panel&&t.name===e.name))),H({type:`SHOW_STATUS_TOAST`,text:`Deleted preset "${e.name}"`})}catch(e){s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Delete failed`)}finally{a(!1)}}async function d(e,t){a(!0),s(null);try{await Bc({panel:e.panel,name:t,template_id:e.record.template_id,options:e.record.options}),await Vc(e.panel,e.name),r(n=>n.map(n=>n.panel===e.panel&&n.name===e.name?{...n,name:t}:n)),H({type:`SHOW_STATUS_TOAST`,text:`Renamed to "${t}"`})}catch(e){s((e instanceof wc?e.message??`HTTP ${e.status}`:e.message)??`Rename failed`)}finally{a(!1)}}return e?(0,U.jsxs)(`div`,{className:`share-manage-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":el,onClick:e=>e.stopPropagation(),children:[(0,U.jsxs)(`div`,{className:`share-manage-header`,children:[(0,U.jsx)(`h2`,{id:el,children:`Manage presets`}),(0,U.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`share-manage-close`,children:`⤬`})]}),o?(0,U.jsx)(`div`,{className:`share-manage-error`,role:`alert`,children:o}):null,n.length===0&&!o?(0,U.jsx)(`p`,{className:`share-manage-empty`,children:`No saved presets yet.`}):null,n.length>0?(0,U.jsxs)(`table`,{className:`share-manage-table`,children:[(0,U.jsx)(`thead`,{children:(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`th`,{children:`Panel`}),(0,U.jsx)(`th`,{children:`Name`}),(0,U.jsx)(`th`,{children:`Saved at`}),(0,U.jsx)(`th`,{})]})}),(0,U.jsx)(`tbody`,{children:n.map(e=>(0,U.jsx)(nl,{row:e,busy:i,onDelete:()=>void u(e),onRename:t=>void d(e,t)},`${e.panel}/${e.name}`))})]}):null]}):null}function nl({row:e,busy:t,onDelete:n,onRename:r}){let[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(e.name),c=()=>{let t=o.trim();if(!t||t===e.name){s(e.name),a(!1);return}r(t),a(!1)};return(0,U.jsxs)(`tr`,{children:[(0,U.jsx)(`td`,{children:Ic(e.panel)}),(0,U.jsx)(`td`,{children:i?(0,U.jsx)(`input`,{className:`share-manage-name-input`,autoFocus:!0,value:o,disabled:t,maxLength:64,onChange:e=>s(e.target.value),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),c()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),s(e.name),a(!1))}}):(0,U.jsx)(`span`,{children:e.name})}),(0,U.jsx)(`td`,{children:e.record.saved_at}),(0,U.jsxs)(`td`,{className:`share-manage-actions`,children:[(0,U.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>{i?(s(e.name),a(!1)):a(!0)},children:i?`Cancel`:`Rename`}),(0,U.jsx)(`button`,{type:`button`,disabled:t,onClick:n,children:`Delete`})]})]})}function rl(){return{format:`md`,theme:`light`,reveal_projects:!1,no_branding:!1,top_n:5,period:{kind:`current`},project_allowlist:null,show_chart:!0,show_table:!0}}function il(e,t){if(!t)return e;let n={...e,...t};return t.period&&(n.period={...e.period,...t.period}),n}function al({panel:e,onClose:t,initialParams:n}){let r=Ic(e),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(()=>{let e=rl();return n?.windowWeeks==null?e:{...e,windowWeeks:n.windowWeeks}}),f=(0,_.useRef)(!1),[p,m]=(0,_.useState)(!1),h=`share-modal-title`;Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`overlay`,layer:200,when:()=>!p&&B().composerModal===null,action:t}],[t,p])),(0,_.useEffect)(()=>{let t=!1;return a(null),s(null),Ec(e).then(e=>{if(t)return;a(e.templates);let n=e.templates[0];n&&(l(n.id),f.current||d(e=>il(e,n.default_options)))}).catch(e=>{t||s(e instanceof wc?`Couldn't load templates: ${e.message??`HTTP ${e.status}`}`:`Couldn't load templates: ${e.message}`)}),()=>{t=!0}},[e]),(0,_.useEffect)(()=>{if(!i||!c||f.current)return;let e=i.find(e=>e.id===c);e&&d(t=>il(t,e.default_options))},[c,i]);let g=e=>{f.current=!0,d(e)};return(0,U.jsxs)(`div`,{className:`share-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":h,onClick:e=>e.stopPropagation(),children:[(0,U.jsx)(`header`,{className:`share-modal-header`,children:(0,U.jsxs)(`h2`,{id:h,children:[`Share `,r,` report`]})}),(0,U.jsxs)(`div`,{className:`share-modal-body`,children:[(0,U.jsxs)(`section`,{className:`share-section share-gallery-section`,"aria-label":`Template gallery`,children:[(0,U.jsx)(`div`,{className:`share-gallery-header`,children:(0,U.jsx)($c,{panel:e,onPick:(e,t)=>{l(e),f.current=!0,d(e=>({...e,...t}))},onManage:()=>m(!0)})}),(0,U.jsx)(Ac,{panel:e,templates:i,error:o,selectedTemplateId:c,onSelect:e=>l(e)})]}),(0,U.jsxs)(`section`,{className:`share-section share-main-section`,children:[(0,U.jsx)(`div`,{className:`share-knobs-col`,"aria-label":`Render options`,children:(0,U.jsx)(jc,{options:u,onChange:g})}),(0,U.jsx)(`div`,{className:`share-preview-col`,"aria-label":`Live preview`,children:(0,U.jsx)(Pc,{panel:e,templateId:c,options:u})})]})]}),(0,U.jsx)(`footer`,{className:`share-modal-footer`,children:(0,U.jsx)(Zc,{panel:e,templateId:c,options:u,onOptionsChange:g})}),(0,U.jsx)(`button`,{type:`button`,className:`share-modal-close`,"aria-label":`Close share modal`,onClick:t,children:`⤬`}),(0,U.jsx)(tl,{open:p,onClose:()=>m(!1)})]})}function ol(e,t){return{title:t.title,theme:t.theme,format:t.format,no_branding:t.no_branding,reveal_projects:t.reveal_projects,sections:e.map(e=>({snapshot:{panel:e.panel,template_id:e.template_id,options:e.options,data_digest_at_add:e.data_digest_at_add,kernel_version:e.kernel_version}}))}}async function sl(e,t){let n=await fetch(`/api/share/compose`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t?.signal});if(!n.ok){let e={};try{e=await n.json()}catch{}throw new wc(n.status,e.field,e.error??`HTTP ${n.status}`,e.code)}return n.json()}function cl({items:e,results:t,kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a}){let o=Xr(Yr(Zi,{activationConstraint:{distance:4}}),Yr(Ki,{coordinateGetter:wo}));function s(t){if(!t.over||t.active.id===t.over.id)return;let n=e.findIndex(e=>e.id===t.active.id),r=e.findIndex(e=>e.id===t.over.id);n<0||r<0||H({type:`BASKET_REORDER`,fromIdx:n,toIdx:r})}return(0,U.jsx)(Ja,{sensors:o,collisionDetection:ii,onDragEnd:s,children:(0,U.jsx)(fo,{items:e.map(e=>e.id),strategy:co,children:(0,U.jsx)(`ul`,{className:`composer-section-list`,children:e.map((e,o)=>(0,U.jsx)(ll,{item:e,result:t[o],kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a},e.id))})})})}function ll({item:e,result:t,kernelVersion:n,onRefresh:r,onRemove:i,onPreviewOnly:a}){let{attributes:o,listeners:s,setNodeRef:c,transform:l,transition:u,isDragging:d}=bo({id:e.id}),f=jo(),p={transform:Pr.Transform.toString(l),transition:f?void 0:u,opacity:d?.4:1},[m,h]=(0,_.useState)(!1),g=t?.drift_detected,v=e.kernel_version!==n,y=!!(g||v);return(0,U.jsxs)(`li`,{ref:c,style:p,className:`composer-section-row`,children:[(0,U.jsx)(`button`,{className:`composer-drag-handle`,"aria-label":`Reorder ${e.label_hint}`,type:`button`,...o,...s,children:`≡`}),(0,U.jsx)(`span`,{className:`composer-section-label`,children:e.label_hint}),y?(0,U.jsx)(`span`,{className:`composer-outdated-badge`,title:g&&v?`Data and kernel both shifted since add-time. Refresh to update.`:g?`Data has changed since this section was added. Refresh to update.`:`Kernel updated since this section was added. Refresh to re-render at the new version.`,children:`Outdated`}):null,(0,U.jsxs)(`div`,{className:`composer-section-actions`,children:[(0,U.jsx)(`button`,{type:`button`,"aria-haspopup":`menu`,"aria-expanded":m,onClick:()=>h(e=>!e),"aria-label":`Actions for ${e.label_hint}`,children:`⋯`}),m?(0,U.jsxs)(`ul`,{role:`menu`,className:`composer-section-menu`,children:[(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{a(e.id),h(!1)},children:`Preview only this`})}),(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{r(e.id),h(!1)},children:`Refresh from current data`})}),(0,U.jsx)(`li`,{children:(0,U.jsx)(`button`,{type:`button`,onClick:()=>{i(e.id),h(!1)},"aria-label":`Remove ${e.label_hint}`,children:`Remove`})})]}):null]})]})}function ul(e,t){return t&&e>0}function dl(e){return`cctally-report-${new Date().toISOString().slice(0,10).replaceAll(`-`,``)}.${e===`md`?`md`:e}`}function fl(e){switch(e){case`md`:return`text/markdown;charset=utf-8`;case`html`:return`text/html;charset=utf-8`;case`svg`:return`image/svg+xml;charset=utf-8`}}function pl(e){return e===`light`?`#ffffff`:`#0f172a`}function ml(e,t){let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.style.display=`none`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),0)}var hl=200;function gl(){return B().composerModal}function _l(){return B().basket}var vl=`composer-modal-title`;function yl(){let e=(0,_.useSyncExternalStore)(V,gl),t=(0,_.useSyncExternalStore)(V,_l),n=cn(),r=(0,_.useRef)(null),i=(0,_.useRef)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(`light`),[l,u]=(0,_.useState)(`html`),[d,f]=(0,_.useState)(!0),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(!1),S=(0,_.useRef)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(null);(0,_.useEffect)(()=>{E(null)},[l,s,d,p]),Ht((0,_.useMemo)(()=>[{key:`Escape`,scope:`overlay`,layer:210,when:()=>B().composerModal!==null,action:()=>H(me())}],[])),(0,_.useEffect)(()=>{e?.open&&a===``&&o(`cctally report — ${new Date().toISOString().slice(0,10)}`)},[e?.open,a]),(0,_.useEffect)(()=>{if(e?.open)i.current||(i.current=!0,r.current=document.activeElement);else if(i.current){i.current=!1;let e=r.current;if(r.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e?.open]),(0,_.useEffect)(()=>{if(!e?.open||t.items.length===0||a===``)return;let n=setTimeout(()=>{S.current?.abort();let e=new AbortController;S.current=e,x(!0),y(null),sl(ol(t.items,{title:a,theme:s,format:l,no_branding:p,reveal_projects:!d}),{signal:e.signal}).then(t=>{e.signal.aborted||g(t)}).catch(t=>{t?.name!==`AbortError`&&(e.signal.aborted||y(t instanceof wc?t.message??`HTTP ${t.status}`:t.message))}).finally(()=>{e.signal.aborted||x(!1)})},hl);return()=>clearTimeout(n)},[e?.open,t.items,a,s,l,d,p]);async function D(e){let n=t.items.findIndex(t=>t.id===e);if(n<0)return;let r=t.items[n];try{let t=await Dc({panel:r.panel,template_id:r.template_id,options:{...r.options,reveal_projects:!d}}),i=_e({panel:r.panel,template_id:r.template_id,options:r.options,added_at:new Date().toISOString(),data_digest_at_add:t.snapshot.data_digest,kernel_version:t.snapshot.kernel_version,label_hint:r.label_hint,id:r.id});H({type:`BASKET_REMOVE`,id:e}),H({type:`BASKET_ADD`,item:i});let a=B().basket.items.length-1;a!==n&&H({type:`BASKET_REORDER`,fromIdx:a,toIdx:n})}catch(e){y(`Refresh failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}}let O=async e=>{let n=await sl(ol(t.items,{title:a,theme:s,format:e,no_branding:p,reveal_projects:!d}));return{body:n.body,content_type:n.content_type}},k=e=>H({type:`SHOW_STATUS_TOAST`,text:e}),A=async(e,t,n)=>{if(C==null){w(e),E(null);try{await t()}catch(e){E(`${n} failed: ${e instanceof wc?e.message??`HTTP ${e.status}`:e.message}`)}finally{w(null)}}},j=()=>A(`copy`,async()=>{let{body:e}=await O(`md`);if(!navigator.clipboard||typeof navigator.clipboard.writeText!=`function`)throw Error(`Clipboard API unavailable in this browser`);await navigator.clipboard.writeText(e),k(`Copied`)},`Copy`),M=()=>A(`download`,async()=>{let{body:e}=await O(l),t=new Blob([e],{type:fl(l)});ml(dl(l),t),k(`Downloaded`)},`Download`),N=()=>A(`open`,async()=>{let{body:e}=await O(l),t=new Blob([e],{type:fl(l)}),n=URL.createObjectURL(t);window.open(n,`_blank`,`noopener,noreferrer`)},`Open`),P=()=>A(`png`,async()=>{let{body:e}=await O(`svg`),t=await Gc(e,2,pl(s));ml(dl(`svg`).replace(/\.svg$/,`.png`),t),k(`PNG downloaded`)},`PNG export`),F=()=>A(`print`,async()=>{let{body:e}=await O(`html`);J(e)},`Print`),ee=C==null&&l===`md`&&t.items.length>0,te=C==null&&t.items.length>0,ne=C==null&&(l===`html`||l===`svg`)&&t.items.length>0,I=C==null&&l===`svg`&&t.items.length>0,re=C==null&&l===`html`&&t.items.length>0,ie=!d,ae=ul(t.items.length,ie),oe=ie?t.items.length:0;return e?.open?t.items.length===0?(0,U.jsxs)(`div`,{className:`composer-modal composer-modal-empty${n?` composer-modal-mobile`:``}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":vl,children:[(0,U.jsxs)(`header`,{className:`composer-modal-header`,children:[(0,U.jsx)(`h2`,{id:vl,children:`Compose report`}),(0,U.jsx)(`button`,{type:`button`,className:`composer-modal-close`,onClick:()=>H(me()),"aria-label":`Close`,children:`⤬`})]}),(0,U.jsx)(`p`,{className:`composer-empty-message`,children:`Basket is empty. Open any panel's share menu and pick + Basket to add a section.`})]}):(0,U.jsxs)(`div`,{className:`composer-modal${n?` composer-modal-mobile`:``}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":vl,children:[(0,U.jsxs)(`header`,{className:`composer-modal-header`,children:[(0,U.jsx)(`h2`,{id:vl,children:`Compose report`}),(0,U.jsx)(`button`,{type:`button`,className:`composer-modal-close`,onClick:()=>H(me()),"aria-label":`Close`,children:`⤬`})]}),(0,U.jsxs)(`div`,{className:`composer-knobs`,children:[(0,U.jsxs)(`label`,{children:[`Title`,(0,U.jsx)(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value)})]}),(0,U.jsxs)(`label`,{children:[`Theme`,(0,U.jsxs)(`select`,{value:s,onChange:e=>c(e.target.value),children:[(0,U.jsx)(`option`,{value:`light`,children:`light`}),(0,U.jsx)(`option`,{value:`dark`,children:`dark`})]})]}),(0,U.jsxs)(`label`,{children:[`Format`,(0,U.jsxs)(`select`,{value:l,onChange:e=>u(e.target.value),children:[(0,U.jsx)(`option`,{value:`html`,children:`html`}),(0,U.jsx)(`option`,{value:`md`,children:`md`}),(0,U.jsx)(`option`,{value:`svg`,children:`svg`})]})]}),(0,U.jsxs)(`label`,{children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Anon on export`]}),(0,U.jsxs)(`label`,{children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),`No branding`]})]}),ae?(0,U.jsxs)(`div`,{className:`composer-anon-banner`,role:`status`,"aria-live":`polite`,children:[(0,U.jsxs)(`span`,{children:[oe,` section`,oe===1?``:`s`,` contain real project names. They will appear in the export.`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>f(!0),children:`Anonymize all`})]}):null,(0,U.jsxs)(`div`,{className:`composer-body`,children:[(0,U.jsx)(cl,{items:t.items,results:h?.snapshot.section_results??[],kernelVersion:h?.snapshot.kernel_version??1,onRefresh:e=>{D(e)},onRemove:e=>H({type:`BASKET_REMOVE`,id:e}),onPreviewOnly:e=>{}}),(0,U.jsx)(`iframe`,{className:`composer-preview`,title:`Combined preview`,tabIndex:-1,sandbox:`allow-same-origin`,srcDoc:h?.body??`<p>Composing&hellip;</p>`})]}),b?(0,U.jsx)(`div`,{className:`composer-busy`,children:`Composing…`}):null,v?(0,U.jsx)(`div`,{className:`composer-error`,role:`alert`,children:v}):null,T?(0,U.jsx)(`div`,{className:`composer-error`,role:`alert`,children:T}):null,(0,U.jsxs)(`footer`,{className:`composer-actions`,children:[(0,U.jsxs)(`div`,{className:`composer-export-row`,children:[(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-copy`,onClick:j,disabled:!ee,title:l===`md`?C===`copy`?`Copying…`:`Copy composed report to clipboard`:`Copy is available for Markdown only`,children:C===`copy`?`Copying…`:`Copy`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-download`,onClick:M,disabled:!te,title:C===`download`?`Downloading…`:`Download composed report`,children:C===`download`?`Downloading…`:`Download`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-open`,onClick:N,disabled:!ne,title:l===`html`||l===`svg`?C===`open`?`Opening…`:`Open composed report in new tab`:`Open is available for HTML/SVG`,children:C===`open`?`Opening…`:`Open`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-png`,onClick:P,disabled:!I,title:l===`svg`?C===`png`?`Rasterizing…`:`Download composed report as PNG`:`PNG export — available for SVG format only`,children:C===`png`?`Rasterizing…`:`PNG`}),(0,U.jsx)(`button`,{type:`button`,className:`share-action share-action-print`,onClick:F,disabled:!re,title:l===`html`?C===`print`?`Opening print dialog…`:`Open the browser print dialog (save as PDF)`:`Print → PDF — available for HTML format only`,children:C===`print`?`Printing…`:`Print → PDF`})]}),(0,U.jsx)(`button`,{type:`button`,className:`composer-clear-all`,onClick:()=>H({type:`BASKET_CLEAR`}),children:`Clear all`})]})]}):null}function bl(){let e=(0,_.useSyncExternalStore)(V,()=>B().shareModal),t=(0,_.useRef)(null),n=(0,_.useRef)(!1);(0,_.useEffect)(()=>{if(e)n.current||(n.current=!0,t.current=(e.triggerId?document.getElementById(e.triggerId):null)??document.activeElement);else if(n.current){n.current=!1;let e=t.current;if(t.current=null,e&&typeof e.focus==`function`&&document.contains(e))e.focus();else{let e=document.activeElement;e&&typeof e.blur==`function`&&e.blur(),document.body.focus()}}},[e]);let r=()=>H(fe());return(0,U.jsxs)(U.Fragment,{children:[e?(0,U.jsx)(`div`,{id:`share-modal-root`,className:`share-overlay`,onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&r()},children:(0,U.jsx)(al,{panel:e.panel,initialParams:e.params,onClose:r})}):null,(0,U.jsx)(yl,{})]})}var xl=class extends Error{constructor(e){super(`HTTP ${e}`),this.status=e,this.name=`HttpError`}};function Sl(e){return e?.name===`AbortError`}async function Cl(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw new xl(n.status);return await n.json()}function wl(e){let[t,n]=(0,_.useState)(null),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=(0,_.useRef)(e),c=(0,_.useRef)(null),l=(0,_.useRef)(!1),u=(0,_.useRef)(!1),d=(0,_.useCallback)(async()=>{if(l.current){u.current=!0;return}let e=s.current;if(e){l.current=!0;try{let t=await Cl(`/api/conversation/${encodeURIComponent(e)}/outline`);if(s.current!==e)return;c.current=t,n(t),o(null),i(!1)}catch{if(s.current!==e)return;o(`Couldn't load the outline.`),i(!1)}finally{l.current=!1,u.current&&(u.current=!1,d())}}},[]);return(0,_.useEffect)(()=>{if(s.current=e,c.current=null,l.current=!1,u.current=!1,n(null),o(null),!e){i(!1);return}i(!0),d()},[e,d]),(0,_.useEffect)(()=>{c.current&&d()},[W()?.generated_at??``]),{outline:t,loading:r,error:a}}var Tl=50;function El(){let[e,t]=(0,_.useState)([]),[n,r]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(0),c=W()?.generated_at??``,l=(0,_.useRef)(!1),u=(0,_.useRef)(0);(0,_.useEffect)(()=>{u.current=e.length},[e.length]);let d=(0,_.useRef)(null),f=(0,_.useCallback)(()=>{if(l.current||u.current>Tl)return;d.current?.abort();let e=new AbortController;d.current=e,Cl(`/api/conversations?sort=recent&limit=${Tl}&offset=0`,e.signal).then(e=>{t(e.conversations),s(e.page.next_offset),a(null),r(!1)}).catch(e=>{Sl(e)||(a(`Couldn't load conversations.`),r(!1))})},[]);(0,_.useEffect)(()=>{if(!(typeof document<`u`&&document.hidden))return f(),()=>d.current?.abort()},[c,f]),(0,_.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{document.hidden||f()};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[f]);let p=(0,_.useCallback)(async()=>{if(!(o==null||l.current)){l.current=!0;try{let e=await Cl(`/api/conversations?sort=recent&limit=${Tl}&offset=${o}`);t(t=>[...t,...e.conversations]),s(e.page.next_offset)}catch{}finally{l.current=!1}}},[o]);return{rows:e,loading:n,error:i,hasMore:o!=null,loadMore:p}}function Dl(e,t,n=e){let[r,i]=(0,_.useState)(n);return(0,_.useEffect)(()=>{let n=setTimeout(()=>i(e),t);return()=>clearTimeout(n)},[e,t]),r}var Ol=200;function kl(e,t=`all`){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(0),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),g=e.trim(),v=Dl(g,Ol,``),y=(0,_.useRef)(null),b=(0,_.useRef)(0);b.current=n.length;let x=(0,_.useRef)(0);x.current=o;let S=(0,_.useRef)(!1);S.current=f;let C=(0,_.useCallback)(e=>`/api/conversation/search?q=${encodeURIComponent(v)}&limit=50&offset=${e}&kind=${t}`,[v,t]);(0,_.useEffect)(()=>(g||(r([]),a(null),s(0),l(null),h(null)),()=>{y.current?.abort()}),[g,t]),(0,_.useEffect)(()=>{if(!v){d(!1),p(!1);return}let e=new AbortController;return y.current=e,d(!0),p(!1),Cl(C(0),e.signal).then(e=>{r(e.hits),a(e.mode),s(e.total),l(e.search_depth??`full`),h(null),d(!1)}).catch(e=>{Sl(e)||(h(`Search failed.`),d(!1))}),()=>e.abort()},[v,t,C]);let w=(0,_.useCallback)(()=>{if(S.current||b.current>=x.current)return;let e=b.current,t=new AbortController;y.current=t,p(!0),Cl(C(e),t.signal).then(e=>{r(t=>[...t,...e.hits]),s(e.total),a(e.mode),l(e.search_depth??`full`),p(!1)}).catch(e=>{Sl(e)||(h(`Search failed.`),p(!1))})},[C]);return{hits:n,mode:i,total:o,loading:g!==``&&(g!==v||u),loadingMore:f,searchDepth:c,error:m,loadMore:w}}function Al(e){let t=[],n=0,r=0;for(;n<e.length;){let i=e.indexOf(`[`,n);if(i===-1){t.push((0,U.jsx)(_.Fragment,{children:e.slice(n)},r++));break}let a=e.indexOf(`]`,i+1);if(a===-1){t.push((0,U.jsx)(_.Fragment,{children:e.slice(n)},r++));break}i>n&&t.push((0,U.jsx)(_.Fragment,{children:e.slice(n,i)},r++)),t.push((0,U.jsx)(`mark`,{children:e.slice(i+1,a)},r++)),n=a+1}return(0,U.jsx)(U.Fragment,{children:t})}var jl=864e5;function Ml(e,t){let[n,r,i]=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).format(new Date(e)).split(`-`).map(Number);return{y:n,m:r,d:i}}function Nl(e,t,n){let r=Date.parse(e),i=Ml(r,t),a=Ml(n,t),o=Date.UTC(i.y,i.m-1,i.d),s=Date.UTC(a.y,a.m-1,a.d),c=Math.round((s-o)/jl);return c<=0?`Today`:c===1?`Yesterday`:c<7?`This Week`:i.y===a.y&&i.m===a.m?`This Month`:new Intl.DateTimeFormat(`en-US`,{timeZone:t,month:`long`,year:`numeric`}).format(new Date(r))}var Pl=[{kind:`all`,label:`All`,needsSplit:!1},{kind:`prompts`,label:`Prompts`,needsSplit:!1},{kind:`assistant`,label:`Assistant`,needsSplit:!1},{kind:`tools`,label:`Tools`,needsSplit:!0},{kind:`thinking`,label:`Thinking`,needsSplit:!0}];function Fl(){let e=(0,_.useSyncExternalStore)(V,()=>B().conversationSearch),t=(0,_.useSyncExternalStore)(V,()=>B().conversationSearchKind),n=(0,_.useSyncExternalStore)(V,()=>B().selectedConversationId),r=Wt(),i={tz:r.resolvedTz,offsetLabel:r.offsetLabel},a=(0,_.useRef)(null),o=e.trim()!==``;return(0,U.jsxs)(`aside`,{className:`conv-rail`,children:[(0,U.jsx)(`div`,{className:`conv-rail-search`,children:(0,U.jsx)(`input`,{ref:a,type:`search`,className:`conv-rail-search-input`,placeholder:`search all conversations…`,value:e,onChange:e=>H({type:`SET_CONVERSATION_SEARCH`,text:e.target.value}),onFocus:()=>H({type:`SET_INPUT_MODE`,mode:`search`}),onBlur:()=>H({type:`SET_INPUT_MODE`,mode:null}),onKeyDown:e=>{e.key===`Escape`&&(H({type:`SET_CONVERSATION_SEARCH`,text:``}),a.current?.blur())}})}),o?(0,U.jsx)(zl,{needle:e,kind:t,ctx:i}):(0,U.jsx)(Il,{selectedId:n,ctx:i})]})}function Il({selectedId:e,ctx:t}){let{rows:n,loading:r,error:i,hasMore:a,loadMore:o}=El();if(i)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:i})});if(r&&n.length===0)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`Loading…`})});if(n.length===0)return(0,U.jsx)(`div`,{className:`conv-rail-list`,children:(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`No conversations.`})});let s=null,c=Date.now();return(0,U.jsxs)(`div`,{className:`conv-rail-list`,children:[n.map(n=>{let r=Nl(n.started_utc,t.tz,c),i=r!==s;return i&&(s=r),(0,U.jsxs)(_.Fragment,{children:[i&&(0,U.jsx)(`div`,{className:`conv-rail-sec`,children:r}),(0,U.jsx)(Ll,{row:n,ctx:t,active:n.session_id===e})]},n.session_id)}),a&&(0,U.jsx)(`button`,{type:`button`,className:`conv-rail-more`,onClick:()=>void o(),children:`Load more`})]})}function Ll({row:e,ctx:t,active:n}){return(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-row${n?` is-active`:``}`,onClick:()=>H({type:`SELECT_CONVERSATION`,sessionId:e.session_id}),children:[(0,U.jsx)(`div`,{className:`conv-rail-row-title`,children:e.title}),(0,U.jsxs)(`div`,{className:`conv-rail-row-meta`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-project`,children:e.project_label||`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-branch`,children:e.git_branch??`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-when`,children:A.startedShort(e.started_utc,t,{noSuffix:!0})}),(0,U.jsx)(`span`,{className:`conv-rail-row-cost`,children:A.usd2(e.cost_usd)}),(0,U.jsxs)(`span`,{className:`conv-rail-row-msgs`,children:[e.msg_count,` msgs`]})]})]})}function Rl({kind:e,proseOnly:t}){return(0,U.jsx)(`div`,{className:`conv-rail-chips`,role:`radiogroup`,"aria-label":`Search kind`,children:Pl.map(n=>{let r=n.needsSplit&&t,i=e===n.kind;return(0,U.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":i,disabled:r,title:r?`indexing…`:void 0,className:`conv-rail-chip${i?` is-on`:``}`,onClick:()=>H({type:`SET_CONVERSATION_SEARCH_KIND`,kind:n.kind}),children:n.label},n.kind)})})}function zl({needle:e,kind:t,ctx:n}){let{hits:r,mode:i,total:a,loading:o,loadingMore:s,searchDepth:c,error:l,loadMore:u}=kl(e,t),d=c===`prose-only`,f=a-r.length,p=d&&(t===`tools`||t===`thinking`),m=(a===0?`No results`:`${a} results${i===`like`?` · basic search`:``}`)+(p?` · indexing…`:``);return(0,U.jsxs)(`div`,{className:`conv-rail-list`,children:[(0,U.jsx)(Rl,{kind:t,proseOnly:d}),l?(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:l}):o&&r.length===0?(0,U.jsx)(`div`,{className:`conv-rail-empty`,children:`Searching…`}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`conv-rail-count`,"aria-live":`polite`,children:m}),r.map((e,t)=>(0,U.jsx)(Bl,{hit:e,ctx:n},`${e.session_id}-${e.uuid}-${t}`)),r.length<a&&(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-more`,disabled:s,onClick:()=>u(),children:[`Load `,Math.min(50,f),` more (`,f,` remaining)`]})]})]})}function Bl({hit:e,ctx:t}){let n=e.match_kinds??[];return(0,U.jsxs)(`button`,{type:`button`,className:`conv-rail-row conv-rail-row--hit`,onClick:()=>H({type:`OPEN_CONVERSATION`,sessionId:e.session_id,jump:{session_id:e.session_id,uuid:e.uuid}}),children:[(0,U.jsxs)(`div`,{className:`conv-rail-row-title conv-rail-row-title--hit`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-title-text`,children:e.title}),n.length>0&&(0,U.jsx)(`span`,{className:`conv-rail-kindbs`,children:n.map(e=>(0,U.jsx)(`span`,{className:`conv-rail-kindb`,children:e},e))})]}),(0,U.jsxs)(`div`,{className:`conv-rail-row-meta`,children:[(0,U.jsx)(`span`,{className:`conv-rail-row-project`,children:e.project_label||`—`}),(0,U.jsx)(`span`,{className:`conv-rail-row-when`,children:A.startedShort(e.ts,t,{noSuffix:!0})}),(0,U.jsx)(`span`,{className:`conv-rail-row-cost`,children:A.usd2(e.cost_usd)})]}),(0,U.jsx)(`div`,{className:`conv-rail-row-snippet`,children:Al(e.snippet)})]})}var Vl=500;function Hl(e){let[t,n]=(0,_.useState)(null),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(!1),h=(0,_.useRef)(null),g=(0,_.useCallback)(e=>{n(t=>{let n=typeof e==`function`?e(t):e;return h.current=n,n})},[]);(0,_.useEffect)(()=>{if(d.current=e,!e){g(null),c(null),i(!1),o(null),l.current=null;return}i(!0),o(null),g(null),l.current=null;let t=new AbortController;return Cl(`/api/conversation/${encodeURIComponent(e)}?limit=${Vl}`,t.signal).then(t=>{g(t),c(e),l.current=t.page.next_after,i(!1)}).catch(e=>{if(!Sl(e)){if(e instanceof xl&&e.status===404){o(`Conversation not found.`),i(!1);return}o(`Couldn't load the conversation.`),i(!1)}}),()=>t.abort()},[e,g]);let v=(0,_.useCallback)(async()=>{let e=l.current,t=d.current;if(e==null||t==null||u.current)return!1;u.current=!0;try{let n;try{n=await Cl(`/api/conversation/${encodeURIComponent(t)}?limit=${Vl}&after=${e}`)}catch{return!1}return d.current===t?(g(e=>e?{...e,items:[...e.items,...n.items],page:n.page,subagent_meta:n.subagent_meta??e.subagent_meta}:n),l.current=n.page.next_after,n.page.next_after!=null):!1}finally{u.current=!1}},[g]),y=(0,_.useCallback)(async()=>{await v()},[v]),b=(0,_.useCallback)(async e=>{let t=()=>{let t=h.current;return!!t&&t.items.some(t=>t.member_uuids.includes(e))};for(let e=0;e<20;e++)if(t()||!await v())return},[v]),x=t!=null&&s===e,S=x?t:null,C=e!=null&&!x&&a==null?!0:r,w=S?.page?.next_after!=null;f.current=w;let T=(0,_.useCallback)(async()=>{if(p.current){m.current=!0;return}let e=d.current;if(!(!e||f.current||u.current)){p.current=!0;try{for(let t=0;t<50;t++){let t=h.current?.items.at(-1);if(!t)break;let n;try{n=await Cl(`/api/conversation/${encodeURIComponent(e)}?limit=${Vl}&after=${t.anchor.id}`)}catch{break}if(d.current!==e)return;if(g(e=>e&&{...e,items:n.items.length?[...e.items,...n.items]:e.items,cost_usd:n.cost_usd,models:n.models,title:n.title??e.title,git_branch:n.git_branch,project_label:n.project_label,subagent_meta:n.subagent_meta??e.subagent_meta,page:e.page}),!n.items.length||n.page.next_after==null)break}}finally{p.current=!1,m.current&&(m.current=!1,T())}}},[g]);return(0,_.useEffect)(()=>{h.current&&!f.current&&T()},[W()?.generated_at??``]),{detail:S,loading:C,error:a,hasMore:w,loadMore:y,loadUntil:b}}function Ul(e){let t=[],n=[],r=()=>{n.length>=2?t.push({kind:`tool_result_run`,items:n}):n.length===1&&t.push({kind:`item`,item:n[0]}),n=[]};for(let i of e){if(i.kind===`item`&&i.item.kind===`tool_result`){n.push(i.item);continue}r(),t.push(i)}return r(),t}function Wl(e){let t=new Map,n=new Map;for(let r of e){let e=r.subagent_key;if(e!=null){let n=t.get(e);n?n.push(r):t.set(e,[r])}else for(let e of r.member_uuids)n.set(e,r)}let r=new Set,i=new Map;for(let[e,a]of t){let t=(a.find(e=>e.kind!==`meta`)??a[0]).parent_uuid,o=t==null?void 0:n.get(t);if(o){r.add(e);let t=o.anchor.uuid,n=i.get(t);n?n.push(e):i.set(t,[e])}}let a=[],o=new Set,s=e=>{a.push({kind:`subagent`,subagentKey:e,items:t.get(e),nested:r.has(e)}),o.add(e)};for(let t of e)if(t.subagent_key==null){a.push({kind:`item`,item:t});let e=i.get(t.anchor.uuid);if(e)for(let t of e)o.has(t)||s(t)}else{let e=t.subagent_key;if(o.has(e)||r.has(e))continue;s(e)}for(let e of t.keys())o.has(e)||s(e);return Ul(a)}var Gl=RegExp(`^\\s*(?:<(${[`command-name`,`command-message`,`command-args`,`local-command-caveat`,`local-command-stdout`,`local-command-stderr`].join(`|`)})>(?:(?!</\\1>)[\\s\\S])*</\\1>\\s*)+$`);function Kl(e){return e?Gl.test(e):!1}var ql=200;function Jl(e,t){let[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(0),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=t.trim(),h=Dl(m,ql,``),g=(0,_.useRef)(null);return(0,_.useEffect)(()=>(m||(r([]),a(0),s(!1),l(null),p(null)),()=>{g.current?.abort()}),[m]),(0,_.useEffect)(()=>{if(!h){d(!1);return}let t=new AbortController;return g.current=t,d(!0),Cl(`/api/conversation/${encodeURIComponent(e)}/find?q=${encodeURIComponent(h)}`,t.signal).then(e=>{r(e.anchors),a(e.total),s(e.anchors_truncated),l(e.mode),p(null),d(!1)}).catch(e=>{Sl(e)||(r([]),a(0),s(!1),l(null),p(`Find failed.`),d(!1))}),()=>t.abort()},[e,h]),{anchors:n,total:i,truncated:o,mode:c,loading:m!==``&&(m!==h||u),error:f}}function Yl({sessionId:e,onClose:t,onTermsChange:n,stepRef:r}){let[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(0),{anchors:c,total:l,truncated:u,mode:d,loading:f,error:p}=Jl(e,i),m=(0,_.useRef)(null);(0,_.useEffect)(()=>{m.current?.focus()},[]);let h=Dl(i.trim(),200,``);(0,_.useEffect)(()=>{n(h)},[h,n]),(0,_.useEffect)(()=>{s(0)},[c]);let g=t=>{if(c.length===0)return;let n=((o+t)%c.length+c.length)%c.length;s(n);let r=c[n];H({type:`OPEN_CONVERSATION`,sessionId:e,jump:{session_id:e,uuid:r.uuid,expand_details:r.match_kinds.length>0}})};r&&(r.current=g),(0,_.useEffect)(()=>()=>{r&&(r.current=null)},[r]);let v=()=>{H({type:`CLOSE_CONV_FIND`}),t()},y=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),g(e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),v())},b=c.length>0,x=b?c[o]:null,S=`${b?o+1:0} / ${l}`;return(0,U.jsxs)(`div`,{className:`conv-findbar`,role:`search`,"aria-label":`Find within this conversation`,children:[(0,U.jsx)(`input`,{ref:m,className:`conv-findbar-input`,type:`text`,"aria-label":`Find in conversation`,placeholder:`Find…`,value:i,onChange:e=>a(e.target.value),onKeyDown:y}),(0,U.jsxs)(`span`,{className:`conv-findbar-count`,"aria-live":`polite`,children:[S,u&&(0,U.jsx)(`span`,{className:`conv-findbar-note`,children:` · first 500`})]}),x&&x.match_kinds.length>0&&(0,U.jsx)(`span`,{className:`conv-findbar-kind`,children:x.match_kinds.join(` `)}),d===`like`&&(0,U.jsx)(`span`,{className:`conv-findbar-hint`,children:`basic search`}),p&&(0,U.jsx)(`span`,{className:`conv-findbar-hint`,children:`find failed`}),f&&(0,U.jsx)(`span`,{className:`conv-findbar-spin`,"aria-hidden":`true`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-nav`,"aria-label":`Previous match`,title:`Previous match (Shift+Enter)`,disabled:!b,onClick:()=>g(-1),children:`‹`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-nav`,"aria-label":`Next match`,title:`Next match (Enter)`,disabled:!b,onClick:()=>g(1),children:`›`}),(0,U.jsx)(`button`,{type:`button`,className:`conv-findbar-close`,"aria-label":`Close find`,title:`Close (Esc)`,onClick:v,children:`✕`})]})}var Xl=(0,_.createContext)(null);function Zl(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function Ql(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var $l=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eu=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tu={};function nu(e,t){return((t||tu).jsx?eu:$l).test(e)}var ru=/[ \t\n\f\r]/g;function iu(e){return typeof e==`object`?e.type===`text`?au(e.value):!1:au(e)}function au(e){return e.replace(ru,``)===``}var ou=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};ou.prototype.normal={},ou.prototype.property={},ou.prototype.space=void 0;function su(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new ou(n,r,t)}function cu(e){return e.toLowerCase()}var lu=class{constructor(e,t){this.attribute=t,this.property=e}};lu.prototype.attribute=``,lu.prototype.booleanish=!1,lu.prototype.boolean=!1,lu.prototype.commaOrSpaceSeparated=!1,lu.prototype.commaSeparated=!1,lu.prototype.defined=!1,lu.prototype.mustUseProperty=!1,lu.prototype.number=!1,lu.prototype.overloadedBoolean=!1,lu.prototype.property=``,lu.prototype.spaceSeparated=!1,lu.prototype.space=void 0;var uu=s({boolean:()=>Y,booleanish:()=>fu,commaOrSpaceSeparated:()=>gu,commaSeparated:()=>hu,number:()=>X,overloadedBoolean:()=>pu,spaceSeparated:()=>mu}),du=0,Y=_u(),fu=_u(),pu=_u(),X=_u(),mu=_u(),hu=_u(),gu=_u();function _u(){return 2**++du}var vu=Object.keys(uu),yu=class extends lu{constructor(e,t,n,r){let i=-1;if(super(e,t),bu(this,`space`,r),typeof n==`number`)for(;++i<vu.length;){let e=vu[i];bu(this,vu[i],(n&uu[e])===uu[e])}}};yu.prototype.defined=!0;function bu(e,t,n){n&&(e[t]=n)}function xu(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new yu(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[cu(r)]=r,n[cu(a.attribute)]=r}return new ou(t,n,e.space)}var Su=xu({properties:{ariaActiveDescendant:null,ariaAtomic:fu,ariaAutoComplete:null,ariaBusy:fu,ariaChecked:fu,ariaColCount:X,ariaColIndex:X,ariaColSpan:X,ariaControls:mu,ariaCurrent:null,ariaDescribedBy:mu,ariaDetails:null,ariaDisabled:fu,ariaDropEffect:mu,ariaErrorMessage:null,ariaExpanded:fu,ariaFlowTo:mu,ariaGrabbed:fu,ariaHasPopup:null,ariaHidden:fu,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:mu,ariaLevel:X,ariaLive:null,ariaModal:fu,ariaMultiLine:fu,ariaMultiSelectable:fu,ariaOrientation:null,ariaOwns:mu,ariaPlaceholder:null,ariaPosInSet:X,ariaPressed:fu,ariaReadOnly:fu,ariaRelevant:null,ariaRequired:fu,ariaRoleDescription:mu,ariaRowCount:X,ariaRowIndex:X,ariaRowSpan:X,ariaSelected:fu,ariaSetSize:X,ariaSort:null,ariaValueMax:X,ariaValueMin:X,ariaValueNow:X,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function Cu(e,t){return t in e?e[t]:t}function wu(e,t){return Cu(e,t.toLowerCase())}var Tu=xu({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:hu,acceptCharset:mu,accessKey:mu,action:null,allow:null,allowFullScreen:Y,allowPaymentRequest:Y,allowUserMedia:Y,alpha:Y,alt:null,as:null,async:Y,autoCapitalize:null,autoComplete:mu,autoFocus:Y,autoPlay:Y,blocking:mu,capture:null,charSet:null,checked:Y,cite:null,className:mu,closedBy:null,colorSpace:null,cols:X,colSpan:X,command:null,commandFor:null,content:null,contentEditable:fu,controls:Y,controlsList:mu,coords:X|hu,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Y,defer:Y,dir:null,dirName:null,disabled:Y,download:pu,draggable:fu,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Y,formTarget:null,headers:mu,height:X,hidden:pu,high:X,href:null,hrefLang:null,htmlFor:mu,httpEquiv:mu,id:null,imageSizes:null,imageSrcSet:null,inert:Y,inputMode:null,integrity:null,is:null,isMap:Y,itemId:null,itemProp:mu,itemRef:mu,itemScope:Y,itemType:mu,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Y,low:X,manifest:null,max:null,maxLength:X,media:null,method:null,min:null,minLength:X,multiple:Y,muted:Y,name:null,nonce:null,noModule:Y,noValidate:Y,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Y,optimum:X,pattern:null,ping:mu,placeholder:null,playsInline:Y,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Y,referrerPolicy:null,rel:mu,required:Y,reversed:Y,rows:X,rowSpan:X,sandbox:mu,scope:null,scoped:Y,seamless:Y,selected:Y,shadowRootClonable:Y,shadowRootCustomElementRegistry:Y,shadowRootDelegatesFocus:Y,shadowRootMode:null,shadowRootSerializable:Y,shape:null,size:X,sizes:null,slot:null,span:X,spellCheck:fu,src:null,srcDoc:null,srcLang:null,srcSet:null,start:X,step:null,style:null,tabIndex:X,target:null,title:null,translate:null,type:null,typeMustMatch:Y,useMap:null,value:fu,width:X,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:mu,axis:null,background:null,bgColor:null,border:X,borderColor:null,bottomMargin:X,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Y,declare:Y,event:null,face:null,frame:null,frameBorder:null,hSpace:X,leftMargin:X,link:null,longDesc:null,lowSrc:null,marginHeight:X,marginWidth:X,noResize:Y,noHref:Y,noShade:Y,noWrap:Y,object:null,profile:null,prompt:null,rev:null,rightMargin:X,rules:null,scheme:null,scrolling:fu,standby:null,summary:null,text:null,topMargin:X,valueType:null,version:null,vAlign:null,vLink:null,vSpace:X,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:Y,disablePictureInPicture:Y,disableRemotePlayback:Y,exportParts:hu,part:mu,prefix:null,property:null,results:X,security:null,unselectable:null},space:`html`,transform:wu}),Eu=xu({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:gu,accentHeight:X,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:X,amplitude:X,arabicForm:null,ascent:X,attributeName:null,attributeType:null,azimuth:X,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:X,by:null,calcMode:null,capHeight:X,className:mu,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:X,diffuseConstant:X,direction:null,display:null,dur:null,divisor:X,dominantBaseline:null,download:Y,dx:null,dy:null,edgeMode:null,editable:null,elevation:X,enableBackground:null,end:null,event:null,exponent:X,externalResourcesRequired:null,fill:null,fillOpacity:X,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:hu,g2:hu,glyphName:hu,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:X,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:X,horizOriginX:X,horizOriginY:X,id:null,ideographic:X,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:X,k:X,k1:X,k2:X,k3:X,k4:X,kernelMatrix:gu,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:X,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:X,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:X,overlineThickness:X,paintOrder:null,panose1:null,path:null,pathLength:X,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:mu,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:X,pointsAtY:X,pointsAtZ:X,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:gu,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:gu,rev:gu,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:gu,requiredFeatures:gu,requiredFonts:gu,requiredFormats:gu,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:X,specularExponent:X,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:X,strikethroughThickness:X,string:null,stroke:null,strokeDashArray:gu,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:X,strokeOpacity:X,strokeWidth:null,style:null,surfaceScale:X,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:gu,tabIndex:X,tableValues:null,target:null,targetX:X,targetY:X,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:gu,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:X,underlineThickness:X,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:X,values:null,vAlphabetic:X,vMathematical:X,vectorEffect:null,vHanging:X,vIdeographic:X,version:null,vertAdvY:X,vertOriginX:X,vertOriginY:X,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:X,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:Cu}),Du=xu({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),Ou=xu({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:wu}),ku=xu({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),Au={classId:`classID`,dataType:`datatype`,itemId:`itemID`,strokeDashArray:`strokeDasharray`,strokeDashOffset:`strokeDashoffset`,strokeLineCap:`strokeLinecap`,strokeLineJoin:`strokeLinejoin`,strokeMiterLimit:`strokeMiterlimit`,typeOf:`typeof`,xLinkActuate:`xlinkActuate`,xLinkArcRole:`xlinkArcrole`,xLinkHref:`xlinkHref`,xLinkRole:`xlinkRole`,xLinkShow:`xlinkShow`,xLinkTitle:`xlinkTitle`,xLinkType:`xlinkType`,xmlnsXLink:`xmlnsXlink`},ju=/[A-Z]/g,Mu=/-[a-z]/g,Nu=/^data[-\w.:]+$/i;function Pu(e,t){let n=cu(t),r=t,i=lu;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&Nu.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(Mu,Iu);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!Mu.test(e)){let n=e.replace(ju,Fu);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=yu}return new i(r,t)}function Fu(e){return`-`+e.toLowerCase()}function Iu(e){return e.charAt(1).toUpperCase()}var Lu=su([Su,Tu,Du,Ou,ku],`html`),Ru=su([Su,Eu,Du,Ou,ku],`svg`);function zu(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function Bu(e){return e.join(` `).trim()}var Vu=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=`
19
19
  `,d=`/`,f=`*`,p=``,m=`comment`,h=`declaration`;function g(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,g=1;function v(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(u);g=~n?e.length-n:g+e.length}function y(){var e={line:l,column:g};return function(t){return t.position=new b(e),C(),t}}function b(e){this.start=e,this.end={line:l,column:g},this.source=t.source}b.prototype.content=e;function x(n){var r=Error(t.source+`:`+l+`:`+g+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=g,r.source=e,!t.silent)throw r}function S(t){var n=t.exec(e);if(n){var r=n[0];return v(r),e=e.slice(r.length),n}}function C(){S(i)}function w(e){var t;for(e||=[];t=T();)t!==!1&&e.push(t);return e}function T(){var t=y();if(!(d!=e.charAt(0)||f!=e.charAt(1))){for(var n=2;p!=e.charAt(n)&&(f!=e.charAt(n)||d!=e.charAt(n+1));)++n;if(n+=2,p===e.charAt(n-1))return x(`End of comment missing`);var r=e.slice(2,n-2);return g+=2,v(r),e=e.slice(n),g+=2,t({type:m,comment:r})}}function E(){var e=y(),t=S(a);if(t){if(T(),!S(o))return x(`property missing ':'`);var r=S(s),i=e({type:h,property:_(t[0].replace(n,p)),value:r?_(r[0].replace(n,p)):p});return S(c),i}}function D(){var e=[];w(e);for(var t;t=E();)t!==!1&&(e.push(t),w(e));return e}return C(),D()}function _(e){return e?e.replace(l,p):p}t.exports=g})),Hu=o((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0}),e.default=r;var n=t(Vu());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),Uu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),Wu=o(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(Hu()),r=Uu();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),Gu=qu(`end`),Ku=qu(`start`);function qu(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function Ju(e){let t=Ku(e),n=Gu(e);if(t&&n)return{start:t,end:n}}function Yu(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Zu(e.position):`start`in e||`end`in e?Zu(e):`line`in e||`column`in e?Xu(e):``}function Xu(e){return Qu(e&&e.line)+`:`+Qu(e&&e.column)}function Zu(e){return Xu(e&&e.start)+`-`+Xu(e&&e.end)}function Qu(e){return e&&typeof e==`number`?e:1}var $u=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=Yu(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};$u.prototype.file=``,$u.prototype.name=``,$u.prototype.reason=``,$u.prototype.message=``,$u.prototype.stack=``,$u.prototype.column=void 0,$u.prototype.line=void 0,$u.prototype.ancestors=void 0,$u.prototype.cause=void 0,$u.prototype.fatal=void 0,$u.prototype.place=void 0,$u.prototype.ruleId=void 0,$u.prototype.source=void 0;var ed=l(Wu(),1),td={}.hasOwnProperty,nd=new Map,rd=/[A-Z]/g,id=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),ad=new Set([`td`,`th`]),od=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function sd(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=vd(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=_d(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?Ru:Lu,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=cd(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function cd(e,t,n){if(t.type===`element`)return ld(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return ud(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return fd(e,t,n);if(t.type===`mdxjsEsm`)return dd(e,t);if(t.type===`root`)return pd(e,t,n);if(t.type===`text`)return md(e,t)}function ld(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=Ru,e.schema=i),e.ancestors.push(t);let a=wd(e,t.tagName,!1),o=yd(e,t),s=xd(e,t);return id.has(t.tagName)&&(s=s.filter(function(e){return typeof e==`string`?!iu(e):!0})),hd(e,o,a,t),gd(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function ud(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}Td(e,t.position)}function dd(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Td(e,t.position)}function fd(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=Ru,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:wd(e,t.name,!0),o=bd(e,t),s=xd(e,t);return hd(e,o,a,t),gd(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function pd(e,t,n){let r={};return gd(r,xd(e,t)),e.create(t,e.Fragment,r,n)}function md(e,t){return t.value}function hd(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function gd(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function _d(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function vd(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=Ku(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function yd(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&td.call(t.properties,i)){let a=Sd(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&ad.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function bd(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`)if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Td(e,t.position);else{let i=r.name,a;if(r.value&&typeof r.value==`object`)if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else Td(e,t.position);else a=r.value===null?!0:r.value;n[i]=a}return n}function xd(e,t){let n=[],r=-1,i=e.passKeys?new Map:nd;for(;++r<t.children.length;){let a=t.children[r],o;if(e.passKeys){let e=a.type===`element`?a.tagName:a.type===`mdxJsxFlowElement`||a.type===`mdxJsxTextElement`?a.name:void 0;if(e){let t=i.get(e)||0;o=e+`-`+t,i.set(e,t+1)}}let s=cd(e,a,o);s!==void 0&&n.push(s)}return n}function Sd(e,t,n){let r=Pu(e.schema,t);if(!(n==null||typeof n==`number`&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Ql(n):Bu(n)),r.property===`style`){let t=typeof n==`object`?n:Cd(e,String(n));return e.stylePropertyNameCase===`css`&&(t=Ed(t)),[`style`,t]}return[e.elementAttributeNameCase===`react`&&r.space?Au[r.property]||r.property:r.attribute,n]}}function Cd(e,t){try{return(0,ed.default)(t,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};let n=t,r=new $u("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:`style`,source:`hast-util-to-jsx-runtime`});throw r.file=e.filePath||void 0,r.url=od+`#cannot-parse-style-attribute`,r}}function wd(e,t,n){let r;if(!n)r={type:`Literal`,value:t};else if(t.includes(`.`)){let e=t.split(`.`),n=-1,i;for(;++n<e.length;){let t=nu(e[n])?{type:`Identifier`,name:e[n]}:{type:`Literal`,value:e[n]};i=i?{type:`MemberExpression`,object:i,property:t,computed:!!(n&&t.type===`Literal`),optional:!1}:t}r=i}else r=nu(t)&&!/^[a-z]/.test(t)?{type:`Identifier`,name:t}:{type:`Literal`,value:t};if(r.type===`Literal`){let t=r.value;return td.call(e.components,t)?e.components[t]:t}if(e.evaluater)return e.evaluater.evaluateExpression(r);Td(e)}function Td(e,t){let n=new $u("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:`mdx-estree`,source:`hast-util-to-jsx-runtime`});throw n.file=e.filePath||void 0,n.url=od+`#cannot-handle-mdx-estrees-without-createevaluater`,n}function Ed(e){let t={},n;for(n in e)td.call(e,n)&&(t[Dd(n)]=e[n]);return t}function Dd(e){let t=e.replace(rd,Od);return t.slice(0,3)===`ms-`&&(t=`-`+t),t}function Od(e){return`-`+e.toLowerCase()}var kd={action:[`form`],cite:[`blockquote`,`del`,`ins`,`q`],data:[`object`],formAction:[`button`,`input`],href:[`a`,`area`,`base`,`link`],icon:[`menuitem`],itemId:null,manifest:[`html`],ping:[`a`,`area`],poster:[`video`],src:[`audio`,`embed`,`iframe`,`img`,`input`,`script`,`source`,`track`,`video`]},Ad={};function jd(e,t){let n=t||Ad;return Md(e,typeof n.includeImageAlt==`boolean`?n.includeImageAlt:!0,typeof n.includeHtml==`boolean`?n.includeHtml:!0)}function Md(e,t,n){if(Pd(e)){if(`value`in e)return e.type===`html`&&!n?``:e.value;if(t&&`alt`in e&&e.alt)return e.alt;if(`children`in e)return Nd(e.children,t,n)}return Array.isArray(e)?Nd(e,t,n):``}function Nd(e,t,n){let r=[],i=-1;for(;++i<e.length;)r[i]=Md(e[i],t,n);return r.join(``)}function Pd(e){return!!(e&&typeof e==`object`)}var Fd=document.createElement(`i`);function Id(e){let t=`&`+e+`;`;Fd.innerHTML=t;let n=Fd.textContent;return n.charCodeAt(n.length-1)===59&&e!==`semi`||n===t?!1:n}function Ld(e,t,n,r){let i=e.length,a=0,o;if(t=t<0?-t>i?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a<r.length;)o=r.slice(a,a+1e4),o.unshift(t,0),e.splice(...o),a+=1e4,t+=1e4}function Rd(e,t){return e.length>0?(Ld(e,e.length,0,t),e):t}var zd={}.hasOwnProperty;function Bd(e){let t={},n=-1;for(;++n<e.length;)Vd(t,e[n]);return t}function Vd(e,t){let n;for(n in t){let r=(zd.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n],a;if(i)for(a in i){zd.call(r,a)||(r[a]=[]);let e=i[a];Hd(r[a],Array.isArray(e)?e:e?[e]:[])}}}function Hd(e,t){let n=-1,r=[];for(;++n<t.length;)(t[n].add===`after`?e:r).push(t[n]);Ld(e,0,0,r)}function Ud(e,t){let n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function Wd(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var Gd=tf(/[A-Za-z]/),Kd=tf(/[\dA-Za-z]/),qd=tf(/[#-'*+\--9=?A-Z^-~]/);function Jd(e){return e!==null&&(e<32||e===127)}var Yd=tf(/\d/),Xd=tf(/[\dA-Fa-f]/),Zd=tf(/[!-/:-@[-`{-~]/);function Z(e){return e!==null&&e<-2}function Qd(e){return e!==null&&(e<0||e===32)}function Q(e){return e===-2||e===-1||e===32}var $d=tf(/\p{P}|\p{S}/u),ef=tf(/\s/);function tf(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function nf(e){let t=[],n=-1,r=0,i=0;for(;++n<e.length;){let a=e.charCodeAt(n),o=``;if(a===37&&Kd(e.charCodeAt(n+1))&&Kd(e.charCodeAt(n+2)))i=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(o=String.fromCharCode(a));else if(a>55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function $(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return Q(r)?(e.enter(n),s(r)):t(r)}function s(r){return Q(r)&&a++<i?(e.consume(r),s):(e.exit(n),t(r))}}var rf={tokenize:af};function af(e){let t=e.attempt(this.parser.constructs.contentInitial,r,i),n;return t;function r(n){if(n===null){e.consume(n);return}return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),$(e,t,`linePrefix`)}function i(t){return e.enter(`paragraph`),a(t)}function a(t){let r=e.enter(`chunkText`,{contentType:`text`,previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){if(t===null){e.exit(`chunkText`),e.exit(`paragraph`),e.consume(t);return}return Z(t)?(e.consume(t),e.exit(`chunkText`),a):(e.consume(t),o)}}var of={tokenize:cf},sf={tokenize:lf};function cf(e){let t=this,n=[],r=0,i,a,o;return s;function s(i){if(r<n.length){let a=n[r];return t.containerState=a[1],e.attempt(a[0].continuation,c,l)(i)}return l(i)}function c(e){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();let n=t.events.length,a=n,o;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){o=t.events[a][1].end;break}_(r);let s=n;for(;s<t.events.length;)t.events[s][1].end={...o},s++;return Ld(t.events,a+1,0,t.events.slice(n)),t.events.length=s,l(e)}return s(e)}function l(a){if(r===n.length){if(!i)return f(a);if(i.currentConstruct&&i.currentConstruct.concrete)return m(a);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(sf,u,d)(a)}function u(e){return i&&v(),_(r),f(e)}function d(e){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,m(e)}function f(n){return t.containerState={},e.attempt(sf,p,m)(n)}function p(e){return r++,n.push([t.currentConstruct,t.containerState]),f(e)}function m(n){if(n===null){i&&v(),_(0),e.consume(n);return}return i||=t.parser.flow(t.now()),e.enter(`chunkFlow`,{_tokenizer:i,contentType:`flow`,previous:a}),h(n)}function h(n){if(n===null){g(e.exit(`chunkFlow`),!0),_(0),e.consume(n);return}return Z(n)?(e.consume(n),g(e.exit(`chunkFlow`)),r=0,t.interrupt=void 0,s):(e.consume(n),h)}function g(e,n){let s=t.sliceStream(e);if(n&&s.push(null),e.previous=a,a&&(a.next=e),a=e,i.defineSkip(e.start),i.write(s),t.parser.lazy[e.start.line]){let e=i.events.length;for(;e--;)if(i.events[e][1].start.offset<o&&(!i.events[e][1].end||i.events[e][1].end.offset>o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;e<t.events.length;)t.events[e][1].end={...c},e++;Ld(t.events,a+1,0,t.events.slice(n)),t.events.length=e}}function _(r){let i=n.length;for(;i-- >r;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function lf(e,t,n){return $(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function uf(e){if(e===null||Qd(e)||ef(e))return 1;if($d(e))return 2}function df(e,t,n){let r=[],i=-1;for(;++i<e.length;){let a=e[i].resolveAll;a&&!r.includes(a)&&(t=a(t,n),r.push(a))}return t}var ff={name:`attention`,resolveAll:pf,tokenize:mf};function pf(e,t){let n=-1,r,i,a,o,s,c,l,u;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`attentionSequence`&&e[n][1]._close){for(r=n;r--;)if(e[r][0]===`exit`&&e[r][1].type===`attentionSequence`&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};hf(d,-c),hf(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=Rd(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=Rd(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=Rd(l,df(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=Rd(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=Rd(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,Ld(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`attentionSequence`&&(e[n][1].type=`data`);return e}function mf(e,t){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=uf(r),a;return o;function o(t){return a=t,e.enter(`attentionSequence`),s(t)}function s(o){if(o===a)return e.consume(o),s;let c=e.exit(`attentionSequence`),l=uf(o),u=!l||l===2&&i||n.includes(o),d=!i||i===2&&l||n.includes(r);return c._open=!!(a===42?u:u&&(i||!d)),c._close=!!(a===42?d:d&&(l||!u)),t(o)}}function hf(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var gf={name:`autolink`,tokenize:_f};function _f(e,t,n){let r=0;return i;function i(t){return e.enter(`autolink`),e.enter(`autolinkMarker`),e.consume(t),e.exit(`autolinkMarker`),e.enter(`autolinkProtocol`),a}function a(t){return Gd(t)?(e.consume(t),o):t===64?n(t):l(t)}function o(e){return e===43||e===45||e===46||Kd(e)?(r=1,s(e)):l(e)}function s(t){return t===58?(e.consume(t),r=0,c):(t===43||t===45||t===46||Kd(t))&&r++<32?(e.consume(t),s):(r=0,l(t))}function c(r){return r===62?(e.exit(`autolinkProtocol`),e.enter(`autolinkMarker`),e.consume(r),e.exit(`autolinkMarker`),e.exit(`autolink`),t):r===null||r===32||r===60||Jd(r)?n(r):(e.consume(r),c)}function l(t){return t===64?(e.consume(t),u):qd(t)?(e.consume(t),l):n(t)}function u(e){return Kd(e)?d(e):n(e)}function d(n){return n===46?(e.consume(n),r=0,u):n===62?(e.exit(`autolinkProtocol`).type=`autolinkEmail`,e.enter(`autolinkMarker`),e.consume(n),e.exit(`autolinkMarker`),e.exit(`autolink`),t):f(n)}function f(t){if((t===45||Kd(t))&&r++<63){let n=t===45?f:d;return e.consume(t),n}return n(t)}}var vf={partial:!0,tokenize:yf};function yf(e,t,n){return r;function r(t){return Q(t)?$(e,i,`linePrefix`)(t):i(t)}function i(e){return e===null||Z(e)?t(e):n(e)}}var bf={continuation:{tokenize:Sf},exit:Cf,name:`blockQuote`,tokenize:xf};function xf(e,t,n){let r=this;return i;function i(t){if(t===62){let n=r.containerState;return n.open||=(e.enter(`blockQuote`,{_container:!0}),!0),e.enter(`blockQuotePrefix`),e.enter(`blockQuoteMarker`),e.consume(t),e.exit(`blockQuoteMarker`),a}return n(t)}function a(n){return Q(n)?(e.enter(`blockQuotePrefixWhitespace`),e.consume(n),e.exit(`blockQuotePrefixWhitespace`),e.exit(`blockQuotePrefix`),t):(e.exit(`blockQuotePrefix`),t(n))}}function Sf(e,t,n){let r=this;return i;function i(t){return Q(t)?$(e,a,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):a(t)}function a(r){return e.attempt(bf,t,n)(r)}}function Cf(e){e.exit(`blockQuote`)}var wf={name:`characterEscape`,tokenize:Tf};function Tf(e,t,n){return r;function r(t){return e.enter(`characterEscape`),e.enter(`escapeMarker`),e.consume(t),e.exit(`escapeMarker`),i}function i(r){return Zd(r)?(e.enter(`characterEscapeValue`),e.consume(r),e.exit(`characterEscapeValue`),e.exit(`characterEscape`),t):n(r)}}var Ef={name:`characterReference`,tokenize:Df};function Df(e,t,n){let r=this,i=0,a,o;return s;function s(t){return e.enter(`characterReference`),e.enter(`characterReferenceMarker`),e.consume(t),e.exit(`characterReferenceMarker`),c}function c(t){return t===35?(e.enter(`characterReferenceMarkerNumeric`),e.consume(t),e.exit(`characterReferenceMarkerNumeric`),l):(e.enter(`characterReferenceValue`),a=31,o=Kd,u(t))}function l(t){return t===88||t===120?(e.enter(`characterReferenceMarkerHexadecimal`),e.consume(t),e.exit(`characterReferenceMarkerHexadecimal`),e.enter(`characterReferenceValue`),a=6,o=Xd,u):(e.enter(`characterReferenceValue`),a=7,o=Yd,u(t))}function u(s){if(s===59&&i){let i=e.exit(`characterReferenceValue`);return o===Kd&&!Id(r.sliceSerialize(i))?n(s):(e.enter(`characterReferenceMarker`),e.consume(s),e.exit(`characterReferenceMarker`),e.exit(`characterReference`),t)}return o(s)&&i++<a?(e.consume(s),u):n(s)}}var Of={partial:!0,tokenize:jf},kf={concrete:!0,name:`codeFenced`,tokenize:Af};function Af(e,t,n){let r=this,i={partial:!0,tokenize:x},a=0,o=0,s;return c;function c(e){return l(e)}function l(t){let n=r.events[r.events.length-1];return a=n&&n[1].type===`linePrefix`?n[2].sliceSerialize(n[1],!0).length:0,s=t,e.enter(`codeFenced`),e.enter(`codeFencedFence`),e.enter(`codeFencedFenceSequence`),u(t)}function u(t){return t===s?(o++,e.consume(t),u):o<3?n(t):(e.exit(`codeFencedFenceSequence`),Q(t)?$(e,d,`whitespace`)(t):d(t))}function d(n){return n===null||Z(n)?(e.exit(`codeFencedFence`),r.interrupt?t(n):e.check(Of,h,b)(n)):(e.enter(`codeFencedFenceInfo`),e.enter(`chunkString`,{contentType:`string`}),f(n))}function f(t){return t===null||Z(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),d(t)):Q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),$(e,p,`whitespace`)(t)):t===96&&t===s?n(t):(e.consume(t),f)}function p(t){return t===null||Z(t)?d(t):(e.enter(`codeFencedFenceMeta`),e.enter(`chunkString`,{contentType:`string`}),m(t))}function m(t){return t===null||Z(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceMeta`),d(t)):t===96&&t===s?n(t):(e.consume(t),m)}function h(t){return e.attempt(i,b,g)(t)}function g(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),_}function _(t){return a>0&&Q(t)?$(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||Z(t)?e.check(Of,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||Z(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),Q(t)?$(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),Q(t)?$(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||Z(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function jf(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var Mf={name:`codeIndented`,tokenize:Pf},Nf={partial:!0,tokenize:Ff};function Pf(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),$(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):Z(t)?e.attempt(Nf,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||Z(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function Ff(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):Z(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):$(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):Z(e)?i(e):n(e)}}var If={name:`codeText`,previous:Rf,resolve:Lf,tokenize:zf};function Lf(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r<t;)if(e[r][1].type===`codeTextData`){e[n][1].type=`codeTextPadding`,e[t][1].type=`codeTextPadding`,n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!==`lineEnding`&&(i=r):(r===t||e[r][1].type===`lineEnding`)&&(e[i][1].type=`codeTextData`,r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function Rf(e){return e!==96||this.events[this.events.length-1][1].type===`characterEscape`}function zf(e,t,n){let r=0,i,a;return o;function o(t){return e.enter(`codeText`),e.enter(`codeTextSequence`),s(t)}function s(t){return t===96?(e.consume(t),r++,s):(e.exit(`codeTextSequence`),c(t))}function c(t){return t===null?n(t):t===32?(e.enter(`space`),e.consume(t),e.exit(`space`),c):t===96?(a=e.enter(`codeTextSequence`),i=0,u(t)):Z(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c):(e.enter(`codeTextData`),l(t))}function l(t){return t===null||t===32||t===96||Z(t)?(e.exit(`codeTextData`),c(t)):(e.consume(t),l)}function u(n){return n===96?(e.consume(n),i++,u):i===r?(e.exit(`codeTextSequence`),e.exit(`codeText`),t(n)):(a.type=`codeTextData`,l(n))}}var Bf=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){let n=t??1/0;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&Vf(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),Vf(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Vf(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let t=this.left.splice(e,1/0);Vf(this.right,t.reverse())}else{let t=this.right.splice(this.left.length+this.right.length-e,1/0);Vf(this.left,t.reverse())}}};function Vf(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Hf(e){let t={},n=-1,r,i,a,o,s,c,l,u=new Bf(e);for(;++n<u.length;){for(;n in t;)n=t[n];if(r=u.get(n),n&&r[1].type===`chunkFlow`&&u.get(n-1)[1].type===`listItemPrefix`&&(c=r[1]._tokenizer.events,a=0,a<c.length&&c[a][1].type===`lineEndingBlank`&&(a+=2),a<c.length&&c[a][1].type===`content`))for(;++a<c.length&&c[a][1].type!==`content`;)c[a][1].type===`chunkText`&&(c[a][1]._isInFirstContentOfListItem=!0,a++);if(r[0]===`enter`)r[1].contentType&&(Object.assign(t,Uf(u,n)),n=t[n],l=!0);else if(r[1]._container){for(a=n,i=void 0;a--;)if(o=u.get(a),o[1].type===`lineEnding`||o[1].type===`lineEndingBlank`)o[0]===`enter`&&(i&&(u.get(i)[1].type=`lineEndingBlank`),o[1].type=`lineEnding`,i=a);else if(!(o[1].type===`linePrefix`||o[1].type===`listItemIndent`))break;i&&(r[1].end={...u.get(i)[1].start},s=u.slice(i,n),s.unshift(r),u.splice(i,n-i+1,s))}}return Ld(e,0,1/0,u.slice(0)),!l}function Uf(e,t){let n=e.get(t)[1],r=e.get(t)[2],i=t-1,a=[],o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));let s=o.events,c=[],l={},u,d,f=-1,p=n,m=0,h=0,g=[h];for(;p;){for(;e.get(++i)[1]!==p;);a.push(i),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),d&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]===`exit`&&s[f-1][0]===`enter`&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(h=f+1,g.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),f=g.length;f--;){let t=s.slice(g[f],g[f+1]),n=a.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),f=-1;++f<c.length;)l[m+c[f][0]]=m+c[f][1],m+=c[f][1]-c[f][0]-1;return l}var Wf={resolve:Kf,tokenize:qf},Gf={partial:!0,tokenize:Jf};function Kf(e){return Hf(e),e}function qf(e,t){let n;return r;function r(t){return e.enter(`content`),n=e.enter(`chunkContent`,{contentType:`content`}),i(t)}function i(t){return t===null?a(t):Z(t)?e.check(Gf,o,a)(t):(e.consume(t),i)}function a(n){return e.exit(`chunkContent`),e.exit(`content`),t(n)}function o(t){return e.consume(t),e.exit(`chunkContent`),n.next=e.enter(`chunkContent`,{contentType:`content`,previous:n}),n=n.next,i}}function Jf(e,t,n){let r=this;return i;function i(t){return e.exit(`chunkContent`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),$(e,a,`linePrefix`)}function a(i){if(i===null||Z(i))return n(i);let a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes(`codeIndented`)&&a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Yf(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||Jd(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||Z(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||Qd(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u<l&&i===40?(e.consume(i),u++,h):i===41?(e.consume(i),u--,h):i===null||i===32||i===40||Jd(i)?n(i):(e.consume(i),i===92?g:h)}function g(t){return t===40||t===41||t===92?(e.consume(t),h):h(t)}}function Xf(e,t,n,r,i,a){let o=this,s=0,c;return l;function l(t){return e.enter(r),e.enter(i),e.consume(t),e.exit(i),e.enter(a),u}function u(l){return s>999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):Z(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||Z(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!Q(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function Zf(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):Z(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),$(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||Z(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function Qf(e,t){let n;return r;function r(i){return Z(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):Q(i)?$(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var $f={name:`definition`,tokenize:tp},ep={partial:!0,tokenize:np};function tp(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return Xf.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=Wd(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return Qd(t)?Qf(e,l)(t):l(t)}function l(t){return Yf(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(ep,d,d)(t)}function d(t){return Q(t)?$(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||Z(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function np(e,t,n){return r;function r(t){return Qd(t)?Qf(e,i)(t):n(t)}function i(t){return Zf(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return Q(t)?$(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||Z(e)?t(e):n(e)}}var rp={name:`hardBreakEscape`,tokenize:ip};function ip(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return Z(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var ap={name:`headingAtx`,resolve:op,tokenize:sp};function op(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},Ld(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function sp(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||Qd(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||Z(n)?(e.exit(`atxHeading`),t(n)):Q(n)?$(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||Qd(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var cp=`address.article.aside.base.basefont.blockquote.body.caption.center.col.colgroup.dd.details.dialog.dir.div.dl.dt.fieldset.figcaption.figure.footer.form.frame.frameset.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),lp=[`pre`,`script`,`style`,`textarea`],up={concrete:!0,name:`htmlFlow`,resolveTo:pp,tokenize:mp},dp={partial:!0,tokenize:gp},fp={partial:!0,tokenize:hp};function pp(e){let t=e.length;for(;t--&&!(e[t][0]===`enter`&&e[t][1].type===`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function mp(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:ee):Gd(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):Gd(a)?(e.consume(a),i=4,r.interrupt?t:ee):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:ee):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return Gd(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||Qd(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&lp.includes(l)?(i=1,r.interrupt?t(s):O(s)):cp.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||Kd(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return Q(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||Gd(t)?(e.consume(t),b):Q(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||Kd(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):Q(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):Q(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||Z(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||Qd(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||Q(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||Z(t)?O(t):Q(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),M):t===60&&i===1?(e.consume(t),N):t===62&&i===4?(e.consume(t),te):t===63&&i===3?(e.consume(t),ee):t===93&&i===5?(e.consume(t),F):Z(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(dp,ne,k)(t)):t===null||Z(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(fp,A,ne)(t)}function A(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),j}function j(t){return t===null||Z(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function M(t){return t===45?(e.consume(t),ee):O(t)}function N(t){return t===47?(e.consume(t),o=``,P):O(t)}function P(t){if(t===62){let n=o.toLowerCase();return lp.includes(n)?(e.consume(t),te):O(t)}return Gd(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),P):O(t)}function F(t){return t===93?(e.consume(t),ee):O(t)}function ee(t){return t===62?(e.consume(t),te):t===45&&i===2?(e.consume(t),ee):O(t)}function te(t){return t===null||Z(t)?(e.exit(`htmlFlowData`),ne(t)):(e.consume(t),te)}function ne(n){return e.exit(`htmlFlow`),t(n)}}function hp(e,t,n){let r=this;return i;function i(t){return Z(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function gp(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(vf,t,n)}}var _p={name:`htmlText`,tokenize:vp};function vp(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):Gd(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):Gd(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):Z(t)?(o=d,N(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?M(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):Z(t)?(o=h,N(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?M(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?M(t):Z(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):Z(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return e===62?M(e):y(e)}function x(t){return Gd(t)?(e.consume(t),S):n(t)}function S(t){return t===45||Kd(t)?(e.consume(t),S):C(t)}function C(t){return Z(t)?(o=C,N(t)):Q(t)?(e.consume(t),C):M(t)}function w(t){return t===45||Kd(t)?(e.consume(t),w):t===47||t===62||Qd(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),M):t===58||t===95||Gd(t)?(e.consume(t),E):Z(t)?(o=T,N(t)):Q(t)?(e.consume(t),T):M(t)}function E(t){return t===45||t===46||t===58||t===95||Kd(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):Z(t)?(o=D,N(t)):Q(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):Z(t)?(o=O,N(t)):Q(t)?(e.consume(t),O):(e.consume(t),A)}function k(t){return t===i?(e.consume(t),i=void 0,j):t===null?n(t):Z(t)?(o=k,N(t)):(e.consume(t),k)}function A(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||Qd(t)?T(t):(e.consume(t),A)}function j(e){return e===47||e===62||Qd(e)?T(e):n(e)}function M(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function N(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),P}function P(t){return Q(t)?$(e,F,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):F(t)}function F(t){return e.enter(`htmlTextData`),o(t)}}var yp={name:`labelEnd`,resolveAll:Cp,resolveTo:wp,tokenize:Tp},bp={tokenize:Ep},xp={tokenize:Dp},Sp={tokenize:Op};function Cp(e){let t=-1,n=[];for(;++t<e.length;){let r=e[t][1];if(n.push(e[t]),r.type===`labelImage`||r.type===`labelLink`||r.type===`labelEnd`){let e=r.type===`labelImage`?4:2;r.type=`data`,t+=e}}return e.length!==n.length&&Ld(e,0,e.length,n),e}function wp(e,t){let n=e.length,r=0,i,a,o,s;for(;n--;)if(i=e[n][1],a){if(i.type===`link`||i.type===`labelLink`&&i._inactive)break;e[n][0]===`enter`&&i.type===`labelLink`&&(i._inactive=!0)}else if(o){if(e[n][0]===`enter`&&(i.type===`labelImage`||i.type===`labelLink`)&&!i._balanced&&(a=n,i.type!==`labelLink`)){r=2;break}}else i.type===`labelEnd`&&(o=n);let c={type:e[a][1].type===`labelLink`?`link`:`image`,start:{...e[a][1].start},end:{...e[e.length-1][1].end}},l={type:`label`,start:{...e[a][1].start},end:{...e[o][1].end}},u={type:`labelText`,start:{...e[a+r+2][1].end},end:{...e[o-2][1].start}};return s=[[`enter`,c,t],[`enter`,l,t]],s=Rd(s,e.slice(a+1,a+r+3)),s=Rd(s,[[`enter`,u,t]]),s=Rd(s,df(t.parser.constructs.insideSpan.null,e.slice(a+r+4,o-3),t)),s=Rd(s,[[`exit`,u,t],e[o-2],e[o-1],[`exit`,l,t]]),s=Rd(s,e.slice(o+1)),s=Rd(s,[[`exit`,c,t]]),Ld(e,a,e.length,s),e}function Tp(e,t,n){let r=this,i=r.events.length,a,o;for(;i--;)if((r.events[i][1].type===`labelImage`||r.events[i][1].type===`labelLink`)&&!r.events[i][1]._balanced){a=r.events[i][1];break}return s;function s(t){return a?a._inactive?d(t):(o=r.parser.defined.includes(Wd(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter(`labelEnd`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelEnd`),c):n(t)}function c(t){return t===40?e.attempt(bp,u,o?u:d)(t):t===91?e.attempt(xp,u,o?l:d)(t):o?u(t):d(t)}function l(t){return e.attempt(Sp,u,d)(t)}function u(e){return t(e)}function d(e){return a._balanced=!0,n(e)}}function Ep(e,t,n){return r;function r(t){return e.enter(`resource`),e.enter(`resourceMarker`),e.consume(t),e.exit(`resourceMarker`),i}function i(t){return Qd(t)?Qf(e,a)(t):a(t)}function a(t){return t===41?u(t):Yf(e,o,s,`resourceDestination`,`resourceDestinationLiteral`,`resourceDestinationLiteralMarker`,`resourceDestinationRaw`,`resourceDestinationString`,32)(t)}function o(t){return Qd(t)?Qf(e,c)(t):u(t)}function s(e){return n(e)}function c(t){return t===34||t===39||t===40?Zf(e,l,n,`resourceTitle`,`resourceTitleMarker`,`resourceTitleString`)(t):u(t)}function l(t){return Qd(t)?Qf(e,u)(t):u(t)}function u(r){return r===41?(e.enter(`resourceMarker`),e.consume(r),e.exit(`resourceMarker`),e.exit(`resource`),t):n(r)}}function Dp(e,t,n){let r=this;return i;function i(t){return Xf.call(r,e,a,o,`reference`,`referenceMarker`,`referenceString`)(t)}function a(e){return r.parser.defined.includes(Wd(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function o(e){return n(e)}}function Op(e,t,n){return r;function r(t){return e.enter(`reference`),e.enter(`referenceMarker`),e.consume(t),e.exit(`referenceMarker`),i}function i(r){return r===93?(e.enter(`referenceMarker`),e.consume(r),e.exit(`referenceMarker`),e.exit(`reference`),t):n(r)}}var kp={name:`labelStartImage`,resolveAll:yp.resolveAll,tokenize:Ap};function Ap(e,t,n){let r=this;return i;function i(t){return e.enter(`labelImage`),e.enter(`labelImageMarker`),e.consume(t),e.exit(`labelImageMarker`),a}function a(t){return t===91?(e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelImage`),o):n(t)}function o(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var jp={name:`labelStartLink`,resolveAll:yp.resolveAll,tokenize:Mp};function Mp(e,t,n){let r=this;return i;function i(t){return e.enter(`labelLink`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelLink`),a}function a(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var Np={name:`lineEnding`,tokenize:Pp};function Pp(e,t){return n;function n(n){return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),$(e,t,`linePrefix`)}}var Fp={name:`thematicBreak`,tokenize:Ip};function Ip(e,t,n){let r=0,i;return a;function a(t){return e.enter(`thematicBreak`),o(t)}function o(e){return i=e,s(e)}function s(a){return a===i?(e.enter(`thematicBreakSequence`),c(a)):r>=3&&(a===null||Z(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),Q(t)?$(e,s,`whitespace`)(t):s(t))}}var Lp={continuation:{tokenize:Vp},exit:Up,name:`list`,tokenize:Bp},Rp={partial:!0,tokenize:Wp},zp={partial:!0,tokenize:Hp};function Bp(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:Yd(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(Fp,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return Yd(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(vf,r.interrupt?n:u,e.attempt(Rp,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return Q(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function Vp(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(vf,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,$(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!Q(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(zp,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,$(e,e.attempt(Lp,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function Hp(e,t,n){let r=this;return $(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function Up(e){e.exit(this.containerState.type)}function Wp(e,t,n){let r=this;return $(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!Q(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var Gp={name:`setextUnderline`,resolveTo:Kp,tokenize:qp};function Kp(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function qp(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),Q(t)?$(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||Z(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var Jp={tokenize:Yp};function Yp(e){let t=this,n=e.attempt(vf,r,e.attempt(this.parser.constructs.flowInitial,i,$(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Wf,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var Xp={resolveAll:em()},Zp=$p(`string`),Qp=$p(`text`);function $p(e){return{resolveAll:em(e===`text`?tm:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++i<t.length;){let e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}function em(e){return t;function t(t,n){let r=-1,i;for(;++r<=t.length;)i===void 0?t[r]&&t[r][1].type===`data`&&(i=r,r++):(!t[r]||t[r][1].type!==`data`)&&(r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(t,n):t}}function tm(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type===`lineEnding`)&&e[n-1][1].type===`data`){let r=e[n-1][1],i=t.sliceStream(r),a=i.length,o=-1,s=0,c;for(;a--;){let e=i[a];if(typeof e==`string`){for(o=e.length;e.charCodeAt(o-1)===32;)s++,o--;if(o)break;o=-1}else if(e===-2)c=!0,s++;else if(e!==-1){a++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){let i={type:n===e.length||c||s<2?`lineSuffix`:`hardBreakTrailing`,start:{_bufferIndex:a?o:r.start._bufferIndex+o,_index:r.start._index+a,line:r.end.line,column:r.end.column-s,offset:r.end.offset-s},end:{...r.end}};r.end={...i.start},r.start.offset===r.end.offset?Object.assign(r,i):(e.splice(n,0,[`enter`,i,t],[`exit`,i,t]),n+=2)}n++}return e}var nm=s({attentionMarkers:()=>um,contentInitial:()=>im,disable:()=>dm,document:()=>rm,flow:()=>om,flowInitial:()=>am,insideSpan:()=>lm,string:()=>sm,text:()=>cm}),rm={42:Lp,43:Lp,45:Lp,48:Lp,49:Lp,50:Lp,51:Lp,52:Lp,53:Lp,54:Lp,55:Lp,56:Lp,57:Lp,62:bf},im={91:$f},am={[-2]:Mf,[-1]:Mf,32:Mf},om={35:ap,42:Fp,45:[Gp,Fp],60:up,61:Gp,95:Fp,96:kf,126:kf},sm={38:Ef,92:wf},cm={[-5]:Np,[-4]:Np,[-3]:Np,33:kp,38:Ef,42:ff,60:[gf,_p],91:jp,92:[rp,wf],93:yp,95:ff,96:If},lm={null:[ff,Xp]},um={null:[42,95]},dm={null:[]};function fm(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=Rd(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=df(a,l.events,l),l.events):[]}function f(e,t){return mm(p(e),t)}function p(e){return pm(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index<o.length;){let t=o[r._index];if(typeof t==`string`)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)_(t.charCodeAt(r._bufferIndex));else _(t)}}function _(e){u=u(e)}function v(e){Z(e)?(r.line++,r.column=1,r.offset+=e===-3?2:1,E()):e!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),l.previous=e}function y(e,t){let n=t||{};return n.type=e,n.start=m(),l.events.push([`enter`,n,l]),s.push(n),n}function b(e){let t=s.pop();return t.end=m(),l.events.push([`exit`,t,l]),t}function x(e,t){w(e,t.from)}function S(e,t){t.restore()}function C(e,t){return n;function n(n,r,i){let a,o,s,u;return Array.isArray(n)?f(n):`tokenize`in n?f([n]):d(n);function d(e){return t;function t(t){let n=t!==null&&e[t],r=t!==null&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(r)?r:r?[r]:[]])(t)}}function f(e){return a=e,o=0,e.length===0?i:p(e[o])}function p(e){return n;function n(n){return u=T(),s=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?h(n):e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,m,h)(n)}}function m(t){return e(s,u),r}function h(e){return u.restore(),++o<a.length?p(a[o]):i}}}function w(e,t){e.resolveAll&&!a.includes(e)&&a.push(e),e.resolve&&Ld(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function T(){let e=m(),t=l.previous,n=l.currentConstruct,i=l.events.length,a=Array.from(s);return{from:i,restore:o};function o(){r=e,l.previous=t,l.currentConstruct=n,l.events.length=i,s=a,E()}}function E(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function pm(e,t){let n=t.start._index,r=t.start._bufferIndex,i=t.end._index,a=t.end._bufferIndex,o;if(n===i)o=[e[n].slice(r,a)];else{if(o=e.slice(n,i),r>-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function mm(e,t){let n=-1,r=[],i;for(;++n<e.length;){let a=e[n],o;if(typeof a==`string`)o=a;else switch(a){case-5:o=`\r`;break;case-4:o=`
20
20
  `;break;case-3:o=`\r
21
21
  `;break;case-2:o=t?` `:` `;break;case-1:if(!t&&i)continue;o=` `;break;default:o=String.fromCharCode(a)}i=a===-2,r.push(o)}return r.join(``)}function hm(e){let t={constructs:Bd([nm,...(e||{}).extensions||[]]),content:n(rf),defined:[],document:n(of),flow:n(Jp),lazy:{},string:n(Zp),text:n(Qp)};return t;function n(e){return n;function n(n){return fm(t,e,n)}}}function gm(e){for(;!Hf(e););return e}var _m=/[\0\t\n\r]/g;function vm(){let e=1,t=``,n=!0,r;return i;function i(i,a,o){let s=[],c,l,u,d,f;for(i=t+(typeof i==`string`?i.toString():new TextDecoder(a||void 0).decode(i)),u=0,t=``,n&&=(i.charCodeAt(0)===65279&&u++,void 0);u<i.length;){if(_m.lastIndex=u,c=_m.exec(i),d=c&&c.index!==void 0?c.index:i.length,f=i.charCodeAt(d),!c){t=i.slice(u);break}if(f===10&&u===d&&r)s.push(-3),r=void 0;else switch(r&&=(s.push(-5),void 0),u<d&&(s.push(i.slice(u,d)),e+=d-u),f){case 0:s.push(65533),e++;break;case 9:for(l=Math.ceil(e/4)*4,s.push(-2);e++<l;)s.push(-1);break;case 10:s.push(-4),e=1;break;default:r=!0,e=1}u=d+1}return o&&(r&&s.push(-5),t&&s.push(t),s.push(null)),s}}var ym=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function bm(e){return e.replace(ym,xm)}function xm(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){let e=n.charCodeAt(1),t=e===120||e===88;return Ud(n.slice(t?2:1),t?16:10)}return Id(n)||e}var Sm={}.hasOwnProperty;function Cm(e,t,n){return t&&typeof t==`object`&&(n=t,t=void 0),wm(n)(gm(hm(n).document().write(vm()(e,t,!0))))}function wm(e){let t={transforms:[],canContainEols:[`emphasis`,`fragment`,`heading`,`paragraph`,`strong`],enter:{autolink:a(ge),autolinkProtocol:T,autolinkEmail:T,atxHeading:a(fe),blockQuote:a(ce),characterEscape:T,characterReference:T,codeFenced:a(le),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:a(le,o),codeText:a(ue,o),codeTextData:T,data:T,codeFlowValue:T,definition:a(de),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:a(R),hardBreakEscape:a(pe),hardBreakTrailing:a(pe),htmlFlow:a(me,o),htmlFlowData:T,htmlText:a(me,o),htmlTextData:T,image:a(he),label:o,link:a(ge),listItem:a(ve),listItemValue:f,listOrdered:a(_e,d),listUnordered:a(_e),paragraph:a(ye),reference:I,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:a(fe),strong:a(be),thematicBreak:a(Se)},exit:{atxHeading:c(),atxHeadingSequence:x,autolink:c(),autolinkEmail:L,autolinkProtocol:se,blockQuote:c(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:ie,characterReferenceMarkerNumeric:ie,characterReferenceValue:ae,characterReference:oe,codeFenced:c(g),codeFencedFence:h,codeFencedFenceInfo:p,codeFencedFenceMeta:m,codeFlowValue:E,codeIndented:c(_),codeText:c(j),codeTextData:E,data:E,definition:c(),definitionDestinationString:b,definitionLabelString:v,definitionTitleString:y,emphasis:c(),hardBreakEscape:c(O),hardBreakTrailing:c(O),htmlFlow:c(k),htmlFlowData:E,htmlText:c(A),htmlTextData:E,image:c(N),label:F,labelText:P,lineEnding:D,link:c(M),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:re,resourceDestinationString:ee,resourceTitleString:te,resource:ne,setextHeading:c(w),setextHeadingLineSequence:C,setextHeadingText:S,strong:c(),thematicBreak:c()}};Em(t,(e||{}).mdastExtensions||[]);let n={};return r;function r(e){let r={type:`root`,children:[]},a={stack:[r],tokenStack:[],config:t,enter:s,exit:l,buffer:o,resume:u,data:n},c=[],d=-1;for(;++d<e.length;)(e[d][1].type===`listOrdered`||e[d][1].type===`listUnordered`)&&(e[d][0]===`enter`?c.push(d):d=i(e,c.pop(),d));for(d=-1;++d<e.length;){let n=t[e[d][0]];Sm.call(n,e[d][1].type)&&n[e[d][1].type].call(Object.assign({sliceSerialize:e[d][2].sliceSerialize},a),e[d][1])}if(a.tokenStack.length>0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||Om).call(a,void 0,e[0])}for(r.position={start:Tm(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Tm(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d<t.transforms.length;)r=t.transforms[d](r)||r;return r}function i(e,t,n){let r=t-1,i=-1,a=!1,o,s,c,l;for(;++r<=n;){let t=e[r];switch(t[1].type){case`listUnordered`:case`listOrdered`:case`blockQuote`:t[0]===`enter`?i++:i--,l=void 0;break;case`lineEndingBlank`:t[0]===`enter`&&(o&&!l&&!i&&!c&&(c=r),l=void 0);break;case`linePrefix`:case`listItemValue`:case`listItemMarker`:case`listItemPrefix`:case`listItemPrefixWhitespace`:break;default:l=void 0}if(!i&&t[0]===`enter`&&t[1].type===`listItemPrefix`||i===-1&&t[0]===`exit`&&(t[1].type===`listUnordered`||t[1].type===`listOrdered`)){if(o){let i=r;for(s=void 0;i--;){let t=e[i];if(t[1].type===`lineEnding`||t[1].type===`lineEndingBlank`){if(t[0]===`exit`)continue;s&&(e[s][1].type=`lineEndingBlank`,a=!0),t[1].type=`lineEnding`,s=i}else if(!(t[1].type===`linePrefix`||t[1].type===`blockQuotePrefix`||t[1].type===`blockQuotePrefixWhitespace`||t[1].type===`blockQuoteMarker`||t[1].type===`listItemIndent`))break}c&&(!s||c<s)&&(o._spread=!0),o.end=Object.assign({},s?e[s][1].start:t[1].end),e.splice(s||r,0,[`exit`,o,t[2]]),r++,n++}if(t[1].type===`listItemPrefix`){let i={type:`listItem`,_spread:!1,start:Object.assign({},t[1].start),end:void 0};o=i,e.splice(r,0,[`enter`,i,t[2]]),r++,n++,c=void 0,l=!0}}}return e[t][1]._spread=a,n}function a(e,t){return n;function n(n){s.call(this,e(n),n),t&&t.call(this,n)}}function o(){this.stack.push({type:`fragment`,children:[]})}function s(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:Tm(t.start),end:void 0}}function c(e){return t;function t(t){e&&e.call(this,t),l.call(this,t)}}function l(e,t){let n=this.stack.pop(),r=this.tokenStack.pop();if(r)r[0].type!==e.type&&(t?t.call(this,e,r[0]):(r[1]||Om).call(this,e,r[0]));else throw Error("Cannot close `"+e.type+"` ("+Yu({start:e.start,end:e.end})+`): it’s not open`);n.position.end=Tm(e.end)}function u(){return jd(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(e){if(this.data.expectingFirstListItemValue){let t=this.stack[this.stack.length-2];t.start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0}}function p(){let e=this.resume(),t=this.stack[this.stack.length-1];t.lang=e}function m(){let e=this.resume(),t=this.stack[this.stack.length-1];t.meta=e}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``),this.data.flowCodeInside=void 0}function _(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/(\r?\n|\r)$/g,``)}function v(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Wd(this.sliceSerialize(e)).toLowerCase()}function y(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function b(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function x(e){let t=this.stack[this.stack.length-1];t.depth||=this.sliceSerialize(e).length}function S(){this.data.setextHeadingSlurpLineEnding=!0}function C(e){let t=this.stack[this.stack.length-1];t.depth=this.sliceSerialize(e).codePointAt(0)===61?1:2}function w(){this.data.setextHeadingSlurpLineEnding=void 0}function T(e){let t=this.stack[this.stack.length-1].children,n=t[t.length-1];(!n||n.type!==`text`)&&(n=xe(),n.position={start:Tm(e.start),end:void 0},t.push(n)),this.stack.push(n)}function E(e){let t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=Tm(e.end)}function D(e){let n=this.stack[this.stack.length-1];if(this.data.atHardBreak){let t=n.children[n.children.length-1];t.position.end=Tm(e.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(T.call(this,e),E.call(this,e))}function O(){this.data.atHardBreak=!0}function k(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function A(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function j(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function M(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function N(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function P(e){let t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=bm(t),n.identifier=Wd(t).toLowerCase()}function F(){let e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];this.data.inReference=!0,n.type===`link`?n.children=e.children:n.alt=t}function ee(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function te(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function ne(){this.data.inReference=void 0}function I(){this.data.referenceType=`collapsed`}function re(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Wd(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType=`full`}function ie(e){this.data.characterReferenceType=e.type}function ae(e){let t=this.sliceSerialize(e),n=this.data.characterReferenceType,r;n?(r=Ud(t,n===`characterReferenceMarkerNumeric`?10:16),this.data.characterReferenceType=void 0):r=Id(t);let i=this.stack[this.stack.length-1];i.value+=r}function oe(e){let t=this.stack.pop();t.position.end=Tm(e.end)}function se(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=this.sliceSerialize(e)}function L(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=`mailto:`+this.sliceSerialize(e)}function ce(){return{type:`blockquote`,children:[]}}function le(){return{type:`code`,lang:null,meta:null,value:``}}function ue(){return{type:`inlineCode`,value:``}}function de(){return{type:`definition`,identifier:``,label:null,title:null,url:``}}function R(){return{type:`emphasis`,children:[]}}function fe(){return{type:`heading`,depth:0,children:[]}}function pe(){return{type:`break`}}function me(){return{type:`html`,value:``}}function he(){return{type:`image`,title:null,url:``,alt:null}}function ge(){return{type:`link`,title:null,url:``,children:[]}}function _e(e){return{type:`list`,ordered:e.type===`listOrdered`,start:null,spread:e._spread,children:[]}}function ve(e){return{type:`listItem`,spread:e._spread,checked:null,children:[]}}function ye(){return{type:`paragraph`,children:[]}}function be(){return{type:`strong`,children:[]}}function xe(){return{type:`text`,value:``}}function Se(){return{type:`thematicBreak`}}}function Tm(e){return{line:e.line,column:e.column,offset:e.offset}}function Em(e,t){let n=-1;for(;++n<t.length;){let r=t[n];Array.isArray(r)?Em(e,r):Dm(e,r)}}function Dm(e,t){let n;for(n in t)if(Sm.call(t,n))switch(n){case`canContainEols`:{let r=t[n];r&&e[n].push(...r);break}case`transforms`:{let r=t[n];r&&e[n].push(...r);break}case`enter`:case`exit`:{let r=t[n];r&&Object.assign(e[n],r);break}}}function Om(e,t){throw Error(e?"Cannot close `"+e.type+"` ("+Yu({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Yu({start:t.start,end:t.end})+`) is open`:"Cannot close document, a token (`"+t.type+"`, "+Yu({start:t.start,end:t.end})+`) is still open`)}function km(e){let t=this;t.parser=n;function n(n){return Cm(n,{...t.data(`settings`),...e,extensions:t.data(`micromarkExtensions`)||[],mdastExtensions:t.data(`fromMarkdownExtensions`)||[]})}}function Am(e,t){let n={type:`element`,tagName:`blockquote`,properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function jm(e,t){let n={type:`element`,tagName:`br`,properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:`text`,value:`