@ipv9/tokentracker-cli 0.39.48 → 0.39.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +11 -9
  2. package/dashboard/dist/assets/{Card-CQ0G1GlR.js → Card-G3yjiaQ3.js} +1 -1
  3. package/dashboard/dist/assets/{DashboardPage-B5aBShIc.js → DashboardPage-p9US1mNh.js} +1 -1
  4. package/dashboard/dist/assets/{FadeIn-BG37Pb1J.js → FadeIn-Bcqp5CE1.js} +1 -1
  5. package/dashboard/dist/assets/{IpCheckPage-DD2nObWJ.js → IpCheckPage-DsTJ2UMw.js} +1 -1
  6. package/dashboard/dist/assets/{LimitsPage-L55ZcbUp.js → LimitsPage-Dh7MA0MN.js} +1 -1
  7. package/dashboard/dist/assets/{LocalOnlyNotice-3-SG-oKl.js → LocalOnlyNotice-TF43yZEk.js} +1 -1
  8. package/dashboard/dist/assets/{PopoverPopup--Imnw4O7.js → PopoverPopup-BTJTO2ZT.js} +1 -1
  9. package/dashboard/dist/assets/{Select-BNQ73B60.js → Select-_DHMSUO0.js} +1 -1
  10. package/dashboard/dist/assets/{SelectItemText-Dlv4NEpN.js → SelectItemText-CFGxP_cw.js} +1 -1
  11. package/dashboard/dist/assets/{SettingsPage-BDo6aFgs.js → SettingsPage-CbHgbVTV.js} +1 -1
  12. package/dashboard/dist/assets/{SkillsPage-CA2IaWI5.js → SkillsPage-Pbf_dSEd.js} +1 -1
  13. package/dashboard/dist/assets/{WidgetsPage-DTVOLZEy.js → WidgetsPage-DdncxT2a.js} +1 -1
  14. package/dashboard/dist/assets/{WrappedPage-CYwBaHuQ.js → WrappedPage-D1BDK0Ph.js} +1 -1
  15. package/dashboard/dist/assets/{arrow-up-right-3x5AJIbb.js → arrow-up-right-BAE7-yZI.js} +1 -1
  16. package/dashboard/dist/assets/{download-DSegD216.js → download-CwfCmvh_.js} +1 -1
  17. package/dashboard/dist/assets/{format-yTFTff0D.js → format-C3ekCmoV.js} +1 -1
  18. package/dashboard/dist/assets/{limitDisplay-DxvqWNgp.js → limitDisplay-DhC8fM_W.js} +1 -1
  19. package/dashboard/dist/assets/{main-DBDTVhz8.js → main-rZD26_5f.js} +12 -24
  20. package/dashboard/dist/assets/{mock-data-oSiCcgVh.js → mock-data-C1NPjE59.js} +1 -1
  21. package/dashboard/dist/assets/{use-limits-display-prefs-C2F0IlsU.js → use-limits-display-prefs-vLrVb6Bn.js} +1 -1
  22. package/dashboard/dist/assets/{use-native-settings-DtQFof4g.js → use-native-settings-B8qCQ9aO.js} +1 -1
  23. package/dashboard/dist/assets/{useCurrency-5LxVaA8B.js → useCurrency-MOYNpGd7.js} +1 -1
  24. package/dashboard/dist/index.html +13 -11
  25. package/dashboard/dist/llms.txt +1 -1
  26. package/package.json +2 -2
  27. package/src/cli.js +1 -1
  28. package/src/commands/init.js +5 -7
  29. package/src/lib/pricing/seed-snapshot.json +1 -1
package/README.md CHANGED
@@ -78,7 +78,7 @@ Both bundle their own Node runtime, so there is nothing else to install. They sh
78
78
 
79
79
  ## ✨ What you get
80
80
 
81
- - 🔒 **Your usage data never leaves your machine.** Token counts and timestamps only never prompts, responses, or file contents. No account, no telemetry, no analytics, no phone-home. TokenTracker does make a few outbound calls *on your behalf* (model prices, your own plan quotas); every one is named in [Privacy](#-privacy) below, and none of them carry your usage.
81
+ - 🔒 **Your usage data never leaves your machine.** Usage metadata only — source, model, token and conversation counts, timestamps, and derived cost; never prompts, responses, message bodies, or private user-code paths. No account, no telemetry, no analytics, no phone-home. TokenTracker does make documented outbound calls *on your behalf* (for example model prices, provider authentication/quotas, and opt-in tools); none upload token-usage metadata.
82
82
  - 📊 **One calm web dashboard.** Your whole picture in the browser at a local URL, no login — light or dark, auto-refreshing while the tab is open. [What's on it ↓](#-the-dashboard)
83
83
  - 📈 **Quota at a glance, on every card.** Live plan-quota usage (e.g. 5h + weekly) as color-coded chips right on each provider's card — see how close you are to your limits without leaving the overview. Where the provider reports countable units you get the actual number rather than a percentage to convert in your head: GitHub Copilot reads `158/300` premium requests. Full windows + reset countdowns on the Limits page. Covers Claude, Codex, Cursor, Gemini, Kimi, Z.AI, Kiro, Copilot, and Antigravity.
84
84
  - 💰 **Cost you can trust — and a price tag when it can't.** 2,200+ models priced from [LiteLLM](https://github.com/BerriAI/litellm) (refreshed daily) with a bundled offline snapshot, so USD totals are right even without a network. A model too new to have a price is badged **pricing missing** rather than quietly counted as $0, and prices refresh in the background instead of waiting for a restart. Cross-provider records are de-duplicated to match each provider's own billing.
@@ -122,14 +122,14 @@ Rate-limit providers are auto-detected where possible. For Z.AI / GLM Coding Pla
122
122
  ## 🧩 How it works
123
123
 
124
124
  ```
125
- AI CLI tools → hooks / passive readers → local queue file → dashboard
126
- (logs) (token counts only) (30-min buckets) (your browser)
125
+ AI CLI tools → hooks / passive readers → local queue files → dashboard
126
+ (logs) (usage metadata) (30-min buckets) (your browser)
127
127
  ```
128
128
 
129
129
  1. Your AI tools write logs during normal use.
130
- 2. Lightweight hooks (or passive file readers) pick up token counts locally — never prompt or response content. Some tools keep their logs in SQLite (Cursor, Kiro, Zed and friends); TokenTracker only ever *reads* those.
131
- 3. Counts are aggregated into 30-minute UTC buckets and appended to one plain-text file: `~/.tokentracker/tracker/queue.jsonl`.
132
- 4. The dashboard reads that file and renders it in your browser's timezone.
130
+ 2. Lightweight hooks and passive readers parse tool logs locally, then retain only approved usage metadata — never prompts or response content. Some tools keep their logs in SQLite (Cursor, Kiro, Zed and friends); TokenTracker reads those databases without modifying them.
131
+ 3. Counts are aggregated into 30-minute UTC buckets and appended to `~/.tokentracker/tracker/queue.jsonl`; per-project counts and local project identifiers are also written to `~/.tokentracker/tracker/project.queue.jsonl`.
132
+ 4. The dashboard reads those local queues, derives cost, renders in your browser's timezone, and may cache usage summaries and daily rows in browser localStorage.
133
133
 
134
134
  No account, no upload of your usage, and no server to sign in to.
135
135
 
@@ -139,11 +139,13 @@ No account, no upload of your usage, and no server to sign in to.
139
139
 
140
140
  | Protection | What it means |
141
141
  |---|---|
142
- | **No content** | Only token counts and timestamps. Never prompts, responses, or files. |
143
- | **Your usage stays local** | Every count TokenTracker collects is written to one file on your disk and read back by a server on your own machine. There is no endpoint it uploads usage to. |
144
- | **Auditable in one command** | You don't have to take our word for it the store is an append-only text file you can open yourself: `cat ~/.tokentracker/tracker/queue.jsonl`. It's numbers and timestamps. |
142
+ | **Usage metadata only** | Source, model, token and conversation counts, timestamps, and derived cost. Never prompts, responses, message bodies, or private user-code paths. |
143
+ | **Your usage stays local** | Usage rows stay in `queue.jsonl` and `project.queue.jsonl`; derived summaries may also be cached in browser localStorage. No TokenTracker endpoint uploads usage. |
144
+ | **Auditable locally** | Inspect both queue files with `cat ~/.tokentracker/tracker/{queue.jsonl,project.queue.jsonl}` and inspect optional browser localStorage caches in your browser's developer tools. The project queue includes local project identifiers. |
145
145
  | **No telemetry** | No analytics, no crash reporting, no phone-home, no account. |
146
146
 
147
+ Credentials are used only for declared provider authentication or quota flows and their credential files; never place them in TokenTracker queues, logs, fixtures, diagnostics, API responses, or unrelated outbound payloads.
148
+
147
149
  **Outbound calls.** TokenTracker is local-first, not network-free. It reaches these hosts and no others. None of them carry your usage data — but some do reveal that *you* are asking, so they are listed with who makes the call.
148
150
 
149
151
  This table is checked in CI against [`outbound-hosts.json`](outbound-hosts.json): a host the code can reach but the file does not declare fails the build, and so does a declared host missing from this table. It is not maintained by memory.
@@ -1 +1 @@
1
- import{j as r}from"./main-DBDTVhz8.js";function t({children:i,title:a,subtitle:o,className:s="",bodyClassName:d=""}){return r.jsxs("div",{className:`rounded-xl border border-oai-gray-200 dark:border-oai-gray-800 bg-white dark:bg-oai-gray-900 transition-colors duration-200 ${s}`,children:[(a||o)&&r.jsxs("div",{className:"px-5 py-4 border-b border-oai-gray-200 dark:border-oai-gray-800 transition-colors duration-200",children:[a&&r.jsx("h3",{className:"text-sm font-medium text-oai-gray-500 dark:text-oai-gray-300 uppercase tracking-wide transition-colors duration-200",children:a}),o&&r.jsx("p",{className:"text-sm text-oai-gray-500 dark:text-oai-gray-300 mt-1 transition-colors duration-200",children:o})]}),r.jsx("div",{className:`p-5 ${d}`,children:i})]})}export{t as C};
1
+ import{j as r}from"./main-rZD26_5f.js";function t({children:i,title:a,subtitle:o,className:s="",bodyClassName:d=""}){return r.jsxs("div",{className:`rounded-xl border border-oai-gray-200 dark:border-oai-gray-800 bg-white dark:bg-oai-gray-900 transition-colors duration-200 ${s}`,children:[(a||o)&&r.jsxs("div",{className:"px-5 py-4 border-b border-oai-gray-200 dark:border-oai-gray-800 transition-colors duration-200",children:[a&&r.jsx("h3",{className:"text-sm font-medium text-oai-gray-500 dark:text-oai-gray-300 uppercase tracking-wide transition-colors duration-200",children:a}),o&&r.jsx("p",{className:"text-sm text-oai-gray-500 dark:text-oai-gray-300 mt-1 transition-colors duration-200",children:o})]}),r.jsx("div",{className:`p-5 ${d}`,children:i})]})}export{t as C};
@@ -1,4 +1,4 @@
1
- import{c as rn,i as oi,f as Ur,a as Vr,J as si,u as qr,m as ii,r as h,M as Xr,b as li,d as ci,e as Fn,j as o,L as di,g as ui,h as fi,k as mi,l as hi,n as zt,o as gt,p as y,q as Gr,X as da,s as gi,R,t as ua,C as Kr,P as fa,B as Jn,v as Qr,w as Jr,A as Zr,x as Xe,y as yi,z as pi,D as bi,E as xi,F as ki}from"./main-DBDTVhz8.js";import{g as wi,i as Yt,b as Zn,c as pn,a as on,d as tn,f as ht,e as eo,h as to,j as vi,k as Ni,l as _i,m as Mi}from"./mock-data-oSiCcgVh.js";import{g as ji,a as Cn,b as Si,c as Ci,d as no,e as Rn,f as Di,h as Ti,L as Pi,i as Oi,j as $i,u as Ei,t as Ua}from"./limitDisplay-DxvqWNgp.js";import{u as Wi}from"./use-limits-display-prefs-C2F0IlsU.js";import{u as _t,I as ma}from"./useCurrency-5LxVaA8B.js";import{t as Le,f as et,a as Ae,b as Qe}from"./format-yTFTff0D.js";import{u as Ai,D as Fi,a as Ri,b as Ii,c as Li,d as zi,e as Yi,P as ea,f as ta,g as na,h as aa,i as ra,L as Bi}from"./PopoverPopup--Imnw4O7.js";import{C as sn}from"./Card-CQ0G1GlR.js";import{S as Hi}from"./Select-BNQ73B60.js";import{F as ct}from"./FadeIn-BG37Pb1J.js";import"./SelectItemText-Dlv4NEpN.js";const Ui=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],ao=rn("maximize-2",Ui);const Vi=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],qi=rn("pause",Vi);const Xi=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Gi=rn("play",Xi);const Ki=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Qi=rn("rotate-ccw",Ki);const Ji=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ro=rn("terminal",Ji);function Zi(...e){const t=!Array.isArray(e[0]),n=t?0:-1,a=e[0+n],r=e[1+n],s=e[2+n],l=e[3+n],i=oi(r,s,l);return t?i(a):i}function el(e,t,n={}){const a=e.get();let r=null,s=a,l;const i=typeof a=="string"?a.replace(/[\d.-]/g,""):void 0,c=()=>{r&&(r.stop(),r=null),e.animation=void 0},u=()=>{const d=Va(e.get()),m=Va(s);if(d===m){c();return}const g=r?r.getGeneratorVelocity():e.getVelocity();c(),r=new si({keyframes:[d,m],velocity:g,type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:l})},f=()=>{u(),e.animation=r??void 0,e.events.animationStart?.notify(),r?.then(()=>{e.animation=void 0,e.events.animationComplete?.notify()})};if(e.attach((d,m)=>{s=d,l=g=>m(In(g,i)),Ur.postRender(f)},c),Vr(t)){let d=n.skipInitialAnimation===!0;const m=t.on("change",p=>{d?(d=!1,e.jump(In(p,i),!1)):e.set(In(p,i))}),g=e.on("destroy",m);return()=>{m(),g()}}return c}function In(e,t){return t?e+t:e}function Va(e){return typeof e=="number"?e:parseFloat(e)}function ha(e){const t=qr(()=>ii(e)),{isStatic:n}=h.useContext(Xr);if(n){const[,a]=h.useState(e);h.useEffect(()=>t.on("change",a),[])}return t}function oo(e,t){const n=ha(t()),a=()=>n.set(t());return a(),li(()=>{const r=()=>Ur.preRender(a,!1,!0),s=e.map(l=>l.on("change",r));return()=>{s.forEach(l=>l()),ci(a)}}),n}function tl(e){Fn.current=[],e();const t=oo(Fn.current,e);return Fn.current=void 0,t}function so(e,t,n,a){if(typeof e=="function")return tl(e);const s=typeof t=="function"?t:Zi(t,n,a),l=Array.isArray(e)?qa(e,s):qa([e],([c])=>s(c)),i=Array.isArray(e)?void 0:e.accelerate;return i&&!i.isTransformed&&typeof t!="function"&&Array.isArray(n)&&a?.clamp!==!1&&(l.accelerate={...i,times:t,keyframes:n,isTransformed:!0}),l}function qa(e,t){const n=qr(()=>[]);return oo(e,()=>{n.length=0;const a=e.length;for(let r=0;r<a;r++)n[r]=e[r].get();return t(n)})}function nl(e,t={}){const{isStatic:n}=h.useContext(Xr),a=()=>Vr(e)?e.get():e;if(n)return so(a);const r=ha(a());return h.useInsertionEffect(()=>el(r,e,t),[r,JSON.stringify(t)]),r}function al(e,t={}){return nl(e,{type:"spring",...t})}function rl(){return o.jsxs(di,{to:"/landing",className:"flex items-center gap-2.5 no-underline hover:opacity-80 transition-opacity",children:[o.jsx("img",{src:"/app-icon.png",alt:"Token Tracker",width:28,height:28,className:"rounded-md"}),o.jsx("span",{className:"text-base font-semibold text-oai-black dark:text-oai-white leading-tight",children:"Token Tracker"})]})}function ol({children:e,header:t,footer:n,className:a="",hideHeader:r=!1,hideFooter:s=!1,bare:l=!1}){return l?o.jsxs("div",{className:`flex flex-col flex-1 min-h-0 ${a}`,children:[o.jsx("main",{className:"flex-1 px-6 py-6",children:e}),!s&&n&&o.jsx("footer",{className:"border-t border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 mt-auto transition-colors duration-200",children:n})]}):o.jsxs("div",{className:`min-h-screen bg-oai-white dark:bg-oai-gray-950 text-oai-black dark:text-oai-white font-sans flex flex-col transition-colors duration-200 ${a}`,children:[!r&&o.jsxs("header",{className:"border-b border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 flex items-center justify-between transition-colors duration-200",children:[o.jsx(rl,{}),o.jsx("div",{className:"flex-1 flex justify-center",children:t})]}),o.jsx("main",{className:"flex-1 px-6 py-6",children:e}),!s&&n&&o.jsx("footer",{className:"border-t border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 mt-auto transition-colors duration-200",children:n})]})}function sl({children:e,variant:t="info",size:n="md",className:a=""}){const r="inline-flex items-center font-medium",s={success:"bg-oai-brand-100 dark:bg-oai-brand-900/30 text-oai-brand-700 dark:text-oai-brand-400 rounded-full",warning:"bg-oai-amber-50 dark:bg-oai-amber-900/30 text-oai-amber-dark dark:text-oai-amber-400 rounded-full",error:"bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded-full",info:"bg-oai-gray-100 dark:bg-oai-gray-800 text-oai-gray-600 dark:text-oai-gray-300 rounded-full",secondary:"bg-oai-gray-100 dark:bg-oai-gray-800 text-oai-gray-500 dark:text-oai-gray-300 rounded-md"},l={sm:"px-2 py-0.5 text-xs",md:"px-2.5 py-1 text-sm"},i=`${r} ${s[t]} ${l[n]} ${a}`.trim();return o.jsx("span",{className:i,children:e})}const il=h.forwardRef(function(t,n){const{render:a,className:r,disabled:s=!1,nativeButton:l=!0,...i}=t,{store:c}=Ai(),u=c.useState("open");function f(p){u&&c.setOpen(!1,mi(hi,p.nativeEvent))}const{getButtonProps:d,buttonRef:m}=ui({disabled:s,native:l}),g=h.useMemo(()=>({disabled:s}),[s]);return fi("button",t,{state:g,ref:[n,m],props:[{onClick:f},i,d]})});var ll={};function cl(e,t){return e==="."?{width:"0.34ch",justifyContent:"center",marginInline:"-0.04ch"}:e===","?{width:"0.08ch",justifyContent:"center",marginInline:"-0.30ch"}:{width:"0.72ch",justifyContent:"flex-start",paddingLeft:"0.04ch",height:t}}function dl({mv:e,digit:t,height:n}){const a=so(e,r=>{const s=(r%10+10)%10,l=(10+t-s)%10;let i=l*n;return l>5&&(i-=10*n),i});return o.jsx(gt.span,{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",y:a},children:t})}function ul(e){const t=Math.round(e),n=1e-9*Math.max(1,Math.abs(e));return Math.abs(e-t)<n?t:e}function fl(e,t){const n=e/t;return Math.floor(ul(n))}function ml(e){const t=String(e??""),n=Array.from(t),a=n.indexOf(".");let r=n.filter((i,c)=>/\d/.test(i)&&(a===-1||c<a)).length,s=0,l=!1;return n.map(i=>{if(!/\d/.test(i))return i==="."&&(l=!0),i;if(!l){const c=10**Math.max(r-1,0);return r-=1,c}return s+=1,10**-s})}function hl({place:e,value:t,height:n,digitStyle:a,shouldReduceMotion:r,isLed:s}){if(typeof e!="number"){const u=cl(e,n);return o.jsx("span",{"data-counter-token":"static",className:`relative inline-flex items-center justify-center${s?" tt-lcd-sep":""}`,style:{height:n,...u,...a},children:e})}const l=fl(t,e),i=ha(0),c=al(i,{stiffness:220,damping:26,mass:.8});return h.useEffect(()=>{i.set(l)},[i,l]),r?o.jsx("span",{"data-counter-token":"digit",className:`relative inline-flex items-center justify-center overflow-hidden${s?" tt-lcd-cell":""}`,style:{height:n,position:"relative",width:"0.9ch",fontVariantNumeric:"tabular-nums",...a},children:Math.abs(l)%10}):o.jsx("span",{"data-counter-token":"digit",className:`relative inline-flex overflow-hidden${s?" tt-lcd-cell":""}`,style:{height:n,position:"relative",width:"0.9ch",fontVariantNumeric:"tabular-nums",...a},children:Array.from({length:10},(u,f)=>o.jsx(dl,{mv:c,digit:f,height:n},f))})}function gl({value:e,displayValue:t,fontSize:n=72,padding:a=0,places:r,gap:s=6,borderRadius:l=4,horizontalPadding:i=0,textColor:c="inherit",fontWeight:u="inherit",containerStyle:f,counterStyle:d,digitStyle:m,gradientHeight:g=14,gradientFrom:p="rgba(255,255,255,0.95)",gradientTo:b="rgba(255,255,255,0)",topGradientStyle:v,bottomGradientStyle:k,variant:j="default"}){const x=j==="led",N=String(t??e??""),C=h.useMemo(()=>Array.isArray(r)&&r.length?r:ml(N),[r,N]),T=typeof navigator<"u"&&/jsdom/i.test(navigator.userAgent||"")||typeof process<"u"&&ll?.VITEST==="true",z=zt()||T,$=Number.isFinite(Number(e))?Math.abs(Number(e)):0,D=n+a;return z?o.jsx("span",{"data-counter-root":"true",className:x?"tt-lcd":void 0,style:{display:"inline-flex",alignItems:"center",color:c,fontSize:n,fontWeight:u,lineHeight:1,...f,...d},children:x?o.jsx("span",{className:"tt-lcd-cell tt-lcd-cell--static",children:N}):N}):o.jsxs("span",{"data-counter-root":"true",style:{position:"relative",display:"inline-block",...f},children:[o.jsx("span",{className:x?"tt-lcd":void 0,style:{fontSize:n,...x?null:{display:"flex",gap:s,borderRadius:l,paddingLeft:i,paddingRight:i,color:c},overflow:"hidden",lineHeight:1,fontWeight:u,...d},children:C.map((A,K)=>o.jsx(hl,{place:A,value:$,height:D,digitStyle:m,shouldReduceMotion:z,isLed:x},`${String(A)}-${K}`))}),o.jsxs("span",{style:{pointerEvents:"none",position:"absolute",inset:0,display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsx("span",{style:v??{height:g,background:`linear-gradient(to bottom, ${p}, ${b})`}}),o.jsx("span",{style:k??{height:g,background:`linear-gradient(to top, ${p}, ${b})`}})]})]})}var yl={};const pl=new Set([",","."," "]),bl=typeof navigator<"u"&&/jsdom/i.test(navigator.userAgent||"")||typeof process<"u"&&yl?.VITEST==="true";function xl({char:e,reduceMotion:t,index:n}){const[a,r]=h.useState(t?e:""),[s,l]=h.useState(!1),i=h.useRef(e),c=h.useRef(!1);return h.useEffect(()=>{if(!c.current){if(c.current=!0,i.current=e,t){r(e);return}const d=Math.min(n*45,520),m=setTimeout(()=>l(!0),d),g=setTimeout(()=>r(e),d+130),p=setTimeout(()=>l(!1),d+300);return()=>{clearTimeout(m),clearTimeout(g),clearTimeout(p)}}if(e===i.current)return;if(i.current=e,t){r(e);return}l(!0);const u=setTimeout(()=>r(e),130),f=setTimeout(()=>l(!1),300);return()=>{clearTimeout(u),clearTimeout(f)}},[e,t,n]),o.jsx("span",{className:`tt-flap${s?" tt-flap--flip":""}`,"aria-hidden":"true",children:o.jsx("span",{className:"tt-flap__glyph",children:a})})}function kl({value:e,fontSize:t=56,className:n=""}){const a=zt()||bl,r=String(e??""),s=Array.from(r);return o.jsx("span",{className:`tt-flaprow ${n}`,style:{fontSize:`clamp(30px, 9cqi, ${t}px)`},role:"text","aria-label":r,children:s.map((l,i)=>pl.has(l)?o.jsx("span",{className:"tt-flap-sep","aria-hidden":"true",children:l},i):o.jsx(xl,{char:l,reduceMotion:a,index:i},i))})}function wl({baseUrl:e,accessToken:t,guestAllowed:n=!1,weeks:a=52,weekStartsOn:r="sun",cacheKey:s,timeZone:l,tzOffsetMinutes:i,now:c}={}){const u=h.useMemo(()=>wi({weeks:a,weekStartsOn:r,now:c}),[c,a,r]),[f,d]=h.useState([]),[m,g]=h.useState(null),[p,b]=h.useState("edge"),[v,k]=h.useState(!1),[j,x]=h.useState(null),N=Yt(),C=!n,T=h.useMemo(()=>{if(!s)return null;const B=on({timeZone:l,offsetMinutes:i});return`tokentracker.heatmap.${s}.${a}.${r}.${B}`},[s,l,i,a,r]),z=h.useCallback(()=>{if(!T||typeof window>"u")return null;try{const B=window.localStorage.getItem(T);if(!B)return null;const E=JSON.parse(B);return!E||!E.heatmap?null:E}catch{return null}},[T]),$=h.useCallback(B=>{if(!(!T||typeof window>"u"))try{window.localStorage.setItem(T,JSON.stringify(B))}catch{}},[T]),D=h.useCallback(()=>{if(!(!T||typeof window>"u"))try{window.localStorage.removeItem(T)}catch{}},[T]),A=h.useCallback(async()=>{k(!0),x(null);try{try{const H=await ji({baseUrl:e,accessToken:t,weeks:a,to:u.to,weekStartsOn:r,timeZone:l,tzOffsetMinutes:i}),_=Array.isArray(H?.weeks)?H.weeks:[];if(!_.length&&C){const I=z();if(I?.heatmap){g(I.heatmap),d(I.daily||[]),b("cache");return}}if(!_.some(I=>(Array.isArray(I)?I:[]).some(M=>M&&Number.isFinite(Number(M.level))))&&_.length){const I=[];for(const J of _)for(const P of Array.isArray(J)?J:[])P?.day&&I.push({day:P.day,conversation_count:P.conversation_count??0,total_tokens:P.total_tokens??P.value??0,billable_total_tokens:P.billable_total_tokens??P.value??P.total_tokens??0});const M=Zn({dailyRows:I,weeks:a,to:H?.to||u.to,weekStartsOn:r});d(I),g({...M,week_starts_on:r,active_days:I.filter(J=>Number(J?.billable_total_tokens??J?.total_tokens)>0).length,streak_days:pn({dailyRows:I,to:H?.to||u.to})}),b("client"),C?$({heatmap:{...M,week_starts_on:r,active_days:I.filter(J=>Number(J?.billable_total_tokens??J?.total_tokens)>0).length,streak_days:pn({dailyRows:I,to:H?.to||u.to})},daily:I,fetchedAt:new Date().toISOString()}):D();return}g(H||null),d([]),b("edge"),H&&C?$({heatmap:H,daily:[],fetchedAt:new Date().toISOString()}):C||D();return}catch(H){const _=H,w=_?.status??_?.statusCode;if(w===401||w===403)throw H}const B=await Cn({baseUrl:e,accessToken:t,from:u.from,to:u.to,timeZone:l,tzOffsetMinutes:i}),E=Array.isArray(B?.data)?B.data:[];d(E);const W=Zn({dailyRows:E,weeks:a,to:u.to,weekStartsOn:r});g({...W,week_starts_on:r,active_days:E.filter(H=>Number(H?.billable_total_tokens??H?.total_tokens)>0).length,streak_days:pn({dailyRows:E,to:u.to})}),b("client"),C?$({heatmap:{...W,week_starts_on:r,active_days:E.filter(H=>Number(H?.billable_total_tokens??H?.total_tokens)>0).length,streak_days:pn({dailyRows:E,to:u.to})},daily:E,fetchedAt:new Date().toISOString()}):D()}catch(B){if(C){const E=z();if(E?.heatmap)g(E.heatmap),d(E.daily||[]),b("cache"),x(null);else{const W=B;x(W?.message||String(W)),d([]),g(null),b("edge")}}else{const E=B;x(E?.message||String(E)),d([]),g(null),b("edge")}}finally{k(!1)}},[t,e,N,n,C,u.from,u.to,z,l,i,r,a,D,$]);return h.useEffect(()=>{if(!C)D(),d([]),x(null),g(null),b("edge");else{const B=z();B?.heatmap&&(g(B.heatmap),d(B.daily||[]),b("cache"))}A()},[t,N,z,A,n,C,D]),{range:u,daily:f,heatmap:m,source:N?"mock":p==="client"?"edge":p,loading:v,error:j,refresh:A}}function vl({baseUrl:e,accessToken:t,limit:n=3,from:a,to:r,source:s,timeZone:l,tzOffsetMinutes:i}={}){const[c,u]=h.useState([]),[f,d]=h.useState([]),[m,g]=h.useState(!1),[p,b]=h.useState(null),v=h.useCallback(async()=>{g(!0),b(null);try{const k=await Si({baseUrl:e,accessToken:t,limit:n,from:a,to:r,source:s,timeZone:l,tzOffsetMinutes:i});u(Array.isArray(k?.entries)?k.entries:[]),d(Array.isArray(k?.unattributed_sources)?k.unattributed_sources:[])}catch(k){const j=k?.message||String(k);b(j),u([]),d([])}finally{g(!1)}},[t,e,a,n,s,l,r,i]);return h.useEffect(()=>{v()},[v]),{entries:c,unattributedSources:f,loading:m,error:p,refresh:v}}const Nl=24;function io({baseUrl:e,accessToken:t,guestAllowed:n=!1,period:a,from:r,to:s,months:l=Nl,cacheKey:i,timeZone:c,tzOffsetMinutes:u,now:f,sharedRows:d,sharedRange:m}={}){const[g,p]=h.useState([]),[b,v]=h.useState(()=>({from:r,to:s})),[k,j]=h.useState("edge"),[x,N]=h.useState(null),[C,T]=h.useState(!1),[z,$]=h.useState(null),D=Yt(),A=!n&&!D,K=Array.isArray(d),B=m?.from||r,E=m?.to||s,W=h.useMemo(()=>a==="day"||a==="24h"?"hourly":a==="total"?"monthly":"daily",[a]),H=(()=>{if(!i)return null;const P=_l(e)||"default",L=on({timeZone:c,offsetMinutes:u});if(W==="hourly"){const q=a==="24h"?`${r||""}.${s||""}`:s||r||"day";return`tokentracker.trend.${i}.${P}.hourly.${q}.${L}`}if(W==="monthly")return`tokentracker.trend.${i}.${P}.monthly.${l}.${s||"today"}.${L}`;const V=`${r||""}.${s||""}`;return`tokentracker.trend.${i}.${P}.daily.${V}.${L}`})(),_=h.useCallback(()=>{if(!H||typeof window>"u")return null;try{const P=window.localStorage.getItem(H);if(!P)return null;const L=JSON.parse(P);return!L||!Array.isArray(L.rows)?null:L}catch{return null}},[H]),w=h.useCallback(P=>{if(!(!H||typeof window>"u"))try{window.localStorage.setItem(H,JSON.stringify(P))}catch{}},[H]),I=h.useCallback(()=>{if(!(!H||typeof window>"u"))try{window.localStorage.removeItem(H)}catch{}},[H]),M=h.useCallback(async()=>{if(K){p(Array.isArray(d)?d:[]),v({from:B,to:E}),j("shared"),N(null),T(!1),$(null);return}T(!0),$(null);try{let P;W==="hourly"?P=await Ml({baseUrl:e,accessToken:t,from:r,to:s,period:a,timeZone:c,tzOffsetMinutes:u,now:f}):W==="monthly"?P=await Ci({baseUrl:e,accessToken:t,months:l,to:s,timeZone:c,tzOffsetMinutes:u}):P=await Cn({baseUrl:e,accessToken:t,from:r,to:s,timeZone:c,tzOffsetMinutes:u});const L=P?.from||r||P?.day||null,V=P?.to||s||P?.day||null;let q=Array.isArray(P?.data)?P.data:[];W==="daily"?q=Ln(q,L||r,V||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?q=wn(q,L||r||P?.day,V||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):W==="monthly"&&(q=zn(q,{timeZone:c,offsetMinutes:u,now:f}));const fe=new Date().toISOString();p(q),v({from:L,to:V}),j("edge"),N(fe),A?w({rows:q,from:L,to:V,mode:W,fetchedAt:fe}):I()}catch(P){if(A){const L=_();if(L?.rows){let V=W==="daily"?Ln(L.rows||[],L.from||r,L.to||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?wn(L.rows||[],L.from||r||L.day||s,L.to||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):Array.isArray(L.rows)?L.rows:[];W==="monthly"&&(V=zn(V,{timeZone:c,offsetMinutes:u,now:f})),p(V),v({from:L.from||r,to:L.to||s}),j("cache"),N(L.fetchedAt||null),$(null)}else{p([]),v({from:r,to:s}),j("edge"),N(null);const V=P;$(V?.message||String(V))}}else{p([]),v({from:r,to:s}),j("edge"),N(null);const L=P;$(L?.message||String(L))}}finally{T(!1)}},[t,e,r,D,n,A,W,l,a,_,K,B,d,E,c,s,u,f,I,w]);h.useEffect(()=>{if(K){p(Array.isArray(d)?d:[]),v({from:B,to:E}),j("shared"),N(null),T(!1),$(null);return}if(!A)I(),p([]),v({from:r,to:s}),$(null),j("edge"),N(null);else{const P=_();if(P?.rows){let L=W==="daily"?Ln(P.rows||[],P.from||r,P.to||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?wn(P.rows||[],P.from||r||P.day||s,P.to||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):Array.isArray(P.rows)?P.rows:[];W==="monthly"&&(L=zn(L,{timeZone:c,offsetMinutes:u,now:f})),p(L),v({from:P.from||r,to:P.to||s}),j("cache"),N(P.fetchedAt||null)}}M()},[t,D,_,M,K,B,d,E,n,A,I,W,r,s,c,u,f,a]);const J=D?"mock":k;return{rows:g,from:b.from||r,to:b.to||s,source:J,fetchedAt:x,loading:C,error:z,refresh:M}}function _l(e){try{return new URL(e).host}catch{return null}}async function Ml({baseUrl:e,accessToken:t,from:n,to:a,period:r,timeZone:s,tzOffsetMinutes:l,now:i}){const c=r==="24h"?lo(n,a):[a||n].filter(Boolean),u=Array.from(new Set(c)),f=await Promise.all(u.map(p=>no({accessToken:t,day:p,timeZone:s,tzOffsetMinutes:l}))),d=f.flatMap(p=>Array.isArray(p?.data)?p.data:[]),m=r==="24h"?u[0]||n||a:f[0]?.day||n||a,g=r==="24h"?u[u.length-1]||a||n:f[0]?.day||a||n;return{day:g,from:m,to:g,data:wn(d,m,g,{period:r,timeZone:s,offsetMinutes:l,now:i})}}function Lt(e){if(!e)return null;const t=String(e).trim(),n=t.split("-");if(n.length!==3)return null;const a=Number(n[0]),r=Number(n[1])-1,s=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r,s));return Number.isFinite(l.getTime())&&ht(l)===t?l:null}function ga(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function lo(e,t){const n=Lt(e||t),a=Lt(t||e);if(!n||!a)return[e||t].filter(Boolean).map(String);if(a<n)return[ht(a),ht(n)];const r=[];for(let s=n;s<=a;s=ga(s,1))r.push(ht(s));return r}const co=["total_tokens","billable_total_tokens","input_tokens","cached_input_tokens","cache_creation_input_tokens","output_tokens","reasoning_output_tokens","conversation_count"];function Ln(e,t,n,{timeZone:a,offsetMinutes:r,now:s}={}){const l=Lt(t),i=Lt(n);if(!l||!i||i<l)return Array.isArray(e)?e:[];const c=s instanceof Date&&Number.isFinite(s.getTime())?s:new Date,u=tn({timeZone:a,offsetMinutes:r,date:c}),f=Lt(u),d=f?f.getTime():c.getTime(),m=new Map;for(const p of e||[])p?.day&&m.set(p.day,p);const g=[];for(let p=l;p<=i;p=ga(p,1)){const b=ht(p),v=m.get(b),k=p.getTime()>d;if(v){g.push({...v,missing:!1,future:k});continue}g.push({day:b,total_tokens:null,billable_total_tokens:null,input_tokens:null,cached_input_tokens:null,output_tokens:null,reasoning_output_tokens:null,missing:!k,future:k})}return g}function jl(e,t){const n=t?null:0;return{hour:e,total_tokens:n,billable_total_tokens:n,input_tokens:n,cached_input_tokens:n,cache_creation_input_tokens:n,output_tokens:n,reasoning_output_tokens:n,conversation_count:n,missing:!1,future:t}}function Sl(e){if(!e||typeof e!="object")return!1;const t=e.models;return t&&typeof t=="object"&&Object.keys(t).length>0?!1:co.every(n=>e[n]==null)}function Cl(e,t,n){const a={...e,hour:t,missing:!1,future:n};if(!n&&Sl(e))for(const r of co)a[r]=0;return a}function Dl(e,t){const n=t===30?48:24,a=[];for(let r=0;r<n;r++){const s=Math.floor(r*t/60),l=r*t%60;a.push(`${e}T${String(s).padStart(2,"0")}:${String(l).padStart(2,"0")}:00`)}return a}function Tl(e,t,{timeZone:n,offsetMinutes:a}={}){const r=Dl(e,t);if(!n||typeof Intl>"u"||!Intl.DateTimeFormat)return r;const s=Lt(e);if(!s)return r;const l=s.getUTCFullYear()*1e4+(s.getUTCMonth()+1)*100+s.getUTCDate(),i=s.getTime()-2160*60*1e3,c=ga(s,2).getTime()+2160*60*1e3,u=[],f=new Set;for(let d=i;d<=c;d+=1800*1e3){const m=ln({timeZone:n,offsetMinutes:a,now:new Date(d)});if(!m||m.dayNum!==l||t===60&&m.minute!==0||t===30&&m.minute!==0&&m.minute!==30)continue;const g=`${e}T${String(m.hour).padStart(2,"0")}:${String(m.minute).padStart(2,"0")}:00`;f.has(g)||(f.add(g),u.push(g))}return u.length>0?u:r}function Pl(e,t,{timeZone:n,offsetMinutes:a,now:r}={}){if(!t)return Array.isArray(e)?e:[];const s=t.trim().slice(0,10),l=ln({timeZone:n,offsetMinutes:a,now:r}),i=l?l.dayNum:void 0;let c=!1;for(const g of e||[]){const p=g?.hour||g?.label||"",b=vn(p,i);if(b&&b.slot%2!==0){c=!0;break}}const u=c?30:60,f=new Map;for(const g of e||[]){const p=g?.hour||g?.label||"",b=vn(p,i);b&&f.set(b.slot,g)}const d=[],m=Tl(s,u,{timeZone:n,offsetMinutes:a});for(let g=0;g<m.length;g++){const p=m[g],b=vn(p,i),v=b?b.slot:c?g:g*2,k=f.get(v);let j=!1;if(l){const x=l.year*1e4+l.month*100+l.day,N=b?.dayNum??Number(s.replace(/-/g,""));if(N>x)j=!0;else if(N===x){const C=l.hour*2+(l.minute>=30?1:0);j=v>C}}k?d.push(Cl(k,p,j)):d.push(jl(p,j))}return d}function wn(e,t,n,{period:a,timeZone:r,offsetMinutes:s,now:l}={}){const i=a==="24h"?lo(t,n):[n||t].filter(Boolean).map(String),u=Array.from(new Set(i)).flatMap(d=>Pl(Ol(e||[],d),d,{timeZone:r,offsetMinutes:s,now:l})),f=$l(u,{timeZone:r,offsetMinutes:s,now:l});return a!=="24h"?f:El(f,{timeZone:r,offsetMinutes:s,now:l})}function Ol(e,t){return e.filter(n=>{const a=n?.hour||n?.label||"",r=String(a).trim();return r.includes("T")?r.slice(0,10)===t:!0})}function $l(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});return r?e.map(s=>{const l=s?.hour||s?.label||"",i=vn(l,r.dayNum);if(!i)return{...s,future:!1};const c=i.dayNum!==null&&i.dayNum>r.dayNum||(i.dayNum===null||i.dayNum===r.dayNum)&&i.slot>r.slot;return{...s,future:!!c}}):e}function El(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});if(!r)return e.filter(i=>!i?.future);const s=uo({year:r.year,month:r.month,day:r.day,hour:r.hour,minute:r.minute}),l=s-1440*60*1e3;return e.filter(i=>{if(i?.future)return!1;const c=Wl(i?.hour||i?.label);return c!=null&&c>=l&&c<=s})}function zn(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});return r?e.map(s=>{const l=s?.month||s?.label||"",i=Al(l);if(!i)return{...s,future:!1};const c=i.year>r.year||i.year===r.year&&i.month>r.month;return{...s,future:c}}):e}function ln({timeZone:e,offsetMinutes:t,now:n}={}){const a=n instanceof Date&&Number.isFinite(n.getTime())?n:new Date;if(e&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const m=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(a).reduce((j,x)=>(x.type&&x.value&&(j[x.type]=x.value),j),{}),g=Number(m.year),p=Number(m.month),b=Number(m.day),v=Number(m.hour),k=Number(m.minute);if(Number.isFinite(g)&&Number.isFinite(p)&&Number.isFinite(b)&&Number.isFinite(v)&&Number.isFinite(k)){const j=v*2+(k>=30?1:0);return{year:g,month:p,day:b,hour:v,minute:k,dayNum:g*1e4+p*100+b,slot:j}}}catch{}if(Number.isFinite(t)){const f=new Date(a.getTime()+t*60*1e3),d=f.getUTCFullYear(),m=f.getUTCMonth()+1,g=f.getUTCDate(),p=f.getUTCHours(),b=f.getUTCMinutes(),v=p*2+(b>=30?1:0);return{year:d,month:m,day:g,hour:p,minute:b,dayNum:d*1e4+m*100+g,slot:v}}const r=a.getFullYear(),s=a.getMonth()+1,l=a.getDate(),i=a.getHours(),c=a.getMinutes(),u=i*2+(c>=30?1:0);return{year:r,month:s,day:l,hour:i,minute:c,dayNum:r*1e4+s*100+l,slot:u}}function vn(e,t){if(!e)return null;const n=String(e).trim();if(n.includes("T")){const[a,r]=n.split("T");if(!a||!r)return null;const s=a.split("-");if(s.length!==3)return null;const l=Number(s[0]),i=Number(s[1]),c=Number(s[2]);if(!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c))return null;const u=r.split(":"),f=Number(u[0]),d=Number(u[1]);if(!Number.isFinite(f)||f<0||f>23||!Number.isFinite(d)||d<0||d>59)return null;const m=f*2+(d>=30?1:0);return{dayNum:l*1e4+i*100+c,slot:m}}else{let a=NaN,r=0;if(/^\d{1,2}$/.test(n))a=Number(n);else if(/^\d{1,2}:\d{2}(:\d{2})?$/.test(n)){const l=n.split(":");a=Number(l[0]),r=Number(l[1])}if(!Number.isFinite(a)||a<0||a>23||!Number.isFinite(r)||r<0||r>59)return null;const s=a*2+(r>=30?1:0);return{dayNum:t||null,slot:s}}}function uo({year:e,month:t,day:n,hour:a=0,minute:r=0}){return Date.UTC(Number(e),Number(t)-1,Number(n),Number(a),Number(r),0,0)}function Wl(e){if(!e)return null;const t=String(e).trim();if(!t.includes("T"))return null;const[n,a]=t.split("T");if(!n||!a)return null;const r=n.split("-"),s=a.split(":");if(r.length!==3||s.length<2)return null;const[l,i,c]=r.map(Number),[u,f]=s.map(Number);return!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c)||!Number.isFinite(u)||!Number.isFinite(f)?null:uo({year:l,month:i,day:c,hour:u,minute:f})}function Al(e){if(!e)return null;const n=String(e).trim().split("-");if(n.length!==2)return null;const a=Number(n[0]),r=Number(n[1]);return!Number.isFinite(a)||!Number.isFinite(r)||r<1||r>12?null:{year:a,month:r}}function Xa({baseUrl:e,accessToken:t,guestAllowed:n=!1,from:a,to:r,includeDaily:s=!0,cacheKey:l,timeZone:i,tzOffsetMinutes:c,now:u}={}){const[f,d]=h.useState([]),[m,g]=h.useState(null),[p,b]=h.useState(null),[v,k]=h.useState("edge"),[j,x]=h.useState(null),[N,C]=h.useState(!1),[T,z]=h.useState(null),$=Yt(),D=!n&&!$,A=(()=>{if(!l)return null;const _=Fl(e)||"default",w=s?"daily":"summary",I=on({timeZone:i,offsetMinutes:c});return`tokentracker.usage.${l}.${_}.${a}.${r}.${w}.${I}`})(),K=h.useCallback(()=>{if(!A||typeof window>"u")return null;try{const _=window.localStorage.getItem(A);if(!_)return null;const w=JSON.parse(_);return!w||!w.summary?null:w}catch{return null}},[A]),B=h.useCallback(_=>{if(!(!A||typeof window>"u"))try{window.localStorage.setItem(A,JSON.stringify(_))}catch{}},[A]),E=h.useCallback(()=>{if(!(!A||typeof window>"u"))try{window.localStorage.removeItem(A)}catch{}},[A]),W=h.useCallback(async()=>{C(!0),z(null);try{let _=null,w=null;if(s){const[L,V]=await Promise.allSettled([Cn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c}),Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0})]);if(L.status==="rejected")throw L.reason;_=L.value,w=V.status==="fulfilled"?V.value:null}else w=await Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0});let I=s&&Array.isArray(_?.data)?_.data:[];s&&(I=Bn(I,a,r,{timeZone:i,offsetMinutes:c,now:u}));let M=w?.totals||_?.summary?.totals||null,J=w?.rolling||_?.summary?.rolling||null;if(s&&!M&&!w)try{const L=await Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0});M=L?.totals||null,J=L?.rolling||J}catch{}const P=new Date().toISOString();d(I),g(M),b(J),k("edge"),x(P),M&&D?B({summary:M,rolling:J,daily:I,from:a,to:r,includeDaily:s,fetchedAt:P}):D||E()}catch(_){if(D){const w=K();if(w?.summary){g(w.summary),b(w.rolling||null);const I=Array.isArray(w.daily)?w.daily:[],M=s?Bn(I,w.from||a,w.to||r,{timeZone:i,offsetMinutes:c,now:u}):I;d(M),k("cache"),x(w.fetchedAt||null),z(null)}else{const I=_;z(I?.message||String(I)),d([]),g(null),b(null),k("edge"),x(null)}}else{const w=_;z(w?.message||String(w)),d([]),g(null),b(null),k("edge"),x(null)}}finally{C(!1)}},[t,e,a,s,$,n,D,u,K,i,r,c,E,B]);return h.useEffect(()=>{if(!D)E(),d([]),g(null),b(null),z(null),k("edge"),x(null);else{const _=K();if(_?.summary){g(_.summary),b(_.rolling||null);const w=Array.isArray(_.daily)?_.daily:[],I=s?Bn(w,_.from||a,_.to||r,{timeZone:i,offsetMinutes:c,now:u}):w;d(I),k("cache"),x(_.fetchedAt||null)}}W()},[t,$,K,W,n,D,E]),{daily:f,summary:m,rolling:p,source:$?"mock":v,fetchedAt:j,loading:N,error:T,refresh:W}}function Fl(e){try{return new URL(e).host}catch{return null}}function Yn(e){if(!e)return null;const t=String(e).trim(),n=t.split("-");if(n.length!==3)return null;const a=Number(n[0]),r=Number(n[1])-1,s=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r,s));return Number.isFinite(l.getTime())&&ht(l)===t?l:null}function Rl(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function Bn(e,t,n,{timeZone:a,offsetMinutes:r,now:s}={}){const l=Yn(t),i=Yn(n);if(!l||!i||i<l)return Array.isArray(e)?e:[];const c=s instanceof Date&&Number.isFinite(s.getTime())?s:new Date,u=tn({timeZone:a,offsetMinutes:r,date:c}),f=Yn(u),d=f?f.getTime():c.getTime(),m=new Map;for(const p of e||[])p?.day&&m.set(p.day,p);const g=[];for(let p=l;p<=i;p=Rl(p,1)){const b=ht(p),v=m.get(b),k=p.getTime()>d;if(v){g.push({...v,missing:!1,future:k});continue}g.push({day:b,total_tokens:null,billable_total_tokens:null,input_tokens:null,cached_input_tokens:null,output_tokens:null,reasoning_output_tokens:null,missing:!k,future:k})}return g}function Il({baseUrl:e,accessToken:t,guestAllowed:n=!1,from:a,to:r,cacheKey:s,timeZone:l,tzOffsetMinutes:i}={}){const[c,u]=h.useState(null),[f,d]=h.useState("edge"),[m,g]=h.useState(!1),[p,b]=h.useState(null),v=Yt(),k=!n,j=h.useMemo(()=>{if(!s)return null;const $=Ll(e)||"default",D=on({timeZone:l,offsetMinutes:i});return`tokentracker.modelBreakdown.${s}.${$}.${a}.${r}.${D}`},[e,s,a,l,r,i]),x=h.useCallback(()=>{if(!j||typeof window>"u")return null;try{const $=window.localStorage.getItem(j);if(!$)return null;const D=JSON.parse($);return!D||!D.breakdown?null:D}catch{return null}},[j]),N=h.useCallback($=>{if(!(!j||typeof window>"u"))try{window.localStorage.setItem(j,JSON.stringify($))}catch{}},[j]),C=h.useCallback(()=>{if(!(!j||typeof window>"u"))try{window.localStorage.removeItem(j)}catch{}},[j]),T=h.useCallback(async()=>{g(!0),b(null);try{const $=await Di({baseUrl:e,accessToken:t,from:a,to:r,timeZone:l,tzOffsetMinutes:i});u($||null),d("edge"),$&&k?N({breakdown:$,fetchedAt:new Date().toISOString()}):k||C()}catch($){if(k){const D=x();if(D?.breakdown)u(D.breakdown),d("cache"),b(null);else{u(null),d("edge");const A=$;b(A?.message||String(A))}}else{u(null),d("edge");const D=$;b(D?.message||String(D))}}finally{g(!1)}},[t,e,a,v,n,k,x,l,r,i,C,N]);return h.useEffect(()=>{if(!k)C(),u(null),d("edge"),b(null);else{const $=x();$?.breakdown&&(u($.breakdown),d("cache"))}T()},[t,v,x,T,n,k,C]),{breakdown:c,source:v?"mock":f,loading:m,error:p,refresh:T}}function Ll(e){try{return new URL(e).host}catch{return null}}const oa="tokentracker.plan_prices.v1";function zl(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(oa);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n={};for(const[a,r]of Object.entries(t)){const s=Number(r);Number.isFinite(s)&&s>0&&(n[String(a).toLowerCase()]=s)}return n}catch{return{}}}function Yl(){const[e,t]=h.useState({});h.useEffect(()=>{t(zl())},[]);const n=h.useCallback((a,r)=>{t(s=>{const l=String(a||"").toLowerCase();if(!l)return s;const i={...s},c=Number(r);Number.isFinite(c)&&c>0?i[l]=c:delete i[l];try{window.localStorage.setItem(oa,JSON.stringify(i))}catch{}return i})},[]);return{planPrices:e,setPlanPrice:n,PLAN_PRICES_STORAGE_KEY:oa}}function Re(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}function Bl(e){const t=String(e?.hour??""),n=t.indexOf("T");if(n<0)return null;const a=Number(t.slice(n+1,n+3));return Number.isFinite(a)?a:null}function It(e,t){let n=0,a=0;if(Array.isArray(e))for(const r of e){const s=Bl(r);s==null||s>t||(n+=Re(r.total_tokens),a+=Re(r.total_cost_usd))}return{tokens:n,cost:a}}function _n(...e){return e.reduce((t,n)=>({tokens:t.tokens+Re(n?.tokens),cost:t.cost+Re(n?.cost)}),{tokens:0,cost:0})}function Ga(e){if(!Array.isArray(e)||e.length===0)return null;const t=_n(...e);return{tokens:t.tokens/e.length,cost:t.cost/e.length}}function Hn(e){if(!e)return null;const t=Re(e.tokens);return t<=0?null:Re(e.cost)/(t/1e6)}function Ka(e,t){return e==null||t==null||!Number.isFinite(e)||!Number.isFinite(t)||t===0?null:(e-t)/t}function Hl({current:e,prev:t=null,trailingAvg:n=null,trailingFull:a=null,period:r}){if(r==="total"||!e)return null;const s=(i,c)=>c==null||!(c>0)?null:i/c,l=(i,c,u,f)=>({value:i,deltaVsPrev:Ka(i,c),deltaVsAvg:n?Ka(i,u):null,progress:f});return{period:r,tokens:l(Re(e.tokens),t?Re(t.tokens):null,n?Re(n.tokens):null,a?s(Re(e.tokens),Re(a.tokens)):null),cost:l(Re(e.cost),t?Re(t.cost):null,n?Re(n.cost):null,a?s(Re(e.cost),Re(a.cost)):null),perMTok:l(Hn(e),Hn(t),Hn(n),null)}}const fo=864e5;function sa(e){const t=String(e).split("-").map(Number);return t.length!==3||t.some(n=>!Number.isFinite(n))?null:Date.UTC(t[0],t[1]-1,t[2])}function Mn(e){const t=new Date(e),n=t.getUTCFullYear(),a=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0");return`${n}-${a}-${r}`}function wt(e,t){const n=sa(e);return n==null?null:Mn(n+t*fo)}function Ul(e,{timeZone:t,offsetMinutes:n}){const a=e instanceof Date?e:new Date(e);if(t&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const r=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",hour12:!1});let s=Number(r.format(a).slice(0,2));if(s===24&&(s=0),Number.isFinite(s))return Math.min(23,Math.max(0,s))}catch{}return typeof n=="number"&&Number.isFinite(n)?new Date(a.getTime()+n*6e4).getUTCHours():a.getHours()}function Vl(e,{timeZone:t,offsetMinutes:n}){const a=e instanceof Date?e:new Date(e);if(t&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(a);if(/^\d{4}-\d{2}-\d{2}$/.test(s))return s}catch{}return typeof n=="number"&&Number.isFinite(n)?Mn(a.getTime()+n*6e4):Mn(a.getTime())}const ql=e=>Number(e?.total_tokens??0)||0,Xl=e=>Number(e?.total_cost_usd??0)||0;function Qa(e,t,n){let a={tokens:0,cost:0};const r=t?sa(t):null,s=n?sa(n):null;if(r==null||s==null||r>s)return a;for(let l=r;l<=s;l+=fo){const i=e.get(Mn(l));i&&(a=_n(a,i))}return a}function Gl(e,t){if(!t||e==="total")return null;if(e==="day"||e==="24h"){const s=[];for(let l=1;l<=7;l++){const i=wt(t,-l);i&&s.push(i)}return{kind:"day",hourlyDays:[t,...s],dailyFrom:null,dailyTo:null,todayKey:t,prevKey:wt(t,-1),trailingKeys:s}}const n=e==="week"?6:e==="month"?29:null;if(n==null)return null;const a=n+1,r=wt(t,-a);return{kind:"window",hourlyDays:[t,r].filter(Boolean),dailyFrom:wt(t,-(a*2-1)),dailyTo:t,todayKey:t,curStartKey:wt(t,-n),prevBoundaryKey:r,prevStartKey:wt(t,-(a*2-1))}}function Kl(e,t){const n=new Map;return e.forEach((a,r)=>{n.set(a,Array.isArray(t[r]?.data)?t[r].data:[])}),n}function Ql(e){const t=new Map;for(const n of Array.isArray(e?.data)?e.data:[])n?.day&&t.set(String(n.day),{tokens:ql(n),cost:Xl(n)});return t}function Jl(e,t,n){return{current:It(t.get(e.todayKey),n),prev:e.prevKey?It(t.get(e.prevKey),n):null,trailingAvg:Ga(e.trailingKeys.map(a=>It(t.get(a),n))),trailingFull:Ga(e.trailingKeys.map(a=>It(t.get(a),23)))}}function Zl(e,t,n,a){const r=_n(Qa(n,e.curStartKey,wt(e.todayKey,-1)),It(t.get(e.todayKey),a)),s=_n(Qa(n,e.prevStartKey,e.prevBoundaryKey?wt(e.prevBoundaryKey,-1):null),e.prevBoundaryKey?It(t.get(e.prevBoundaryKey),a):{tokens:0,cost:0});return{current:r,prev:s,trailingAvg:null}}function ec(e){try{return new URL(e).host}catch{return null}}function tc({baseUrl:e,accessToken:t,guestAllowed:n=!1,period:a,timeZone:r,tzOffsetMinutes:s,now:l,cacheKey:i}={}){const[c,u]=h.useState(null),[f,d]=h.useState(!1),[m,g]=h.useState(null),p=h.useRef(0),b=l instanceof Date?l:new Date(l||Date.now()),v=Vl(b,{timeZone:r,offsetMinutes:s}),k=Ul(b,{timeZone:r,offsetMinutes:s}),j=Yt(),x=!n&&!j,N=(()=>{if(!i)return null;const D=ec(e)||"default",A=on({timeZone:r,offsetMinutes:s});return`tokentracker.pulse.${i}.${D}.${a}.${v}.${A}`})(),C=h.useCallback(()=>{if(!N||typeof window>"u")return null;try{const D=window.localStorage.getItem(N);return D?JSON.parse(D):null}catch{return null}},[N]),T=h.useCallback(D=>{if(!(!N||typeof window>"u"))try{window.localStorage.setItem(N,JSON.stringify(D))}catch{}},[N]),z=h.useCallback(()=>{const D=C();return D&&D.cutoffHour===k?D:null},[C,k]),$=h.useCallback(async()=>{const D=Gl(a,v);if(!D){u(null),g(null);return}const A=++p.current;d(!0),g(null);try{const K=await Promise.all(D.hourlyDays.map(H=>no({baseUrl:e,accessToken:t,day:H,timeZone:r,tzOffsetMinutes:s}))),B=Kl(D.hourlyDays,K);let E;if(D.kind==="day")E=Jl(D,B,k);else{const H=await Cn({baseUrl:e,accessToken:t,from:D.dailyFrom,to:D.dailyTo,timeZone:r,tzOffsetMinutes:s});E=Zl(D,B,Ql(H),k)}const W=Hl({...E,period:a});if(A!==p.current)return;u(W),x&&W&&T({pulse:W,todayKey:v,cutoffHour:k,fetchedAt:new Date().toISOString()})}catch(K){if(A!==p.current)return;const B=z();B?.pulse&&u(B.pulse),g(K?.message?String(K.message):"Failed to load pulse")}finally{A===p.current&&d(!1)}},[e,t,n,a,r,s,v,k,x,j,z,T]);return h.useEffect(()=>{if(a==="total"||a==="custom"){u(null);return}const D=z();D?.pulse&&u(D.pulse)},[N,a,k]),h.useEffect(()=>{$()},[$]),{pulse:c,loading:f,error:m,refresh:$}}const mo=new Set(["day","hour","month"]);function nc(e){return mo.has(e)}function Ja(e){if(e==null)return null;const t=String(e).trim();if(!/^[0-9]+$/.test(t))return null;const n=t.replace(/^0+/,"");return n.length===0?"0":n}function ac(e,t){const n=Ja(e),a=Ja(t);if(n&&a)return n.length!==a.length?n.length<a.length?-1:1:n===a?0:n<a?-1:1;const r=Le(e),s=Le(t);return r==null&&s==null?0:r==null?1:s==null?-1:r===s?0:r<s?-1:1}function ho(e,t){const n=typeof e=="string"?e:String(e||""),a=typeof t=="string"?t:String(t||"");return n===a?0:n<a?-1:1}function rc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]),s=Number(n[3]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r-1,s));return!Number.isFinite(l.getTime())||l.getUTCFullYear()!==a||l.getUTCMonth()+1!==r||l.getUTCDate()!==s?null:l.getTime()}function oc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||r<1||r>12)return null;const s=new Date(Date.UTC(a,r-1,1));return Number.isFinite(s.getTime())?s.getTime():null}function sc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?Z?$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]),s=Number(n[3]),l=Number(n[4]),i=Number(n[5]),c=Number(n[6]||0);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c)||r<1||r>12||s<1||s>31||l<0||l>23||i<0||i>59||c<0||c>59)return null;const u=new Date(Date.UTC(a,r-1,s,l,i,c));return Number.isFinite(u.getTime())?u.getTime():null}function ic(e,t,n){const a=n==="hour"?sc:n==="month"?oc:rc,r=a(e),s=a(t);return r!=null&&s!=null?r===s?0:r<s?-1:1:ho(e,t)}function go(e,{key:t,dir:n}){const a=n==="asc"?1:-1,r=Array.isArray(e)?e:[],s=mo.has(t)?(i,c)=>ic(i,c,t):t==="top_model"?ho:ac,l=i=>t==="total_tokens"&&i?.billable_total_tokens!=null?i.billable_total_tokens:i?.[t];return r.map((i,c)=>({row:i,index:c})).sort((i,c)=>{const u=l(i.row),f=l(c.row),d=u==null,m=f==null;if(d&&m)return i.index-c.index;if(d)return 1;if(m)return-1;const g=s(u,f);return g!==0?g*a:i.index-c.index}).map(i=>i.row)}function lc(){return[{key:"day",label:y("daily.sort.date.label"),title:y("daily.sort.date.title")},{key:"total_tokens",label:y("daily.sort.total.label"),title:y("daily.sort.total.title")},{key:"input_tokens",label:y("daily.sort.input.label"),title:y("daily.sort.input.title")},{key:"output_tokens",label:y("daily.sort.output.label"),title:y("daily.sort.output.title")},{key:"cached_input_tokens",label:y("daily.sort.cached.label"),title:y("daily.sort.cached.title")},{key:"reasoning_output_tokens",label:y("daily.sort.reasoning.label"),title:y("daily.sort.reasoning.title")},{key:"conversation_count",label:y("daily.sort.conversations.label"),title:y("daily.sort.conversations.title")}]}function Za(e){const t=nc(e)?e:"day";return lc().map((n,a)=>a===0?{...n,key:t}:n)}function er(e,{key:t,dir:n}){return go(e,{key:t,dir:n})}const jn=12,cc=["total_tokens","billable_total_tokens","input_tokens","cached_input_tokens","cache_creation_input_tokens","output_tokens","reasoning_output_tokens"];function dc(e){if(typeof e=="bigint")return e!==0n;if(typeof e=="number")return Number.isFinite(e)&&e!==0;if(e==null)return!1;const t=String(e).trim();if(!t||!/^-?\d+$/.test(t))return!1;const n=t.startsWith("-")?t.slice(1):t;return/[1-9]/.test(n)}function uc(e){return cc.some(t=>dc(e?.[t]))}function fc(e){const t=Array.isArray(e)?e:[];if(!t.length)return[];const n=go(t,{key:"month",dir:"asc"}),a=n.findIndex(r=>r?.month&&uc(r));return a===-1?t:n.slice(a)}function mc(e,t,n=jn){const a=Array.isArray(e)?e:[],r=Number.isFinite(n)&&n>0?n:jn,l=(Number.isFinite(t)&&t>=0?Math.floor(t):0)*r;return a.slice(l,l+r)}function hc(e){if(typeof e!="string")return null;const t=e.trim();return t?t.toLowerCase():null}function gc(e){const t=hc(e?.model_id);return t||null}function yc(e,t){return e?.model?String(e.model):t}const pc=new Set(["curated:fuzzy","litellm:fuzzy","litellm:prefix-strip"]),bc=new Set(["miss","unattributed","empty"]);function xc(e){const t=String(e||"").toLowerCase();return t.includes("free")||t.includes("hy3-preview")||/^glm-[\d.]+-flash(?![a-z])/.test(t)}function Sn(e,t=0){const n=Le(e?.billable_total_tokens),a=Le(e?.total_tokens);return n!=null&&n>0?n:a!=null&&a>0?a:n??a??t}function yo(e,{copyFn:t}={}){const n=typeof t=="function"?t:l=>l,r=(Array.isArray(e?.sources)?e.sources:[]).map(l=>{const i=Sn(l?.totals),c=Le(l?.totals?.total_cost_usd)??0;return{source:l?.source,totalTokens:Number.isFinite(i)?i:0,totalCost:Number.isFinite(c)?c:0,models:Array.isArray(l?.models)?l.models:[]}}).filter(l=>l.totalTokens>0);if(!r.length)return[];const s=r.reduce((l,i)=>l+i.totalTokens,0);return typeof e?.pricing?.pricing_mode=="string"&&e.pricing.pricing_mode.toUpperCase(),r.slice().sort((l,i)=>i.totalTokens-l.totalTokens).map(l=>{const i=l.source?String(l.source).toUpperCase():n("shared.placeholder.short"),c=s>0?l.totalTokens/s*100:0,u=Number.isFinite(c)?c.toFixed(1):"0.0",f=l.models.map(p=>{const b=Sn(p?.totals);if(!Number.isFinite(b)||b<=0)return null;const v=l.totalTokens>0?Math.round(b/l.totalTokens*1e3)/10:0,k=yc(p,n("shared.placeholder.short")),j=gc(p),x=Le(p?.totals?.total_cost_usd),N=x??(l.totalCost>0&&l.totalTokens>0?b/l.totalTokens*l.totalCost:null),C=typeof p?.pricing_tier=="string"?p.pricing_tier:null,T=C?bc.has(C)&&b>0:b>0&&(N==null||N<=0)&&!xc(k),z=!!(C&&pc.has(C));return{id:j,name:k,share:v,usage:b,cost:N,pricingTier:C,pricingMissing:T,pricingFuzzy:z}}).filter(Boolean),d=f.filter(p=>Number.isFinite(Number(p?.cost))&&Number(p.cost)>0).sort((p,b)=>Number(b.cost)-Number(p.cost))[0]||null,m=f.filter(p=>p?.pricingMissing),g=f.filter(p=>p?.pricingFuzzy);return{source:l.source,label:i,totalPercent:String(u),usd:l.totalCost,usage:l.totalTokens,topCostModel:d,missingPricingModels:m,fuzzyPricingModels:g,models:f}})}function kc(e,{copyFn:t}={}){const a=yo(e,{copyFn:typeof t=="function"?t:d=>d}),r=a.reduce((d,m)=>d+(Number(m?.usage)||0),0),s=a.reduce((d,m)=>d+(Number(m?.usd)||0),0),l=a.flatMap(d=>(d.models||[]).map(m=>({...m,source:d.label}))),i=l.filter(d=>Number.isFinite(Number(d?.cost))&&Number(d.cost)>0).sort((d,m)=>Number(m.cost)-Number(d.cost))[0]||null,c=l.filter(d=>Number.isFinite(Number(d?.usage))&&Number(d.usage)>0).sort((d,m)=>Number(m.usage)-Number(d.usage))[0]||null,u=l.filter(d=>d?.pricingMissing);return{fuzzyPricingModels:l.filter(d=>d?.pricingFuzzy),totalTokens:r,totalCost:s,costPerMillionTokens:r>0?s/(r/1e6):null,topCostModel:i,topUsageModel:c,missingPricingModels:u}}function wc(e,t="—"){const n=Object.entries(e?.models||{});if(!n.length)return t;let a=null,r=-1;for(const[s,l]of n){const i=Number(l);!Number.isFinite(i)||i<=r||(a=s,r=i)}return a||t}function vc(e,{fallback:t="—"}={}){const n=(Array.isArray(e)?e:[]).map(s=>{const l=Sn(s),i=Le(s?.total_cost_usd)??0,c=Number.isFinite(l)&&l>0?i/(l/1e6):null;return{...s,cost_per_million_tokens:c,top_model:wc(s,t)}}),a=n.reduce((s,l)=>{const i=Le(l?.cost_per_million_tokens);return i!=null&&i>0&&s.push(i),s},[]),r=a.length>0?a.reduce((s,l)=>s+l,0)/a.length:null;return n.map(s=>{const l=Le(s?.cost_per_million_tokens),i=l!=null&&r!=null&&r>0&&l>r*1.15;return{...s,cost_per_million_baseline:r,cost_per_million_status:i?"high":"normal"}})}const ut={emerald:{light:["#ebedf0","#a7f3d0","#6ee7b7","#34d399","#10b981"],dark:["#2d333b","#065f46","#059669","#10b981","#34d399"],gridColor:{light:"rgba(16, 185, 129, 0.12)",dark:"rgba(52, 211, 153, 0.08)"}},ocean:{light:["#f1f5f9","#93c5fd","#60a5fa","#3b82f6","#1d4ed8"],dark:["#1e293b","#1e3a8a","#2563eb","#3b82f6","#60a5fa"],gridColor:{light:"rgba(59, 130, 246, 0.12)",dark:"rgba(96, 165, 250, 0.08)"}},neon:{light:["#faf5ff","#ebd5ff","#c084fc","#a855f7","#7e22ce"],dark:["#2e1065","#581c87","#8b5cf6","#a855f7","#c084fc"],gridColor:{light:"rgba(168, 85, 247, 0.12)",dark:"rgba(192, 132, 252, 0.08)"}},amber:{light:["#fffbeb","#fde68a","#f59e0b","#d97706","#b45309"],dark:["#451a03","#78350f","#b45309","#d97706","#f59e0b"],gridColor:{light:"rgba(245, 158, 11, 0.12)",dark:"rgba(245, 158, 11, 0.08)"}}};function Nc(e,t){const n=/^#([0-9a-f]{6})$/i.exec(e);if(!n)return e;const a=parseInt(n[1],16),r=a>>16&255,s=a>>8&255,l=a&255,i=c=>Math.max(0,Math.min(255,Math.round(c*t)));return`rgb(${i(r)}, ${i(s)}, ${i(l)})`}function tt(e,t,n,a,r){const s=Math.cos(a),l=Math.sin(a),i=e*s-t*l,c=e*l+t*s,u=n,f=Math.cos(r),d=Math.sin(r),m=i,g=c*f-u*d,p=c*d+u*f;return{x:m,y:g,z:p}}function _c(e,t,n,a,r){return tt(e,t,n,a,r)}function po(e,t){const n=Number(t).toLocaleString();if(e>=4){const a=Math.floor(Math.random()*3)+1;return y(`heatmap.3d.voxel.joke.${a}`,{value:n})}else return e===3?y("heatmap.3d.voxel.level3",{value:n}):e===2?y("heatmap.3d.voxel.level2",{value:n}):e===1?y("heatmap.3d.voxel.level1",{value:n}):y("heatmap.3d.voxel.level0")}function tr({weeks:e,palette:t="auto",isDark:n=!1,interactive:a=!1,autoRotateInit:r=!1,onResetViewRef:s=null}){const l=ut[t]||(t==="auto"?ut.emerald:null),i=l?n?l.dark:l.light:Array.isArray(t)?t:n?ut.emerald.dark:ut.emerald.light,c=l?n?l.gridColor.dark:l.gridColor.light:n?"rgba(255,255,255,0.06)":"rgba(0,0,0,0.06)",u=-.2,f=.88,[d,m]=h.useState({yaw:u,pitch:f}),[g,p]=h.useState(r),[b,v]=h.useState(1),k=a?13:10.5,j=h.useMemo(()=>{const F=[],U=e.length;if(U===0||!a)return[];for(let Q=0;Q<=7;Q++){const G=(Q-3.5)*k,ne=tt(-U/2*k,G,0,d.yaw,d.pitch),se=tt(U/2*k,G,0,d.yaw,d.pitch);F.push({d:`M${ne.x},${ne.y} L${se.x},${se.y}`,key:`horiz-${Q}`})}for(let Q=0;Q<=U;Q+=4){const G=(Q-U/2)*k,ne=tt(G,-3.5*k,0,d.yaw,d.pitch),se=tt(G,3.5*k,0,d.yaw,d.pitch);F.push({d:`M${ne.x},${ne.y} L${se.x},${se.y}`,key:`vert-${Q}`})}if(U%4!==0){const Q=(U-U/2)*k,G=tt(Q,-3.5*k,0,d.yaw,d.pitch),ne=tt(Q,3.5*k,0,d.yaw,d.pitch);F.push({d:`M${G.x},${G.y} L${ne.x},${ne.y}`,key:"vert-last"})}return F},[e.length,d,k,a]);h.useEffect(()=>{s&&(s.current={reset:()=>{m({yaw:u,pitch:f}),p(!1),v(1),H()},toggleAutoRotate:F=>{p(F)}})},[s]);const x=h.useRef(null),N=h.useRef(null),C=h.useRef(!1),T=h.useRef({x:0,y:0}),z=h.useRef({yaw:u,pitch:f}),$=h.useRef({x:0,y:0}),D=h.useRef({x:0,y:0,time:0}),A=h.useRef(null),[K,B]=h.useState(0),E=h.useRef(null),W=h.useRef(!0);h.useEffect(()=>(W.current=!0,()=>{W.current=!1}),[]);const H=()=>{E.current&&cancelAnimationFrame(E.current),B(0);const F=performance.now(),U=1200,Q=G=>{if(!W.current)return;const ne=G-F,se=Math.min(1,ne/U),ue=1-Math.pow(1-se,3);B(ue),se<1?E.current=requestAnimationFrame(Q):E.current=null};E.current=requestAnimationFrame(Q)};h.useEffect(()=>(H(),()=>{E.current&&cancelAnimationFrame(E.current)}),[a]),h.useEffect(()=>{if(!g||C.current||typeof window>"u"||typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;let U;const Q=()=>{if(typeof document<"u"&&document.visibilityState==="hidden"){U=requestAnimationFrame(Q);return}m(G=>({yaw:G.yaw+.002,pitch:G.pitch})),U=requestAnimationFrame(Q)};return U=requestAnimationFrame(Q),()=>cancelAnimationFrame(U)},[g]);const _=(F,U)=>{a&&(C.current=!0,T.current={x:F,y:U},z.current={yaw:d.yaw,pitch:d.pitch},$.current={x:0,y:0},D.current={x:F,y:U,time:performance.now()},A.current&&cancelAnimationFrame(A.current))},w=(F,U)=>{if(!C.current)return;const Q=F-T.current.x,G=U-T.current.y,ne=performance.now(),se=ne-D.current.time;se>0&&($.current={x:(F-D.current.x)/se,y:(U-D.current.y)/se}),D.current={x:F,y:U,time:ne};const ue=.005,ie=z.current.yaw-Q*ue,me=Math.PI/2.3,De=Math.max(-me,Math.min(me,z.current.pitch-G*ue));m({yaw:ie,pitch:De})},I=()=>{if(!C.current)return;C.current=!1;let F=-$.current.x*12,U=-$.current.y*12;const Q=.95,G=()=>{C.current||(F*=Q,U*=Q,!(Math.abs(F)<.01&&Math.abs(U)<.01)&&(m(ne=>{const se=ne.yaw+F*.005,ue=Math.PI/2.3,ie=Math.max(-ue,Math.min(ue,ne.pitch+U*.005));return{yaw:se,pitch:ie}}),A.current=requestAnimationFrame(G)))};A.current=requestAnimationFrame(G)},[M,J]=h.useState(null),[P,L]=h.useState({x:0,y:0,shiftX:0}),V=h.useRef(null);h.useEffect(()=>()=>{V.current&&clearTimeout(V.current)},[]),h.useEffect(()=>{if(!a||!N.current)return;const F=Q=>{Q.preventDefault();const G=-Q.deltaY*.0025;v(ne=>{const se=ne+G;return Math.max(.5,Math.min(3,se))})},U=N.current;return U.addEventListener("wheel",F,{passive:!1}),()=>{U.removeEventListener("wheel",F)}},[a]);const q=h.useMemo(()=>{const F=[];return e.forEach((U,Q)=>{(Array.isArray(U)?U:[]).forEach((G,ne)=>{G&&F.push({key:G.day||`${Q}-${ne}`,col:Q,row:ne,level:G.level||0,value:G.value||0,total_tokens:G.total_tokens||0,day:G.day,models:G.models||null})})}),F},[e]),ve=k-(a?1.8:1.5),xe=a?38:28,pe=F=>Math.max(1.8,Number(F)/4*xe),Me=h.useMemo(()=>{if(q.length===0)return[];const F=e.length;return q.map(U=>{const Q=pe(U.level),G=Math.sqrt(Math.pow(U.col-F/2,2)+Math.pow(U.row-3.5,2)),ne=Math.sqrt(Math.pow(F/2,2)+Math.pow(3.5,2)),se=G/ne*.4,ue=Math.min(1,Math.max(0,(K-se)*(1/.6))),ie=Q*ue,me=(U.col-F/2)*k,De=(U.row-3.5)*k,ge=ve/2,Ee=[{x:me-ge,y:De-ge,z:0},{x:me+ge,y:De-ge,z:0},{x:me+ge,y:De+ge,z:0},{x:me-ge,y:De+ge,z:0},{x:me-ge,y:De-ge,z:ie},{x:me+ge,y:De-ge,z:ie},{x:me+ge,y:De+ge,z:ie},{x:me-ge,y:De+ge,z:ie}].map(ae=>tt(ae.x,ae.y,ae.z,d.yaw,d.pitch)),Ye=tt(me,De,ie/2,d.yaw,d.pitch),Mt=[{name:"top",indices:[4,5,6,7],scale:1,normal:[0,0,1]},{name:"bottom",indices:[3,2,1,0],scale:.4,normal:[0,0,-1]},{name:"left",indices:[3,0,4,7],scale:.55,normal:[-1,0,0]},{name:"right",indices:[1,2,6,5],scale:.75,normal:[1,0,0]},{name:"front",indices:[0,1,5,4],scale:.85,normal:[0,-1,0]},{name:"back",indices:[2,3,7,6],scale:.65,normal:[0,1,0]}],yt=i[Math.min(4,Math.max(0,Number(U.level)||0))],Ue=[],pt=.35,bt=-.4,re=.83;return Mt.forEach(ae=>{const ee=_c(ae.normal[0],ae.normal[1],ae.normal[2],d.yaw,d.pitch);if(ee.z>.001){const de=Ee[ae.indices[0]],Te=Ee[ae.indices[1]],le=Ee[ae.indices[2]],Ot=Ee[ae.indices[3]],Bt=`M${de.x},${de.y} L${Te.x},${Te.y} L${le.x},${le.y} L${Ot.x},${Ot.y} Z`,Ht=ee.x*pt+ee.y*bt+ee.z*re,jt=n?.18:0,xt=ae.scale*(.82+.28*Math.max(0,Ht))+jt;Ue.push({name:ae.name,d:Bt,fill:Nc(yt,xt)})}}),{...U,centerProj:Ye,renderedFaces:Ue}})},[q,d,i,e.length,K,k,ve,xe]),je=h.useMemo(()=>[...Me].sort((F,U)=>F.centerProj.z-U.centerProj.z),[Me]),ke=h.useMemo(()=>{if(je.length===0)return{minX:-100,minY:-100,maxX:100,maxY:100};let F=1/0,U=1/0,Q=-1/0,G=-1/0;return je.forEach(ne=>{const se=k*2,ue=ne.centerProj.x,ie=ne.centerProj.y;ue-se<F&&(F=ue-se),ue+se>Q&&(Q=ue+se),ie-se<U&&(U=ie-se),ie+se>G&&(G=ie+se)}),{minX:F,minY:U,maxX:Q,maxY:G}},[je,k]),Ce=12,O=ke.maxX-ke.minX+Ce*2,Y=ke.maxY-ke.minY+Ce*2,he=O/b,oe=Y/b,ye=ke.minX-Ce+(O-he)/2,Oe=ke.minY-Ce+(Y-oe)/2,$e=`${ye} ${Oe} ${he} ${oe}`;return q.length===0?o.jsx("div",{className:"py-8 text-center text-sm text-oai-gray-500",children:y("heatmap.empty")}):o.jsxs("div",{ref:N,className:`relative select-none outline-none ${a?"cursor-grab active:cursor-grabbing w-full h-full flex items-center justify-center":"w-full overflow-hidden flex justify-center"}`,onMouseDown:F=>{if(!a)return;_(F.clientX,F.clientY);const U=G=>w(G.clientX,G.clientY),Q=()=>{I(),window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Q)};window.addEventListener("mousemove",U),window.addEventListener("mouseup",Q)},onTouchStart:F=>{!a||F.touches.length===0||_(F.touches[0].clientX,F.touches[0].clientY)},onTouchMove:F=>{!a||F.touches.length===0||w(F.touches[0].clientX,F.touches[0].clientY)},onTouchEnd:()=>{a&&I()},children:[o.jsxs("svg",{ref:x,viewBox:$e,width:a?"95%":"100%",height:a?"95%":"auto",role:"img","aria-label":y("heatmap.iso.aria")||"3D interactive activity heatmap",style:{display:"block",width:"100%",height:"auto",maxWidth:a?"none":`${O}px`,maxHeight:a?"78vh":"none"},className:"transition-transform duration-300 ease-out",children:[a&&j.map(F=>o.jsx("path",{d:F.d,fill:"none",stroke:c,strokeWidth:.25,strokeDasharray:"1.5 2.5",strokeLinecap:"round"},F.key)),je.map(F=>{const U=M&&M.key===F.key;return o.jsxs("g",{onMouseEnter:Q=>{if(V.current&&(clearTimeout(V.current),V.current=null),J(F),a&&x.current){const G=tt((F.col-e.length/2)*k,(F.row-3.5)*k,pe(F.level),d.yaw,d.pitch);let ne=0,se=0;const ue=x.current;if(N.current&&typeof ue.createSVGPoint=="function"&&typeof ue.getScreenCTM=="function")try{const ge=ue.createSVGPoint();ge.x=G.x,ge.y=G.y;const Fe=ue.getScreenCTM();if(Fe){const Ee=ge.matrixTransform(Fe),Ye=N.current.getBoundingClientRect();ne=Ee.x-Ye.left,se=Ee.y-Ye.top}}catch{const Fe=ue.getBoundingClientRect(),Ee=ke.maxX-ke.minX+Ce*2,Ye=ke.maxY-ke.minY+Ce*2;ne=(G.x-(ke.minX-Ce))/Ee*Fe.width,se=(G.y-(ke.minY-Ce))/Ye*Fe.height}else{const ge=ue.getBoundingClientRect(),Fe=ke.maxX-ke.minX+Ce*2,Ee=ke.maxY-ke.minY+Ce*2;ne=(G.x-(ke.minX-Ce))/Fe*ge.width,se=(G.y-(ke.minY-Ce))/Ee*ge.height}const ie=140;let me=0;const De=N.current?N.current.getBoundingClientRect().width:ue.getBoundingClientRect().width;ne<ie?me=ie-ne:ne>De-ie&&(me=De-ie-ne),L({x:ne,y:se,shiftX:me})}},onMouseLeave:()=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{J(null)},150)},className:"transition-all duration-200",style:{filter:U?"brightness(1.15) drop-shadow(0 4px 6px rgba(0,0,0,0.15))":"none",cursor:a?"pointer":"default"},children:[!a&&F.day&&o.jsx("title",{children:`${F.day}: ${Number(F.value).toLocaleString()} conversations`}),F.renderedFaces.map((Q,G)=>o.jsx("path",{d:Q.d,fill:Q.fill,stroke:Q.fill,strokeWidth:.25,strokeLinejoin:"round"},G))]},F.key)})]}),a&&M&&o.jsxs("div",{onMouseEnter:()=>{V.current&&(clearTimeout(V.current),V.current=null)},onMouseLeave:()=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{J(null)},150)},className:"absolute z-[9999] w-0 h-0 transition-all duration-100 ease-out",style:{left:`${P.x}px`,top:`${P.y}px`},children:[o.jsxs("div",{className:"absolute left-0 bottom-[10px] backdrop-blur-md bg-white/90 dark:bg-oai-gray-900/90 border border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-xl rounded-xl p-3.5 max-w-[280px] min-w-[200px] flex flex-col gap-2 animate-in fade-in zoom-in-95 duration-100",style:{transform:`translateX(calc(-50% + ${P.shiftX}px))`},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-oai-gray-100 dark:border-oai-gray-800/80 pb-1.5",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400",children:M.day}),(()=>{const F=M.level===0?n?"#9ca3af":"#6b7280":i[M.level];return o.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:F+"22",color:F,border:`1px solid ${F}44`},children:["Level ",M.level]})})()]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-lg font-bold text-oai-gray-900 dark:text-white leading-none tabular-nums",children:Number(M.value??0).toLocaleString()}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 uppercase tracking-wider font-semibold",children:"Conversations"})]}),o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400 leading-none tabular-nums",children:Number(M.total_tokens??0).toLocaleString()}),o.jsx("span",{className:"text-[9px] text-oai-gray-400 uppercase tracking-wider",children:"tokens"})]})]}),M.models&&Object.keys(M.models).length>0?o.jsxs("div",{className:"mt-1.5 border-t border-oai-gray-100 dark:border-oai-gray-800/60 pt-2 flex flex-col gap-1.5",children:[o.jsx("div",{className:"text-[10px] font-semibold text-oai-gray-400 dark:text-oai-gray-500 uppercase tracking-wider",children:"Model Breakdown"}),o.jsx("div",{className:"flex flex-col gap-2 max-h-[150px] overflow-y-auto pr-1.5 scrollbar-thin",children:Object.entries(M.models).map(([F,U])=>({name:F,val:Number(U)})).sort((F,U)=>U.val-F.val).map(({name:F,val:U})=>{const Q=Number(M.total_tokens)||Object.values(M.models).reduce((ne,se)=>ne+Number(se||0),0)||1,G=Math.round(U/Q*100);return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] gap-3",children:[o.jsx("span",{className:"font-medium text-oai-gray-750 dark:text-oai-gray-200 truncate max-w-[120px]",title:F,children:F}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx("span",{className:"font-mono text-oai-gray-900 dark:text-oai-gray-100 font-semibold",children:U.toLocaleString()}),o.jsxs("span",{className:"text-[9px] text-oai-gray-450 dark:text-oai-gray-500 min-w-[28px] text-right font-medium",children:[G,"%"]})]})]}),o.jsx("div",{className:"w-full h-1 bg-oai-gray-100 dark:bg-oai-gray-800/85 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${G}%`,backgroundColor:i[4],boxShadow:`0 0 4px ${i[4]}55`}})})]},F)})})]}):o.jsx("p",{className:"text-[11px] text-oai-gray-600 dark:text-oai-gray-300 leading-relaxed font-normal mt-1 border-t border-dashed border-oai-gray-100 dark:border-oai-gray-800/60 pt-1.5",children:po(M.level,M.value)})]})]}),o.jsx("div",{className:"absolute bottom-[6px] left-0 -translate-x-1/2 w-2.5 h-2.5 rotate-45 bg-white dark:bg-oai-gray-900 border-r border-b border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-sm",style:{marginBottom:"1px"}})]})]})}const Mc=12,jc=3,Sc=26,Cc=["#ebedf0","#f7d08a","#f2b757","#eca02f","#d9861a"],Dc=["#30363d","#7a4711","#bf7015","#eca02f","#f7c877"];function nr(e){const t=Number(e);return Number.isFinite(t)?t<1e3?t.toLocaleString():Ae(t,{decimals:2}):"0"}function Tc(e){if(typeof e!="string")return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;const n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return Number.isFinite(n.getTime())?n:null}function bo(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function Pc(e,t){return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))/864e5)}function Oc(e,t){const n=t==="mon"?1:0,a=e.getUTCDay();return bo(e,-((a-n+7)%7))}function $c(e,t,n,a){if(!e)return[];const r=Tc(t)||new Date,s=[];for(let f=11;f>=0;f-=1)s.push(new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth()-f,1)));const l=Oc(r,n),i=bo(l,-(e-1)*7),c=[],u=new Set;for(const f of s){const d=Math.floor(Pc(i,f)/7);d<0||d>=e||u.has(d)||(u.add(d),c.push({label:a[f.getUTCMonth()],index:d}))}return c}function Ec({heatmap:e,timeZoneLabel:t,timeZoneShortLabel:n,hideLegend:a=!1,embedded:r=!1}){const{resolvedTheme:s}=Gr(),{currency:l,rate:i}=_t(),c=s==="dark",u=c?Dc:Cc,f=h.useRef(null),d=h.useRef(null),[m,g]=h.useState(null),[p,b]=h.useState({x:0,y:0,shiftX:0}),v=h.useRef(null);h.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const[k,j]=h.useState(!1),[x,N]=h.useState(!1),[C,T]=h.useState(!1),z=h.useRef(null),[$,D]=h.useState("amber"),A=[y("heatmap.month.jan"),y("heatmap.month.feb"),y("heatmap.month.mar"),y("heatmap.month.apr"),y("heatmap.month.may"),y("heatmap.month.jun"),y("heatmap.month.jul"),y("heatmap.month.aug"),y("heatmap.month.sep"),y("heatmap.month.oct"),y("heatmap.month.nov"),y("heatmap.month.dec")],K=(O,Y)=>{if(!Y||!Y.day)return;v.current&&(clearTimeout(v.current),v.current=null),g(Y);const he=O.currentTarget.getBoundingClientRect(),oe=typeof window<"u"?window.innerWidth:1024,ye=he.left+he.width/2,Oe=he.top,$e=140;let F=0;ye<$e?F=$e-ye:ye>oe-$e&&(F=oe-$e-ye),b({x:ye,y:Oe,shiftX:F})},B=()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{g(null)},150)},E=()=>{N(!1),j(!0)},W=()=>{N(!0)},H=O=>{O.target===O.currentTarget&&x&&(j(!1),N(!1))};h.useEffect(()=>{if(!k||x)return;const O=Y=>{Y.key==="Escape"&&W()};return window.addEventListener("keydown",O),()=>{window.removeEventListener("keydown",O)}},[k,x]);const _=h.useMemo(()=>({emerald:{accentText:"text-emerald-500 dark:text-emerald-400",accentBg:"bg-emerald-500/10 dark:bg-emerald-400/10",accentBorder:"border-emerald-500/20 dark:border-emerald-400/15",hoverBorder:"hover:border-emerald-500/30 dark:hover:border-emerald-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(16,185,129,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(52,211,153,0.25)]",rawColor:"#10b981"},ocean:{accentText:"text-blue-500 dark:text-blue-400",accentBg:"bg-blue-500/10 dark:bg-blue-400/10",accentBorder:"border-blue-500/20 dark:border-blue-400/15",hoverBorder:"hover:border-blue-500/30 dark:hover:border-blue-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(59,130,246,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(96,165,250,0.25)]",rawColor:"#3b82f6"},neon:{accentText:"text-purple-500 dark:text-purple-400",accentBg:"bg-purple-500/10 dark:bg-purple-400/10",accentBorder:"border-purple-500/20 dark:border-purple-400/15",hoverBorder:"hover:border-purple-500/30 dark:hover:border-purple-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(168,85,247,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(192,132,252,0.25)]",rawColor:"#a855f7"},amber:{accentText:"text-amber-500 dark:text-amber-400",accentBg:"bg-amber-500/10 dark:bg-amber-400/10",accentBorder:"border-amber-500/20 dark:border-amber-400/15",hoverBorder:"hover:border-amber-500/30 dark:hover:border-amber-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(245,158,11,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(245,158,11,0.25)]",rawColor:"#f59e0b"}}),[]),w=_[$]||_.emerald,I=ut[$]?c?ut[$].dark:ut[$].light:c?ut.emerald.dark:ut.emerald.light,[M,J]=h.useState(()=>{if(r)return"2d";try{return window.localStorage?.getItem("tt:heatmap-view")==="3d"?"3d":"2d"}catch{return"2d"}});h.useEffect(()=>{if(!r)try{window.localStorage?.setItem("tt:heatmap-view",M)}catch{}},[M,r]),h.useEffect(()=>{if(M!=="2d")return;const O=f.current;O&&(O.scrollLeft=O.scrollWidth)},[e?.weeks,M]),h.useEffect(()=>{const O=f.current;if(!O)return;const Y=()=>{v.current&&(clearTimeout(v.current),v.current=null),g(null)};return O.addEventListener("scroll",Y),()=>O.removeEventListener("scroll",Y)},[]);const P=e?.week_starts_on==="mon"?"mon":"sun",L=h.useMemo(()=>{const O=Array.isArray(e?.weeks)?e.weeks:[];if(!O.length)return{weeks:[]};const Y=[];for(const he of O)for(const oe of Array.isArray(he)?he:[])oe?.day&&Y.push({day:oe.day,conversation_count:oe.conversation_count??0,total_tokens:oe.total_tokens??0,billable_total_tokens:oe.billable_total_tokens??oe.total_tokens??0,models:oe.models??null});return Zn({dailyRows:Y,weeks:Math.max(52,O.length),to:e?.to,weekStartsOn:P})},[e?.to,e?.weeks,P]),V=L?.weeks||[],q=h.useMemo(()=>{let O=0,Y=0,he={day:"无数据",value:0},oe=0,ye=0;const Oe=[];V.forEach(ie=>{(Array.isArray(ie)?ie:[]).forEach(me=>{me&&me.day&&Oe.push(me)})}),Oe.sort((ie,me)=>ie.day.localeCompare(me.day)),Oe.forEach(ie=>{const me=Number(ie.value)||0;O+=Number(ie.total_tokens)||0,me>0?(Y++,oe++,oe>ye&&(ye=oe)):oe=0,me>he.value&&(he={day:ie.day,value:me})});const $e=Oe.length||365,F=(Y/$e*100).toFixed(1);let U="heatmap.3d.modal.ai.eval.default",Q="heatmap.3d.modal.ai.title.default";O>=15e6?(Q="heatmap.3d.modal.ai.title.peak",U="heatmap.3d.modal.ai.eval.peak"):O>=5e6?(Q="heatmap.3d.modal.ai.title.heavy",U="heatmap.3d.modal.ai.eval.heavy"):O>=1e6?(Q="heatmap.3d.modal.ai.title.core",U="heatmap.3d.modal.ai.eval.core"):O>=2e4&&(Q="heatmap.3d.modal.ai.title.steady",U="heatmap.3d.modal.ai.eval.steady");const G=e?.total_cost_usd,ne=Number(G),ue=G!=null&&(typeof G!="string"||G.trim()!=="")&&Number.isFinite(ne)?ne:O/15e5;return{totalTokens:O,activeDays:Y,activeRate:F,maxSingleDay:he,maxStreak:ye,aiEvaluationTitleKey:Q,aiEvaluationKey:U,totalCostUsd:ue}},[V,e?.total_cost_usd]),fe=h.useMemo(()=>et(q.totalCostUsd,{currency:l,rate:i}),[q.totalCostUsd,l,i]),ve=P==="mon"?["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(O=>y(`heatmap.day.${O.toLowerCase()}`)):["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(O=>y(`heatmap.day.${O.toLowerCase()}`)),xe=h.useMemo(()=>$c(V.length,L?.to,P,A),[L?.to,V.length,P,A]);if(!V.length)return o.jsx("div",{className:"py-8 text-center text-sm text-oai-gray-500",children:y("heatmap.empty")});const pe=r?10:Mc,Me=r?2:jc,je=r?22:Sc,ke=je+V.length*pe+Math.max(0,V.length-1)*Me,Ce=`${je}px repeat(${V.length}, ${pe}px)`;return o.jsxs("div",{ref:d,className:r?"relative":"relative rounded-xl border border-oai-gray-200 dark:border-oai-gray-800 bg-white dark:bg-oai-gray-900 p-5",children:[!r&&o.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[o.jsx("h3",{className:"text-sm font-medium text-oai-gray-500 dark:text-oai-gray-300 uppercase tracking-wide",children:y("heatmap.title")}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("div",{role:"tablist","aria-label":"Heatmap view",className:"flex rounded-md border border-oai-gray-200 dark:border-oai-gray-800 p-0.5 text-[10px]",children:[o.jsx("button",{type:"button",role:"tab","aria-selected":M==="2d",onClick:()=>J("2d"),className:M==="2d"?"px-2 py-0.5 rounded bg-oai-gray-100 text-oai-black dark:bg-oai-gray-800 dark:text-oai-white font-medium":"px-2 py-0.5 rounded text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-700 dark:hover:text-oai-gray-200",children:y("heatmap.view.2d")}),o.jsx("button",{type:"button",role:"tab","aria-selected":M==="3d",onClick:()=>J("3d"),className:M==="3d"?"px-2 py-0.5 rounded bg-oai-gray-100 text-oai-black dark:bg-oai-gray-800 dark:text-oai-white font-medium":"px-2 py-0.5 rounded text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-700 dark:hover:text-oai-gray-200",children:y("heatmap.view.3d")})]}),o.jsx("span",{className:"text-xs text-oai-gray-400 dark:text-oai-gray-450",children:n||y("heatmap.legend.utc")})]})]}),M==="3d"&&o.jsxs("div",{onClick:E,className:"cursor-pointer group relative overflow-hidden rounded-lg hover:border-oai-gray-350 dark:hover:border-oai-gray-700 border border-transparent transition-all",title:y("heatmap.3d.hover_tip"),children:[o.jsx(tr,{weeks:V,isDark:c,palette:$}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-oai-gray-900/5 to-transparent pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-2",children:o.jsxs("span",{className:"text-[10px] bg-white/95 dark:bg-oai-gray-900/95 shadow border border-oai-gray-200/60 dark:border-oai-gray-800/80 px-2.5 py-1 rounded-full font-medium text-oai-gray-500 dark:text-oai-gray-400 flex items-center gap-1 transform translate-y-2 group-hover:translate-y-0 transition-transform duration-200",children:[o.jsx(ao,{size:9}),y("heatmap.3d.hover_tip")]})})]}),M==="2d"&&o.jsx("div",{ref:f,className:"overflow-x-auto overflow-y-hidden heatmap-scroll-thin",children:o.jsxs("div",{style:{minWidth:ke},children:[o.jsxs("div",{className:"grid text-[10px] uppercase text-oai-gray-400 dark:text-oai-gray-400 mb-1",style:{gridTemplateColumns:Ce,columnGap:Me},children:[o.jsx("span",{}),xe.map(O=>o.jsx("span",{style:{gridColumnStart:O.index+2},className:"whitespace-nowrap",children:O.label},`${O.label}-${O.index}`))]}),o.jsxs("div",{className:"grid",style:{gridTemplateColumns:Ce,columnGap:Me},children:[o.jsx("div",{className:"grid text-[10px] text-oai-gray-400 dark:text-oai-gray-400 sticky left-0 bg-white dark:bg-oai-gray-900 pr-2",style:{gridTemplateRows:`repeat(7, ${pe}px)`,rowGap:Me},children:ve.map(O=>o.jsx("span",{className:"leading-none",children:O},O))}),o.jsx("div",{className:"grid",style:{gridAutoFlow:"column",gridTemplateRows:`repeat(7, ${pe}px)`,gap:Me},children:V.map((O,Y)=>(Array.isArray(O)?O:[]).map((he,oe)=>{if(!he)return null;const ye=he.day||`e-${Y}-${oe}`,Oe=Number(he.level)||0,$e=u[Oe]||u[0];return o.jsx("span",{onMouseEnter:F=>K(F,he),onMouseLeave:B,className:"rounded-[2px] transition-transform hover:scale-125 hover:z-10 cursor-pointer",style:{width:pe,height:pe,background:$e}},ye)}))})]})]})}),!a&&o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[o.jsx("span",{className:"text-[10px] text-oai-gray-400 dark:text-oai-gray-400",children:y("heatmap.legend.less")}),o.jsx("div",{className:"flex gap-0.5",children:u.map((O,Y)=>o.jsx("span",{className:"rounded-[1px]",style:{width:10,height:10,background:O}},Y))}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 dark:text-oai-gray-400",children:y("heatmap.legend.more")})]}),k&&o.jsx("div",{onAnimationEnd:H,onClick:O=>{O.target===O.currentTarget&&W()},className:`fixed inset-0 z-50 flex items-center justify-center p-3 md:p-6 backdrop-blur-md bg-black/15 dark:bg-black/40 ${x?"animate-tt-fade-out":"animate-tt-fade-in"}`,children:o.jsxs("div",{className:`relative w-full max-w-6xl h-[88vh] backdrop-blur-2xl bg-white/90 dark:bg-oai-gray-900/90 border border-oai-gray-200/50 dark:border-white/10 shadow-2xl rounded-2xl flex flex-col md:flex-row overflow-hidden ${x?"animate-tt-modal-exit":"animate-tt-modal"}`,children:[o.jsx("button",{type:"button",onClick:W,className:"absolute top-4 right-4 z-50 p-2 rounded-full border border-oai-gray-200/60 dark:border-oai-gray-800/60 bg-white/50 dark:bg-oai-gray-900/50 text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-900 dark:hover:text-white hover:rotate-90 hover:scale-105 active:scale-95 transition-all duration-300",children:o.jsx(da,{size:16})}),o.jsxs("div",{className:"w-full md:w-[340px] border-b md:border-b-0 md:border-r border-zinc-200/50 dark:border-zinc-800/40 p-5 md:p-6 flex flex-col gap-6 overflow-y-auto backdrop-blur-md bg-zinc-50/50 dark:bg-zinc-950/50",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1.5 select-none",children:[o.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",style:{backgroundColor:w.rawColor}}),o.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5",style:{backgroundColor:w.rawColor}})]}),o.jsx("span",{className:"text-[9px] font-extrabold uppercase tracking-widest font-mono text-zinc-400 dark:text-zinc-500",children:"3D Insight"})]}),o.jsx("h4",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight leading-none mt-2 select-none",children:y("heatmap.3d.modal.title")}),o.jsx("p",{className:"text-[11px] leading-relaxed text-zinc-400 dark:text-zinc-500 mt-2 font-normal select-none",children:y("heatmap.3d.modal.desc")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-x-5 gap-y-5 border-y border-zinc-200/50 dark:border-zinc-800/50 py-5 select-none",children:[o.jsxs("div",{className:"flex flex-col gap-1 relative group cursor-help",children:[o.jsx("div",{className:"absolute left-0 bottom-full mb-2 pointer-events-none opacity-0 translate-y-1 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-200 z-50",children:o.jsxs("div",{className:"bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50 text-[10px] font-semibold font-mono rounded-lg px-2.5 py-1.5 shadow-xl border border-zinc-200 dark:border-zinc-800/80 whitespace-nowrap flex flex-col",children:[o.jsx("span",{className:"text-[9px] text-zinc-400 dark:text-zinc-500",children:y("heatmap.3d.modal.stats.precision_total_tokens")}),o.jsxs("span",{className:"mt-0.5 font-bold text-zinc-900 dark:text-zinc-50",children:[q.totalTokens.toLocaleString()," Tokens"]})]})}),o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.total_tokens")}),o.jsxs("div",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:nr(q.totalTokens)}),o.jsx("div",{className:"opacity-30 group-hover:opacity-60 transition-opacity",children:o.jsx("svg",{width:"24",height:"10",viewBox:"0 0 24 10",fill:"none",children:o.jsx("path",{d:"M1 9C3 7 5 7 7 4C9 1 11 0 13 2C15 4 17 0 23 0",stroke:w.rawColor,strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.estimated_cost")}),o.jsx("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:fe})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.active_rate_days")}),o.jsxs("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.activeRate,"% ",o.jsxs("span",{className:"text-[10px] font-bold text-zinc-400 dark:text-zinc-500 font-mono",children:["(",q.activeDays,"D)"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.max_streak")}),o.jsxs("span",{className:"text-xl font-black text-amber-500 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.maxStreak," ",o.jsx("span",{className:"text-[10px] font-bold text-amber-500/80 font-mono",children:y("heatmap.3d.modal.stats.days_suffix")})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 col-span-2 relative group cursor-help",children:[o.jsx("div",{className:"absolute left-0 bottom-full mb-2 pointer-events-none opacity-0 translate-y-1 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-200 z-50",children:o.jsxs("div",{className:"bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50 text-[10px] font-semibold font-mono rounded-lg px-2.5 py-1.5 shadow-xl border border-zinc-200 dark:border-zinc-800/80 whitespace-nowrap flex flex-col",children:[o.jsx("span",{className:"text-[9px] text-zinc-400 dark:text-zinc-500",children:y("heatmap.3d.modal.stats.precision_peak_value")}),o.jsxs("span",{className:"mt-0.5 font-bold text-zinc-900 dark:text-zinc-50",children:[q.maxSingleDay.value>0?q.maxSingleDay.value.toLocaleString():y("heatmap.3d.modal.stats.no_data")," conversations"]}),o.jsx("span",{className:"text-[8px] text-zinc-400 dark:text-zinc-500 mt-0.5",children:q.maxSingleDay.day!=="无数据"?q.maxSingleDay.day:y("heatmap.3d.modal.stats.no_data")})]})}),o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.peak_day")}),o.jsxs("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.maxSingleDay.value>0?nr(q.maxSingleDay.value):y("heatmap.3d.modal.stats.no_data")," ",o.jsxs("span",{className:"text-[10px] font-bold text-zinc-400 dark:text-zinc-500 font-mono",children:["(",q.maxSingleDay.day!=="无数据"?q.maxSingleDay.day:y("heatmap.3d.modal.stats.no_data"),")"]})]})]})]}),o.jsxs("div",{className:"flex flex-col gap-2.5 py-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5 select-none",children:[o.jsx(ro,{size:11,style:{color:w.rawColor}}),o.jsx("span",{className:"text-[9px] font-extrabold uppercase tracking-widest font-mono",style:{color:w.rawColor},children:y(q.aiEvaluationTitleKey)})]}),o.jsxs("div",{className:"pl-3.5 border-l-2 relative transition-all duration-300 group",style:{borderColor:w.rawColor},children:[o.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px] blur-[2px] opacity-15 pointer-events-none rounded-full",style:{backgroundColor:w.rawColor}}),o.jsx("p",{className:"text-[11px] leading-relaxed text-zinc-600 dark:text-zinc-400 font-normal",children:y(q.aiEvaluationKey)})]})]}),o.jsx("div",{className:"mt-auto border-t border-zinc-200/50 dark:border-zinc-800/50 pt-4 select-none",children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.legend.title")}),o.jsx("span",{className:"text-[10px] font-medium text-zinc-500 dark:text-zinc-400",children:y(`heatmap.3d.modal.palette.${$}`)})]}),o.jsx("div",{className:"flex gap-1",children:I.map((O,Y)=>o.jsx("div",{className:"flex-1 h-1 rounded-[2px]",style:{backgroundColor:O},title:`Level ${Y}`},Y))})]})})]}),o.jsxs("div",{className:"flex-1 h-full relative flex items-center justify-center overflow-hidden p-4",children:[o.jsx("div",{className:"absolute top-1/4 left-1/3 w-96 h-96 rounded-full blur-[130px] pointer-events-none -translate-x-1/2 -translate-y-1/2 transition-all duration-500",style:{backgroundColor:w.rawColor+"15"}}),o.jsx("div",{className:"absolute bottom-1/4 right-1/3 w-80 h-80 rounded-full blur-[120px] pointer-events-none translate-x-1/2 translate-y-1/2 bg-purple-500/[0.04] dark:bg-purple-500/[0.08]"}),o.jsxs("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 flex items-center gap-3 p-1.5 backdrop-blur-md bg-white/70 dark:bg-oai-gray-900/75 border border-oai-gray-200/60 dark:border-oai-gray-800/80 rounded-full shadow-lg z-30 select-none",children:[o.jsx("div",{className:"flex items-center gap-1.5 px-2",children:Object.keys(_).map(O=>{const Y=$===O;return o.jsx("button",{type:"button",onClick:()=>D(O),title:y(`heatmap.3d.modal.palette.${O}`),className:`w-3.5 h-3.5 rounded-full transition-all duration-200 relative hover:scale-125 ${O==="emerald"?"bg-[#10b981]":O==="ocean"?"bg-[#3b82f6]":O==="neon"?"bg-[#a855f7]":"bg-[#f59e0b]"}`,children:Y&&o.jsx("span",{className:"absolute inset-0 rounded-full ring-2 ring-offset-1 ring-offset-white dark:ring-offset-oai-gray-900 ring-oai-gray-900 dark:ring-white scale-110"})},O)})}),o.jsx("div",{className:"w-[1px] h-4 bg-oai-gray-200 dark:bg-oai-gray-800"}),o.jsxs("div",{className:"flex items-center gap-1 pr-1",children:[o.jsx("button",{type:"button",onClick:()=>{const O=!C;T(O),z.current&&z.current.toggleAutoRotate(O)},title:C?y("heatmap.3d.modal.control.pause"):y("heatmap.3d.modal.control.play"),className:`p-1.5 rounded-full transition-all duration-200 hover:bg-oai-gray-100 dark:hover:bg-oai-gray-800 ${C?w.accentText:"text-oai-gray-400 hover:text-oai-gray-600 dark:hover:text-oai-gray-250"}`,children:C?o.jsx(qi,{size:12}):o.jsx(Gi,{size:12})}),o.jsx("button",{type:"button",onClick:()=>{T(!1),z.current&&z.current.reset()},title:y("heatmap.3d.modal.control.reset"),className:"p-1.5 rounded-full text-oai-gray-400 hover:text-oai-gray-600 dark:hover:text-oai-gray-250 hover:bg-oai-gray-100 dark:hover:bg-oai-gray-800 transition-all duration-200",children:o.jsx(Qi,{size:12})})]})]}),o.jsx(tr,{weeks:V,isDark:c,interactive:!0,palette:$,autoRotateInit:C,onResetViewRef:z}),o.jsxs("div",{className:"absolute bottom-4 right-4 flex items-center gap-1.5 text-[9px] font-bold text-oai-gray-400 bg-white/80 dark:bg-oai-gray-900/80 border border-oai-gray-200/50 dark:border-oai-gray-800/80 rounded-md px-2.5 py-1.5 select-none pointer-events-none backdrop-blur-md shadow-sm",children:[o.jsx(ma,{size:10,className:w.accentText}),o.jsx("span",{children:y("heatmap.3d.modal.footer.tip")})]})]})]})}),m&&!k&&typeof document<"u"&&gi.createPortal(o.jsxs("div",{className:"fixed z-[9999] w-0 h-0 transition-all duration-100 ease-out pointer-events-none",style:{left:`${p.x}px`,top:`${p.y}px`},children:[o.jsxs("div",{className:"absolute left-0 bottom-[10px] backdrop-blur-md bg-white/95 dark:bg-oai-gray-900/95 border border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-xl rounded-xl p-3.5 max-w-[280px] min-w-[200px] flex flex-col gap-2 animate-in fade-in zoom-in-95 duration-100",style:{transform:`translateX(calc(-50% + ${p.shiftX}px))`},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-oai-gray-100 dark:border-oai-gray-800/80 pb-1.5",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400",children:m.day}),(()=>{const O=m.level===0?c?"#9ca3af":"#6b7280":u[m.level];return o.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:O+"22",color:O,border:`1px solid ${O}44`},children:["Level ",m.level]})})()]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-lg font-bold text-oai-gray-900 dark:text-white leading-none tabular-nums",children:Number(m.value??0).toLocaleString()}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 uppercase tracking-wider font-semibold",children:"Conversations"})]}),o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400 leading-none tabular-nums",children:Number(m.total_tokens??0).toLocaleString()}),o.jsx("span",{className:"text-[9px] text-oai-gray-400 uppercase tracking-wider",children:"tokens"})]})]}),m.models&&Object.keys(m.models).length>0?o.jsxs("div",{className:"mt-1.5 border-t border-oai-gray-100 dark:border-oai-gray-800/60 pt-2 flex flex-col gap-1.5",children:[o.jsx("div",{className:"text-[10px] font-semibold text-oai-gray-400 dark:text-oai-gray-500 uppercase tracking-wider",children:"Model Breakdown"}),o.jsx("div",{className:"flex flex-col gap-2 max-h-[150px] overflow-y-auto pr-1.5 oai-scrollbar",children:Object.entries(m.models).map(([O,Y])=>({name:O,val:Number(Y)})).sort((O,Y)=>Y.val-O.val).map(({name:O,val:Y})=>{const he=Number(m.total_tokens??m.value)||1,oe=Math.round(Y/he*100);return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] gap-3",children:[o.jsx("span",{className:"font-medium text-oai-gray-750 dark:text-oai-gray-200 truncate max-w-[120px]",title:O,children:O}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx("span",{className:"font-mono text-oai-gray-900 dark:text-oai-gray-100 font-semibold",children:Y.toLocaleString()}),o.jsxs("span",{className:"text-[9px] text-oai-gray-450 dark:text-oai-gray-500 min-w-[28px] text-right font-medium",children:[oe,"%"]})]})]}),o.jsx("div",{className:"w-full h-1 bg-oai-gray-100 dark:bg-oai-gray-800/85 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${oe}%`,backgroundColor:u[4],boxShadow:`0 0 4px ${u[4]}55`}})})]},O)})})]}):o.jsx("p",{className:"text-[11px] text-oai-gray-600 dark:text-oai-gray-300 leading-relaxed font-normal mt-1 border-t border-dashed border-oai-gray-100 dark:border-oai-gray-800/60 pt-1.5",children:po(m.level,m.total_tokens??m.value)})]})]}),o.jsx("div",{className:"absolute bottom-[6px] left-0 -translate-x-1/2 w-2.5 h-2.5 rotate-45 bg-white dark:bg-oai-gray-900 border-r border-b border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-sm",style:{marginBottom:"1px"}})]}),document.body),o.jsx("style",{children:`
1
+ import{c as rn,i as oi,f as Ur,a as Vr,J as si,u as qr,m as ii,r as h,M as Xr,b as li,d as ci,e as Fn,j as o,L as di,g as ui,h as fi,k as mi,l as hi,n as zt,o as gt,p as y,q as Gr,X as da,s as gi,R,t as ua,C as Kr,P as fa,B as Jn,v as Qr,w as Jr,A as Zr,x as Xe,y as yi,z as pi,D as bi,E as xi,F as ki}from"./main-rZD26_5f.js";import{g as wi,i as Yt,b as Zn,c as pn,a as on,d as tn,f as ht,e as eo,h as to,j as vi,k as Ni,l as _i,m as Mi}from"./mock-data-C1NPjE59.js";import{g as ji,a as Cn,b as Si,c as Ci,d as no,e as Rn,f as Di,h as Ti,L as Pi,i as Oi,j as $i,u as Ei,t as Ua}from"./limitDisplay-DhC8fM_W.js";import{u as Wi}from"./use-limits-display-prefs-vLrVb6Bn.js";import{u as _t,I as ma}from"./useCurrency-MOYNpGd7.js";import{t as Le,f as et,a as Ae,b as Qe}from"./format-C3ekCmoV.js";import{u as Ai,D as Fi,a as Ri,b as Ii,c as Li,d as zi,e as Yi,P as ea,f as ta,g as na,h as aa,i as ra,L as Bi}from"./PopoverPopup-BTJTO2ZT.js";import{C as sn}from"./Card-G3yjiaQ3.js";import{S as Hi}from"./Select-_DHMSUO0.js";import{F as ct}from"./FadeIn-Bcqp5CE1.js";import"./SelectItemText-CFGxP_cw.js";const Ui=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],ao=rn("maximize-2",Ui);const Vi=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],qi=rn("pause",Vi);const Xi=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Gi=rn("play",Xi);const Ki=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Qi=rn("rotate-ccw",Ki);const Ji=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ro=rn("terminal",Ji);function Zi(...e){const t=!Array.isArray(e[0]),n=t?0:-1,a=e[0+n],r=e[1+n],s=e[2+n],l=e[3+n],i=oi(r,s,l);return t?i(a):i}function el(e,t,n={}){const a=e.get();let r=null,s=a,l;const i=typeof a=="string"?a.replace(/[\d.-]/g,""):void 0,c=()=>{r&&(r.stop(),r=null),e.animation=void 0},u=()=>{const d=Va(e.get()),m=Va(s);if(d===m){c();return}const g=r?r.getGeneratorVelocity():e.getVelocity();c(),r=new si({keyframes:[d,m],velocity:g,type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:l})},f=()=>{u(),e.animation=r??void 0,e.events.animationStart?.notify(),r?.then(()=>{e.animation=void 0,e.events.animationComplete?.notify()})};if(e.attach((d,m)=>{s=d,l=g=>m(In(g,i)),Ur.postRender(f)},c),Vr(t)){let d=n.skipInitialAnimation===!0;const m=t.on("change",p=>{d?(d=!1,e.jump(In(p,i),!1)):e.set(In(p,i))}),g=e.on("destroy",m);return()=>{m(),g()}}return c}function In(e,t){return t?e+t:e}function Va(e){return typeof e=="number"?e:parseFloat(e)}function ha(e){const t=qr(()=>ii(e)),{isStatic:n}=h.useContext(Xr);if(n){const[,a]=h.useState(e);h.useEffect(()=>t.on("change",a),[])}return t}function oo(e,t){const n=ha(t()),a=()=>n.set(t());return a(),li(()=>{const r=()=>Ur.preRender(a,!1,!0),s=e.map(l=>l.on("change",r));return()=>{s.forEach(l=>l()),ci(a)}}),n}function tl(e){Fn.current=[],e();const t=oo(Fn.current,e);return Fn.current=void 0,t}function so(e,t,n,a){if(typeof e=="function")return tl(e);const s=typeof t=="function"?t:Zi(t,n,a),l=Array.isArray(e)?qa(e,s):qa([e],([c])=>s(c)),i=Array.isArray(e)?void 0:e.accelerate;return i&&!i.isTransformed&&typeof t!="function"&&Array.isArray(n)&&a?.clamp!==!1&&(l.accelerate={...i,times:t,keyframes:n,isTransformed:!0}),l}function qa(e,t){const n=qr(()=>[]);return oo(e,()=>{n.length=0;const a=e.length;for(let r=0;r<a;r++)n[r]=e[r].get();return t(n)})}function nl(e,t={}){const{isStatic:n}=h.useContext(Xr),a=()=>Vr(e)?e.get():e;if(n)return so(a);const r=ha(a());return h.useInsertionEffect(()=>el(r,e,t),[r,JSON.stringify(t)]),r}function al(e,t={}){return nl(e,{type:"spring",...t})}function rl(){return o.jsxs(di,{to:"/landing",className:"flex items-center gap-2.5 no-underline hover:opacity-80 transition-opacity",children:[o.jsx("img",{src:"/app-icon.png",alt:"Token Tracker",width:28,height:28,className:"rounded-md"}),o.jsx("span",{className:"text-base font-semibold text-oai-black dark:text-oai-white leading-tight",children:"Token Tracker"})]})}function ol({children:e,header:t,footer:n,className:a="",hideHeader:r=!1,hideFooter:s=!1,bare:l=!1}){return l?o.jsxs("div",{className:`flex flex-col flex-1 min-h-0 ${a}`,children:[o.jsx("main",{className:"flex-1 px-6 py-6",children:e}),!s&&n&&o.jsx("footer",{className:"border-t border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 mt-auto transition-colors duration-200",children:n})]}):o.jsxs("div",{className:`min-h-screen bg-oai-white dark:bg-oai-gray-950 text-oai-black dark:text-oai-white font-sans flex flex-col transition-colors duration-200 ${a}`,children:[!r&&o.jsxs("header",{className:"border-b border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 flex items-center justify-between transition-colors duration-200",children:[o.jsx(rl,{}),o.jsx("div",{className:"flex-1 flex justify-center",children:t})]}),o.jsx("main",{className:"flex-1 px-6 py-6",children:e}),!s&&n&&o.jsx("footer",{className:"border-t border-oai-gray-200 dark:border-oai-gray-800 px-6 py-4 mt-auto transition-colors duration-200",children:n})]})}function sl({children:e,variant:t="info",size:n="md",className:a=""}){const r="inline-flex items-center font-medium",s={success:"bg-oai-brand-100 dark:bg-oai-brand-900/30 text-oai-brand-700 dark:text-oai-brand-400 rounded-full",warning:"bg-oai-amber-50 dark:bg-oai-amber-900/30 text-oai-amber-dark dark:text-oai-amber-400 rounded-full",error:"bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded-full",info:"bg-oai-gray-100 dark:bg-oai-gray-800 text-oai-gray-600 dark:text-oai-gray-300 rounded-full",secondary:"bg-oai-gray-100 dark:bg-oai-gray-800 text-oai-gray-500 dark:text-oai-gray-300 rounded-md"},l={sm:"px-2 py-0.5 text-xs",md:"px-2.5 py-1 text-sm"},i=`${r} ${s[t]} ${l[n]} ${a}`.trim();return o.jsx("span",{className:i,children:e})}const il=h.forwardRef(function(t,n){const{render:a,className:r,disabled:s=!1,nativeButton:l=!0,...i}=t,{store:c}=Ai(),u=c.useState("open");function f(p){u&&c.setOpen(!1,mi(hi,p.nativeEvent))}const{getButtonProps:d,buttonRef:m}=ui({disabled:s,native:l}),g=h.useMemo(()=>({disabled:s}),[s]);return fi("button",t,{state:g,ref:[n,m],props:[{onClick:f},i,d]})});var ll={};function cl(e,t){return e==="."?{width:"0.34ch",justifyContent:"center",marginInline:"-0.04ch"}:e===","?{width:"0.08ch",justifyContent:"center",marginInline:"-0.30ch"}:{width:"0.72ch",justifyContent:"flex-start",paddingLeft:"0.04ch",height:t}}function dl({mv:e,digit:t,height:n}){const a=so(e,r=>{const s=(r%10+10)%10,l=(10+t-s)%10;let i=l*n;return l>5&&(i-=10*n),i});return o.jsx(gt.span,{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",y:a},children:t})}function ul(e){const t=Math.round(e),n=1e-9*Math.max(1,Math.abs(e));return Math.abs(e-t)<n?t:e}function fl(e,t){const n=e/t;return Math.floor(ul(n))}function ml(e){const t=String(e??""),n=Array.from(t),a=n.indexOf(".");let r=n.filter((i,c)=>/\d/.test(i)&&(a===-1||c<a)).length,s=0,l=!1;return n.map(i=>{if(!/\d/.test(i))return i==="."&&(l=!0),i;if(!l){const c=10**Math.max(r-1,0);return r-=1,c}return s+=1,10**-s})}function hl({place:e,value:t,height:n,digitStyle:a,shouldReduceMotion:r,isLed:s}){if(typeof e!="number"){const u=cl(e,n);return o.jsx("span",{"data-counter-token":"static",className:`relative inline-flex items-center justify-center${s?" tt-lcd-sep":""}`,style:{height:n,...u,...a},children:e})}const l=fl(t,e),i=ha(0),c=al(i,{stiffness:220,damping:26,mass:.8});return h.useEffect(()=>{i.set(l)},[i,l]),r?o.jsx("span",{"data-counter-token":"digit",className:`relative inline-flex items-center justify-center overflow-hidden${s?" tt-lcd-cell":""}`,style:{height:n,position:"relative",width:"0.9ch",fontVariantNumeric:"tabular-nums",...a},children:Math.abs(l)%10}):o.jsx("span",{"data-counter-token":"digit",className:`relative inline-flex overflow-hidden${s?" tt-lcd-cell":""}`,style:{height:n,position:"relative",width:"0.9ch",fontVariantNumeric:"tabular-nums",...a},children:Array.from({length:10},(u,f)=>o.jsx(dl,{mv:c,digit:f,height:n},f))})}function gl({value:e,displayValue:t,fontSize:n=72,padding:a=0,places:r,gap:s=6,borderRadius:l=4,horizontalPadding:i=0,textColor:c="inherit",fontWeight:u="inherit",containerStyle:f,counterStyle:d,digitStyle:m,gradientHeight:g=14,gradientFrom:p="rgba(255,255,255,0.95)",gradientTo:b="rgba(255,255,255,0)",topGradientStyle:v,bottomGradientStyle:k,variant:j="default"}){const x=j==="led",N=String(t??e??""),C=h.useMemo(()=>Array.isArray(r)&&r.length?r:ml(N),[r,N]),T=typeof navigator<"u"&&/jsdom/i.test(navigator.userAgent||"")||typeof process<"u"&&ll?.VITEST==="true",z=zt()||T,$=Number.isFinite(Number(e))?Math.abs(Number(e)):0,D=n+a;return z?o.jsx("span",{"data-counter-root":"true",className:x?"tt-lcd":void 0,style:{display:"inline-flex",alignItems:"center",color:c,fontSize:n,fontWeight:u,lineHeight:1,...f,...d},children:x?o.jsx("span",{className:"tt-lcd-cell tt-lcd-cell--static",children:N}):N}):o.jsxs("span",{"data-counter-root":"true",style:{position:"relative",display:"inline-block",...f},children:[o.jsx("span",{className:x?"tt-lcd":void 0,style:{fontSize:n,...x?null:{display:"flex",gap:s,borderRadius:l,paddingLeft:i,paddingRight:i,color:c},overflow:"hidden",lineHeight:1,fontWeight:u,...d},children:C.map((A,K)=>o.jsx(hl,{place:A,value:$,height:D,digitStyle:m,shouldReduceMotion:z,isLed:x},`${String(A)}-${K}`))}),o.jsxs("span",{style:{pointerEvents:"none",position:"absolute",inset:0,display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsx("span",{style:v??{height:g,background:`linear-gradient(to bottom, ${p}, ${b})`}}),o.jsx("span",{style:k??{height:g,background:`linear-gradient(to top, ${p}, ${b})`}})]})]})}var yl={};const pl=new Set([",","."," "]),bl=typeof navigator<"u"&&/jsdom/i.test(navigator.userAgent||"")||typeof process<"u"&&yl?.VITEST==="true";function xl({char:e,reduceMotion:t,index:n}){const[a,r]=h.useState(t?e:""),[s,l]=h.useState(!1),i=h.useRef(e),c=h.useRef(!1);return h.useEffect(()=>{if(!c.current){if(c.current=!0,i.current=e,t){r(e);return}const d=Math.min(n*45,520),m=setTimeout(()=>l(!0),d),g=setTimeout(()=>r(e),d+130),p=setTimeout(()=>l(!1),d+300);return()=>{clearTimeout(m),clearTimeout(g),clearTimeout(p)}}if(e===i.current)return;if(i.current=e,t){r(e);return}l(!0);const u=setTimeout(()=>r(e),130),f=setTimeout(()=>l(!1),300);return()=>{clearTimeout(u),clearTimeout(f)}},[e,t,n]),o.jsx("span",{className:`tt-flap${s?" tt-flap--flip":""}`,"aria-hidden":"true",children:o.jsx("span",{className:"tt-flap__glyph",children:a})})}function kl({value:e,fontSize:t=56,className:n=""}){const a=zt()||bl,r=String(e??""),s=Array.from(r);return o.jsx("span",{className:`tt-flaprow ${n}`,style:{fontSize:`clamp(30px, 9cqi, ${t}px)`},role:"text","aria-label":r,children:s.map((l,i)=>pl.has(l)?o.jsx("span",{className:"tt-flap-sep","aria-hidden":"true",children:l},i):o.jsx(xl,{char:l,reduceMotion:a,index:i},i))})}function wl({baseUrl:e,accessToken:t,guestAllowed:n=!1,weeks:a=52,weekStartsOn:r="sun",cacheKey:s,timeZone:l,tzOffsetMinutes:i,now:c}={}){const u=h.useMemo(()=>wi({weeks:a,weekStartsOn:r,now:c}),[c,a,r]),[f,d]=h.useState([]),[m,g]=h.useState(null),[p,b]=h.useState("edge"),[v,k]=h.useState(!1),[j,x]=h.useState(null),N=Yt(),C=!n,T=h.useMemo(()=>{if(!s)return null;const B=on({timeZone:l,offsetMinutes:i});return`tokentracker.heatmap.${s}.${a}.${r}.${B}`},[s,l,i,a,r]),z=h.useCallback(()=>{if(!T||typeof window>"u")return null;try{const B=window.localStorage.getItem(T);if(!B)return null;const E=JSON.parse(B);return!E||!E.heatmap?null:E}catch{return null}},[T]),$=h.useCallback(B=>{if(!(!T||typeof window>"u"))try{window.localStorage.setItem(T,JSON.stringify(B))}catch{}},[T]),D=h.useCallback(()=>{if(!(!T||typeof window>"u"))try{window.localStorage.removeItem(T)}catch{}},[T]),A=h.useCallback(async()=>{k(!0),x(null);try{try{const H=await ji({baseUrl:e,accessToken:t,weeks:a,to:u.to,weekStartsOn:r,timeZone:l,tzOffsetMinutes:i}),_=Array.isArray(H?.weeks)?H.weeks:[];if(!_.length&&C){const I=z();if(I?.heatmap){g(I.heatmap),d(I.daily||[]),b("cache");return}}if(!_.some(I=>(Array.isArray(I)?I:[]).some(M=>M&&Number.isFinite(Number(M.level))))&&_.length){const I=[];for(const J of _)for(const P of Array.isArray(J)?J:[])P?.day&&I.push({day:P.day,conversation_count:P.conversation_count??0,total_tokens:P.total_tokens??P.value??0,billable_total_tokens:P.billable_total_tokens??P.value??P.total_tokens??0});const M=Zn({dailyRows:I,weeks:a,to:H?.to||u.to,weekStartsOn:r});d(I),g({...M,week_starts_on:r,active_days:I.filter(J=>Number(J?.billable_total_tokens??J?.total_tokens)>0).length,streak_days:pn({dailyRows:I,to:H?.to||u.to})}),b("client"),C?$({heatmap:{...M,week_starts_on:r,active_days:I.filter(J=>Number(J?.billable_total_tokens??J?.total_tokens)>0).length,streak_days:pn({dailyRows:I,to:H?.to||u.to})},daily:I,fetchedAt:new Date().toISOString()}):D();return}g(H||null),d([]),b("edge"),H&&C?$({heatmap:H,daily:[],fetchedAt:new Date().toISOString()}):C||D();return}catch(H){const _=H,w=_?.status??_?.statusCode;if(w===401||w===403)throw H}const B=await Cn({baseUrl:e,accessToken:t,from:u.from,to:u.to,timeZone:l,tzOffsetMinutes:i}),E=Array.isArray(B?.data)?B.data:[];d(E);const W=Zn({dailyRows:E,weeks:a,to:u.to,weekStartsOn:r});g({...W,week_starts_on:r,active_days:E.filter(H=>Number(H?.billable_total_tokens??H?.total_tokens)>0).length,streak_days:pn({dailyRows:E,to:u.to})}),b("client"),C?$({heatmap:{...W,week_starts_on:r,active_days:E.filter(H=>Number(H?.billable_total_tokens??H?.total_tokens)>0).length,streak_days:pn({dailyRows:E,to:u.to})},daily:E,fetchedAt:new Date().toISOString()}):D()}catch(B){if(C){const E=z();if(E?.heatmap)g(E.heatmap),d(E.daily||[]),b("cache"),x(null);else{const W=B;x(W?.message||String(W)),d([]),g(null),b("edge")}}else{const E=B;x(E?.message||String(E)),d([]),g(null),b("edge")}}finally{k(!1)}},[t,e,N,n,C,u.from,u.to,z,l,i,r,a,D,$]);return h.useEffect(()=>{if(!C)D(),d([]),x(null),g(null),b("edge");else{const B=z();B?.heatmap&&(g(B.heatmap),d(B.daily||[]),b("cache"))}A()},[t,N,z,A,n,C,D]),{range:u,daily:f,heatmap:m,source:N?"mock":p==="client"?"edge":p,loading:v,error:j,refresh:A}}function vl({baseUrl:e,accessToken:t,limit:n=3,from:a,to:r,source:s,timeZone:l,tzOffsetMinutes:i}={}){const[c,u]=h.useState([]),[f,d]=h.useState([]),[m,g]=h.useState(!1),[p,b]=h.useState(null),v=h.useCallback(async()=>{g(!0),b(null);try{const k=await Si({baseUrl:e,accessToken:t,limit:n,from:a,to:r,source:s,timeZone:l,tzOffsetMinutes:i});u(Array.isArray(k?.entries)?k.entries:[]),d(Array.isArray(k?.unattributed_sources)?k.unattributed_sources:[])}catch(k){const j=k?.message||String(k);b(j),u([]),d([])}finally{g(!1)}},[t,e,a,n,s,l,r,i]);return h.useEffect(()=>{v()},[v]),{entries:c,unattributedSources:f,loading:m,error:p,refresh:v}}const Nl=24;function io({baseUrl:e,accessToken:t,guestAllowed:n=!1,period:a,from:r,to:s,months:l=Nl,cacheKey:i,timeZone:c,tzOffsetMinutes:u,now:f,sharedRows:d,sharedRange:m}={}){const[g,p]=h.useState([]),[b,v]=h.useState(()=>({from:r,to:s})),[k,j]=h.useState("edge"),[x,N]=h.useState(null),[C,T]=h.useState(!1),[z,$]=h.useState(null),D=Yt(),A=!n&&!D,K=Array.isArray(d),B=m?.from||r,E=m?.to||s,W=h.useMemo(()=>a==="day"||a==="24h"?"hourly":a==="total"?"monthly":"daily",[a]),H=(()=>{if(!i)return null;const P=_l(e)||"default",L=on({timeZone:c,offsetMinutes:u});if(W==="hourly"){const q=a==="24h"?`${r||""}.${s||""}`:s||r||"day";return`tokentracker.trend.${i}.${P}.hourly.${q}.${L}`}if(W==="monthly")return`tokentracker.trend.${i}.${P}.monthly.${l}.${s||"today"}.${L}`;const V=`${r||""}.${s||""}`;return`tokentracker.trend.${i}.${P}.daily.${V}.${L}`})(),_=h.useCallback(()=>{if(!H||typeof window>"u")return null;try{const P=window.localStorage.getItem(H);if(!P)return null;const L=JSON.parse(P);return!L||!Array.isArray(L.rows)?null:L}catch{return null}},[H]),w=h.useCallback(P=>{if(!(!H||typeof window>"u"))try{window.localStorage.setItem(H,JSON.stringify(P))}catch{}},[H]),I=h.useCallback(()=>{if(!(!H||typeof window>"u"))try{window.localStorage.removeItem(H)}catch{}},[H]),M=h.useCallback(async()=>{if(K){p(Array.isArray(d)?d:[]),v({from:B,to:E}),j("shared"),N(null),T(!1),$(null);return}T(!0),$(null);try{let P;W==="hourly"?P=await Ml({baseUrl:e,accessToken:t,from:r,to:s,period:a,timeZone:c,tzOffsetMinutes:u,now:f}):W==="monthly"?P=await Ci({baseUrl:e,accessToken:t,months:l,to:s,timeZone:c,tzOffsetMinutes:u}):P=await Cn({baseUrl:e,accessToken:t,from:r,to:s,timeZone:c,tzOffsetMinutes:u});const L=P?.from||r||P?.day||null,V=P?.to||s||P?.day||null;let q=Array.isArray(P?.data)?P.data:[];W==="daily"?q=Ln(q,L||r,V||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?q=wn(q,L||r||P?.day,V||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):W==="monthly"&&(q=zn(q,{timeZone:c,offsetMinutes:u,now:f}));const fe=new Date().toISOString();p(q),v({from:L,to:V}),j("edge"),N(fe),A?w({rows:q,from:L,to:V,mode:W,fetchedAt:fe}):I()}catch(P){if(A){const L=_();if(L?.rows){let V=W==="daily"?Ln(L.rows||[],L.from||r,L.to||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?wn(L.rows||[],L.from||r||L.day||s,L.to||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):Array.isArray(L.rows)?L.rows:[];W==="monthly"&&(V=zn(V,{timeZone:c,offsetMinutes:u,now:f})),p(V),v({from:L.from||r,to:L.to||s}),j("cache"),N(L.fetchedAt||null),$(null)}else{p([]),v({from:r,to:s}),j("edge"),N(null);const V=P;$(V?.message||String(V))}}else{p([]),v({from:r,to:s}),j("edge"),N(null);const L=P;$(L?.message||String(L))}}finally{T(!1)}},[t,e,r,D,n,A,W,l,a,_,K,B,d,E,c,s,u,f,I,w]);h.useEffect(()=>{if(K){p(Array.isArray(d)?d:[]),v({from:B,to:E}),j("shared"),N(null),T(!1),$(null);return}if(!A)I(),p([]),v({from:r,to:s}),$(null),j("edge"),N(null);else{const P=_();if(P?.rows){let L=W==="daily"?Ln(P.rows||[],P.from||r,P.to||s,{timeZone:c,offsetMinutes:u,now:f}):W==="hourly"?wn(P.rows||[],P.from||r||P.day||s,P.to||s,{period:a,timeZone:c,offsetMinutes:u,now:f}):Array.isArray(P.rows)?P.rows:[];W==="monthly"&&(L=zn(L,{timeZone:c,offsetMinutes:u,now:f})),p(L),v({from:P.from||r,to:P.to||s}),j("cache"),N(P.fetchedAt||null)}}M()},[t,D,_,M,K,B,d,E,n,A,I,W,r,s,c,u,f,a]);const J=D?"mock":k;return{rows:g,from:b.from||r,to:b.to||s,source:J,fetchedAt:x,loading:C,error:z,refresh:M}}function _l(e){try{return new URL(e).host}catch{return null}}async function Ml({baseUrl:e,accessToken:t,from:n,to:a,period:r,timeZone:s,tzOffsetMinutes:l,now:i}){const c=r==="24h"?lo(n,a):[a||n].filter(Boolean),u=Array.from(new Set(c)),f=await Promise.all(u.map(p=>no({accessToken:t,day:p,timeZone:s,tzOffsetMinutes:l}))),d=f.flatMap(p=>Array.isArray(p?.data)?p.data:[]),m=r==="24h"?u[0]||n||a:f[0]?.day||n||a,g=r==="24h"?u[u.length-1]||a||n:f[0]?.day||a||n;return{day:g,from:m,to:g,data:wn(d,m,g,{period:r,timeZone:s,offsetMinutes:l,now:i})}}function Lt(e){if(!e)return null;const t=String(e).trim(),n=t.split("-");if(n.length!==3)return null;const a=Number(n[0]),r=Number(n[1])-1,s=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r,s));return Number.isFinite(l.getTime())&&ht(l)===t?l:null}function ga(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function lo(e,t){const n=Lt(e||t),a=Lt(t||e);if(!n||!a)return[e||t].filter(Boolean).map(String);if(a<n)return[ht(a),ht(n)];const r=[];for(let s=n;s<=a;s=ga(s,1))r.push(ht(s));return r}const co=["total_tokens","billable_total_tokens","input_tokens","cached_input_tokens","cache_creation_input_tokens","output_tokens","reasoning_output_tokens","conversation_count"];function Ln(e,t,n,{timeZone:a,offsetMinutes:r,now:s}={}){const l=Lt(t),i=Lt(n);if(!l||!i||i<l)return Array.isArray(e)?e:[];const c=s instanceof Date&&Number.isFinite(s.getTime())?s:new Date,u=tn({timeZone:a,offsetMinutes:r,date:c}),f=Lt(u),d=f?f.getTime():c.getTime(),m=new Map;for(const p of e||[])p?.day&&m.set(p.day,p);const g=[];for(let p=l;p<=i;p=ga(p,1)){const b=ht(p),v=m.get(b),k=p.getTime()>d;if(v){g.push({...v,missing:!1,future:k});continue}g.push({day:b,total_tokens:null,billable_total_tokens:null,input_tokens:null,cached_input_tokens:null,output_tokens:null,reasoning_output_tokens:null,missing:!k,future:k})}return g}function jl(e,t){const n=t?null:0;return{hour:e,total_tokens:n,billable_total_tokens:n,input_tokens:n,cached_input_tokens:n,cache_creation_input_tokens:n,output_tokens:n,reasoning_output_tokens:n,conversation_count:n,missing:!1,future:t}}function Sl(e){if(!e||typeof e!="object")return!1;const t=e.models;return t&&typeof t=="object"&&Object.keys(t).length>0?!1:co.every(n=>e[n]==null)}function Cl(e,t,n){const a={...e,hour:t,missing:!1,future:n};if(!n&&Sl(e))for(const r of co)a[r]=0;return a}function Dl(e,t){const n=t===30?48:24,a=[];for(let r=0;r<n;r++){const s=Math.floor(r*t/60),l=r*t%60;a.push(`${e}T${String(s).padStart(2,"0")}:${String(l).padStart(2,"0")}:00`)}return a}function Tl(e,t,{timeZone:n,offsetMinutes:a}={}){const r=Dl(e,t);if(!n||typeof Intl>"u"||!Intl.DateTimeFormat)return r;const s=Lt(e);if(!s)return r;const l=s.getUTCFullYear()*1e4+(s.getUTCMonth()+1)*100+s.getUTCDate(),i=s.getTime()-2160*60*1e3,c=ga(s,2).getTime()+2160*60*1e3,u=[],f=new Set;for(let d=i;d<=c;d+=1800*1e3){const m=ln({timeZone:n,offsetMinutes:a,now:new Date(d)});if(!m||m.dayNum!==l||t===60&&m.minute!==0||t===30&&m.minute!==0&&m.minute!==30)continue;const g=`${e}T${String(m.hour).padStart(2,"0")}:${String(m.minute).padStart(2,"0")}:00`;f.has(g)||(f.add(g),u.push(g))}return u.length>0?u:r}function Pl(e,t,{timeZone:n,offsetMinutes:a,now:r}={}){if(!t)return Array.isArray(e)?e:[];const s=t.trim().slice(0,10),l=ln({timeZone:n,offsetMinutes:a,now:r}),i=l?l.dayNum:void 0;let c=!1;for(const g of e||[]){const p=g?.hour||g?.label||"",b=vn(p,i);if(b&&b.slot%2!==0){c=!0;break}}const u=c?30:60,f=new Map;for(const g of e||[]){const p=g?.hour||g?.label||"",b=vn(p,i);b&&f.set(b.slot,g)}const d=[],m=Tl(s,u,{timeZone:n,offsetMinutes:a});for(let g=0;g<m.length;g++){const p=m[g],b=vn(p,i),v=b?b.slot:c?g:g*2,k=f.get(v);let j=!1;if(l){const x=l.year*1e4+l.month*100+l.day,N=b?.dayNum??Number(s.replace(/-/g,""));if(N>x)j=!0;else if(N===x){const C=l.hour*2+(l.minute>=30?1:0);j=v>C}}k?d.push(Cl(k,p,j)):d.push(jl(p,j))}return d}function wn(e,t,n,{period:a,timeZone:r,offsetMinutes:s,now:l}={}){const i=a==="24h"?lo(t,n):[n||t].filter(Boolean).map(String),u=Array.from(new Set(i)).flatMap(d=>Pl(Ol(e||[],d),d,{timeZone:r,offsetMinutes:s,now:l})),f=$l(u,{timeZone:r,offsetMinutes:s,now:l});return a!=="24h"?f:El(f,{timeZone:r,offsetMinutes:s,now:l})}function Ol(e,t){return e.filter(n=>{const a=n?.hour||n?.label||"",r=String(a).trim();return r.includes("T")?r.slice(0,10)===t:!0})}function $l(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});return r?e.map(s=>{const l=s?.hour||s?.label||"",i=vn(l,r.dayNum);if(!i)return{...s,future:!1};const c=i.dayNum!==null&&i.dayNum>r.dayNum||(i.dayNum===null||i.dayNum===r.dayNum)&&i.slot>r.slot;return{...s,future:!!c}}):e}function El(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});if(!r)return e.filter(i=>!i?.future);const s=uo({year:r.year,month:r.month,day:r.day,hour:r.hour,minute:r.minute}),l=s-1440*60*1e3;return e.filter(i=>{if(i?.future)return!1;const c=Wl(i?.hour||i?.label);return c!=null&&c>=l&&c<=s})}function zn(e,{timeZone:t,offsetMinutes:n,now:a}={}){if(!Array.isArray(e))return[];const r=ln({timeZone:t,offsetMinutes:n,now:a});return r?e.map(s=>{const l=s?.month||s?.label||"",i=Al(l);if(!i)return{...s,future:!1};const c=i.year>r.year||i.year===r.year&&i.month>r.month;return{...s,future:c}}):e}function ln({timeZone:e,offsetMinutes:t,now:n}={}){const a=n instanceof Date&&Number.isFinite(n.getTime())?n:new Date;if(e&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const m=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(a).reduce((j,x)=>(x.type&&x.value&&(j[x.type]=x.value),j),{}),g=Number(m.year),p=Number(m.month),b=Number(m.day),v=Number(m.hour),k=Number(m.minute);if(Number.isFinite(g)&&Number.isFinite(p)&&Number.isFinite(b)&&Number.isFinite(v)&&Number.isFinite(k)){const j=v*2+(k>=30?1:0);return{year:g,month:p,day:b,hour:v,minute:k,dayNum:g*1e4+p*100+b,slot:j}}}catch{}if(Number.isFinite(t)){const f=new Date(a.getTime()+t*60*1e3),d=f.getUTCFullYear(),m=f.getUTCMonth()+1,g=f.getUTCDate(),p=f.getUTCHours(),b=f.getUTCMinutes(),v=p*2+(b>=30?1:0);return{year:d,month:m,day:g,hour:p,minute:b,dayNum:d*1e4+m*100+g,slot:v}}const r=a.getFullYear(),s=a.getMonth()+1,l=a.getDate(),i=a.getHours(),c=a.getMinutes(),u=i*2+(c>=30?1:0);return{year:r,month:s,day:l,hour:i,minute:c,dayNum:r*1e4+s*100+l,slot:u}}function vn(e,t){if(!e)return null;const n=String(e).trim();if(n.includes("T")){const[a,r]=n.split("T");if(!a||!r)return null;const s=a.split("-");if(s.length!==3)return null;const l=Number(s[0]),i=Number(s[1]),c=Number(s[2]);if(!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c))return null;const u=r.split(":"),f=Number(u[0]),d=Number(u[1]);if(!Number.isFinite(f)||f<0||f>23||!Number.isFinite(d)||d<0||d>59)return null;const m=f*2+(d>=30?1:0);return{dayNum:l*1e4+i*100+c,slot:m}}else{let a=NaN,r=0;if(/^\d{1,2}$/.test(n))a=Number(n);else if(/^\d{1,2}:\d{2}(:\d{2})?$/.test(n)){const l=n.split(":");a=Number(l[0]),r=Number(l[1])}if(!Number.isFinite(a)||a<0||a>23||!Number.isFinite(r)||r<0||r>59)return null;const s=a*2+(r>=30?1:0);return{dayNum:t||null,slot:s}}}function uo({year:e,month:t,day:n,hour:a=0,minute:r=0}){return Date.UTC(Number(e),Number(t)-1,Number(n),Number(a),Number(r),0,0)}function Wl(e){if(!e)return null;const t=String(e).trim();if(!t.includes("T"))return null;const[n,a]=t.split("T");if(!n||!a)return null;const r=n.split("-"),s=a.split(":");if(r.length!==3||s.length<2)return null;const[l,i,c]=r.map(Number),[u,f]=s.map(Number);return!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c)||!Number.isFinite(u)||!Number.isFinite(f)?null:uo({year:l,month:i,day:c,hour:u,minute:f})}function Al(e){if(!e)return null;const n=String(e).trim().split("-");if(n.length!==2)return null;const a=Number(n[0]),r=Number(n[1]);return!Number.isFinite(a)||!Number.isFinite(r)||r<1||r>12?null:{year:a,month:r}}function Xa({baseUrl:e,accessToken:t,guestAllowed:n=!1,from:a,to:r,includeDaily:s=!0,cacheKey:l,timeZone:i,tzOffsetMinutes:c,now:u}={}){const[f,d]=h.useState([]),[m,g]=h.useState(null),[p,b]=h.useState(null),[v,k]=h.useState("edge"),[j,x]=h.useState(null),[N,C]=h.useState(!1),[T,z]=h.useState(null),$=Yt(),D=!n&&!$,A=(()=>{if(!l)return null;const _=Fl(e)||"default",w=s?"daily":"summary",I=on({timeZone:i,offsetMinutes:c});return`tokentracker.usage.${l}.${_}.${a}.${r}.${w}.${I}`})(),K=h.useCallback(()=>{if(!A||typeof window>"u")return null;try{const _=window.localStorage.getItem(A);if(!_)return null;const w=JSON.parse(_);return!w||!w.summary?null:w}catch{return null}},[A]),B=h.useCallback(_=>{if(!(!A||typeof window>"u"))try{window.localStorage.setItem(A,JSON.stringify(_))}catch{}},[A]),E=h.useCallback(()=>{if(!(!A||typeof window>"u"))try{window.localStorage.removeItem(A)}catch{}},[A]),W=h.useCallback(async()=>{C(!0),z(null);try{let _=null,w=null;if(s){const[L,V]=await Promise.allSettled([Cn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c}),Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0})]);if(L.status==="rejected")throw L.reason;_=L.value,w=V.status==="fulfilled"?V.value:null}else w=await Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0});let I=s&&Array.isArray(_?.data)?_.data:[];s&&(I=Bn(I,a,r,{timeZone:i,offsetMinutes:c,now:u}));let M=w?.totals||_?.summary?.totals||null,J=w?.rolling||_?.summary?.rolling||null;if(s&&!M&&!w)try{const L=await Rn({baseUrl:e,accessToken:t,from:a,to:r,timeZone:i,tzOffsetMinutes:c,rolling:!0});M=L?.totals||null,J=L?.rolling||J}catch{}const P=new Date().toISOString();d(I),g(M),b(J),k("edge"),x(P),M&&D?B({summary:M,rolling:J,daily:I,from:a,to:r,includeDaily:s,fetchedAt:P}):D||E()}catch(_){if(D){const w=K();if(w?.summary){g(w.summary),b(w.rolling||null);const I=Array.isArray(w.daily)?w.daily:[],M=s?Bn(I,w.from||a,w.to||r,{timeZone:i,offsetMinutes:c,now:u}):I;d(M),k("cache"),x(w.fetchedAt||null),z(null)}else{const I=_;z(I?.message||String(I)),d([]),g(null),b(null),k("edge"),x(null)}}else{const w=_;z(w?.message||String(w)),d([]),g(null),b(null),k("edge"),x(null)}}finally{C(!1)}},[t,e,a,s,$,n,D,u,K,i,r,c,E,B]);return h.useEffect(()=>{if(!D)E(),d([]),g(null),b(null),z(null),k("edge"),x(null);else{const _=K();if(_?.summary){g(_.summary),b(_.rolling||null);const w=Array.isArray(_.daily)?_.daily:[],I=s?Bn(w,_.from||a,_.to||r,{timeZone:i,offsetMinutes:c,now:u}):w;d(I),k("cache"),x(_.fetchedAt||null)}}W()},[t,$,K,W,n,D,E]),{daily:f,summary:m,rolling:p,source:$?"mock":v,fetchedAt:j,loading:N,error:T,refresh:W}}function Fl(e){try{return new URL(e).host}catch{return null}}function Yn(e){if(!e)return null;const t=String(e).trim(),n=t.split("-");if(n.length!==3)return null;const a=Number(n[0]),r=Number(n[1])-1,s=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r,s));return Number.isFinite(l.getTime())&&ht(l)===t?l:null}function Rl(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function Bn(e,t,n,{timeZone:a,offsetMinutes:r,now:s}={}){const l=Yn(t),i=Yn(n);if(!l||!i||i<l)return Array.isArray(e)?e:[];const c=s instanceof Date&&Number.isFinite(s.getTime())?s:new Date,u=tn({timeZone:a,offsetMinutes:r,date:c}),f=Yn(u),d=f?f.getTime():c.getTime(),m=new Map;for(const p of e||[])p?.day&&m.set(p.day,p);const g=[];for(let p=l;p<=i;p=Rl(p,1)){const b=ht(p),v=m.get(b),k=p.getTime()>d;if(v){g.push({...v,missing:!1,future:k});continue}g.push({day:b,total_tokens:null,billable_total_tokens:null,input_tokens:null,cached_input_tokens:null,output_tokens:null,reasoning_output_tokens:null,missing:!k,future:k})}return g}function Il({baseUrl:e,accessToken:t,guestAllowed:n=!1,from:a,to:r,cacheKey:s,timeZone:l,tzOffsetMinutes:i}={}){const[c,u]=h.useState(null),[f,d]=h.useState("edge"),[m,g]=h.useState(!1),[p,b]=h.useState(null),v=Yt(),k=!n,j=h.useMemo(()=>{if(!s)return null;const $=Ll(e)||"default",D=on({timeZone:l,offsetMinutes:i});return`tokentracker.modelBreakdown.${s}.${$}.${a}.${r}.${D}`},[e,s,a,l,r,i]),x=h.useCallback(()=>{if(!j||typeof window>"u")return null;try{const $=window.localStorage.getItem(j);if(!$)return null;const D=JSON.parse($);return!D||!D.breakdown?null:D}catch{return null}},[j]),N=h.useCallback($=>{if(!(!j||typeof window>"u"))try{window.localStorage.setItem(j,JSON.stringify($))}catch{}},[j]),C=h.useCallback(()=>{if(!(!j||typeof window>"u"))try{window.localStorage.removeItem(j)}catch{}},[j]),T=h.useCallback(async()=>{g(!0),b(null);try{const $=await Di({baseUrl:e,accessToken:t,from:a,to:r,timeZone:l,tzOffsetMinutes:i});u($||null),d("edge"),$&&k?N({breakdown:$,fetchedAt:new Date().toISOString()}):k||C()}catch($){if(k){const D=x();if(D?.breakdown)u(D.breakdown),d("cache"),b(null);else{u(null),d("edge");const A=$;b(A?.message||String(A))}}else{u(null),d("edge");const D=$;b(D?.message||String(D))}}finally{g(!1)}},[t,e,a,v,n,k,x,l,r,i,C,N]);return h.useEffect(()=>{if(!k)C(),u(null),d("edge"),b(null);else{const $=x();$?.breakdown&&(u($.breakdown),d("cache"))}T()},[t,v,x,T,n,k,C]),{breakdown:c,source:v?"mock":f,loading:m,error:p,refresh:T}}function Ll(e){try{return new URL(e).host}catch{return null}}const oa="tokentracker.plan_prices.v1";function zl(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(oa);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n={};for(const[a,r]of Object.entries(t)){const s=Number(r);Number.isFinite(s)&&s>0&&(n[String(a).toLowerCase()]=s)}return n}catch{return{}}}function Yl(){const[e,t]=h.useState({});h.useEffect(()=>{t(zl())},[]);const n=h.useCallback((a,r)=>{t(s=>{const l=String(a||"").toLowerCase();if(!l)return s;const i={...s},c=Number(r);Number.isFinite(c)&&c>0?i[l]=c:delete i[l];try{window.localStorage.setItem(oa,JSON.stringify(i))}catch{}return i})},[]);return{planPrices:e,setPlanPrice:n,PLAN_PRICES_STORAGE_KEY:oa}}function Re(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}function Bl(e){const t=String(e?.hour??""),n=t.indexOf("T");if(n<0)return null;const a=Number(t.slice(n+1,n+3));return Number.isFinite(a)?a:null}function It(e,t){let n=0,a=0;if(Array.isArray(e))for(const r of e){const s=Bl(r);s==null||s>t||(n+=Re(r.total_tokens),a+=Re(r.total_cost_usd))}return{tokens:n,cost:a}}function _n(...e){return e.reduce((t,n)=>({tokens:t.tokens+Re(n?.tokens),cost:t.cost+Re(n?.cost)}),{tokens:0,cost:0})}function Ga(e){if(!Array.isArray(e)||e.length===0)return null;const t=_n(...e);return{tokens:t.tokens/e.length,cost:t.cost/e.length}}function Hn(e){if(!e)return null;const t=Re(e.tokens);return t<=0?null:Re(e.cost)/(t/1e6)}function Ka(e,t){return e==null||t==null||!Number.isFinite(e)||!Number.isFinite(t)||t===0?null:(e-t)/t}function Hl({current:e,prev:t=null,trailingAvg:n=null,trailingFull:a=null,period:r}){if(r==="total"||!e)return null;const s=(i,c)=>c==null||!(c>0)?null:i/c,l=(i,c,u,f)=>({value:i,deltaVsPrev:Ka(i,c),deltaVsAvg:n?Ka(i,u):null,progress:f});return{period:r,tokens:l(Re(e.tokens),t?Re(t.tokens):null,n?Re(n.tokens):null,a?s(Re(e.tokens),Re(a.tokens)):null),cost:l(Re(e.cost),t?Re(t.cost):null,n?Re(n.cost):null,a?s(Re(e.cost),Re(a.cost)):null),perMTok:l(Hn(e),Hn(t),Hn(n),null)}}const fo=864e5;function sa(e){const t=String(e).split("-").map(Number);return t.length!==3||t.some(n=>!Number.isFinite(n))?null:Date.UTC(t[0],t[1]-1,t[2])}function Mn(e){const t=new Date(e),n=t.getUTCFullYear(),a=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0");return`${n}-${a}-${r}`}function wt(e,t){const n=sa(e);return n==null?null:Mn(n+t*fo)}function Ul(e,{timeZone:t,offsetMinutes:n}){const a=e instanceof Date?e:new Date(e);if(t&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const r=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",hour12:!1});let s=Number(r.format(a).slice(0,2));if(s===24&&(s=0),Number.isFinite(s))return Math.min(23,Math.max(0,s))}catch{}return typeof n=="number"&&Number.isFinite(n)?new Date(a.getTime()+n*6e4).getUTCHours():a.getHours()}function Vl(e,{timeZone:t,offsetMinutes:n}){const a=e instanceof Date?e:new Date(e);if(t&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(a);if(/^\d{4}-\d{2}-\d{2}$/.test(s))return s}catch{}return typeof n=="number"&&Number.isFinite(n)?Mn(a.getTime()+n*6e4):Mn(a.getTime())}const ql=e=>Number(e?.total_tokens??0)||0,Xl=e=>Number(e?.total_cost_usd??0)||0;function Qa(e,t,n){let a={tokens:0,cost:0};const r=t?sa(t):null,s=n?sa(n):null;if(r==null||s==null||r>s)return a;for(let l=r;l<=s;l+=fo){const i=e.get(Mn(l));i&&(a=_n(a,i))}return a}function Gl(e,t){if(!t||e==="total")return null;if(e==="day"||e==="24h"){const s=[];for(let l=1;l<=7;l++){const i=wt(t,-l);i&&s.push(i)}return{kind:"day",hourlyDays:[t,...s],dailyFrom:null,dailyTo:null,todayKey:t,prevKey:wt(t,-1),trailingKeys:s}}const n=e==="week"?6:e==="month"?29:null;if(n==null)return null;const a=n+1,r=wt(t,-a);return{kind:"window",hourlyDays:[t,r].filter(Boolean),dailyFrom:wt(t,-(a*2-1)),dailyTo:t,todayKey:t,curStartKey:wt(t,-n),prevBoundaryKey:r,prevStartKey:wt(t,-(a*2-1))}}function Kl(e,t){const n=new Map;return e.forEach((a,r)=>{n.set(a,Array.isArray(t[r]?.data)?t[r].data:[])}),n}function Ql(e){const t=new Map;for(const n of Array.isArray(e?.data)?e.data:[])n?.day&&t.set(String(n.day),{tokens:ql(n),cost:Xl(n)});return t}function Jl(e,t,n){return{current:It(t.get(e.todayKey),n),prev:e.prevKey?It(t.get(e.prevKey),n):null,trailingAvg:Ga(e.trailingKeys.map(a=>It(t.get(a),n))),trailingFull:Ga(e.trailingKeys.map(a=>It(t.get(a),23)))}}function Zl(e,t,n,a){const r=_n(Qa(n,e.curStartKey,wt(e.todayKey,-1)),It(t.get(e.todayKey),a)),s=_n(Qa(n,e.prevStartKey,e.prevBoundaryKey?wt(e.prevBoundaryKey,-1):null),e.prevBoundaryKey?It(t.get(e.prevBoundaryKey),a):{tokens:0,cost:0});return{current:r,prev:s,trailingAvg:null}}function ec(e){try{return new URL(e).host}catch{return null}}function tc({baseUrl:e,accessToken:t,guestAllowed:n=!1,period:a,timeZone:r,tzOffsetMinutes:s,now:l,cacheKey:i}={}){const[c,u]=h.useState(null),[f,d]=h.useState(!1),[m,g]=h.useState(null),p=h.useRef(0),b=l instanceof Date?l:new Date(l||Date.now()),v=Vl(b,{timeZone:r,offsetMinutes:s}),k=Ul(b,{timeZone:r,offsetMinutes:s}),j=Yt(),x=!n&&!j,N=(()=>{if(!i)return null;const D=ec(e)||"default",A=on({timeZone:r,offsetMinutes:s});return`tokentracker.pulse.${i}.${D}.${a}.${v}.${A}`})(),C=h.useCallback(()=>{if(!N||typeof window>"u")return null;try{const D=window.localStorage.getItem(N);return D?JSON.parse(D):null}catch{return null}},[N]),T=h.useCallback(D=>{if(!(!N||typeof window>"u"))try{window.localStorage.setItem(N,JSON.stringify(D))}catch{}},[N]),z=h.useCallback(()=>{const D=C();return D&&D.cutoffHour===k?D:null},[C,k]),$=h.useCallback(async()=>{const D=Gl(a,v);if(!D){u(null),g(null);return}const A=++p.current;d(!0),g(null);try{const K=await Promise.all(D.hourlyDays.map(H=>no({baseUrl:e,accessToken:t,day:H,timeZone:r,tzOffsetMinutes:s}))),B=Kl(D.hourlyDays,K);let E;if(D.kind==="day")E=Jl(D,B,k);else{const H=await Cn({baseUrl:e,accessToken:t,from:D.dailyFrom,to:D.dailyTo,timeZone:r,tzOffsetMinutes:s});E=Zl(D,B,Ql(H),k)}const W=Hl({...E,period:a});if(A!==p.current)return;u(W),x&&W&&T({pulse:W,todayKey:v,cutoffHour:k,fetchedAt:new Date().toISOString()})}catch(K){if(A!==p.current)return;const B=z();B?.pulse&&u(B.pulse),g(K?.message?String(K.message):"Failed to load pulse")}finally{A===p.current&&d(!1)}},[e,t,n,a,r,s,v,k,x,j,z,T]);return h.useEffect(()=>{if(a==="total"||a==="custom"){u(null);return}const D=z();D?.pulse&&u(D.pulse)},[N,a,k]),h.useEffect(()=>{$()},[$]),{pulse:c,loading:f,error:m,refresh:$}}const mo=new Set(["day","hour","month"]);function nc(e){return mo.has(e)}function Ja(e){if(e==null)return null;const t=String(e).trim();if(!/^[0-9]+$/.test(t))return null;const n=t.replace(/^0+/,"");return n.length===0?"0":n}function ac(e,t){const n=Ja(e),a=Ja(t);if(n&&a)return n.length!==a.length?n.length<a.length?-1:1:n===a?0:n<a?-1:1;const r=Le(e),s=Le(t);return r==null&&s==null?0:r==null?1:s==null?-1:r===s?0:r<s?-1:1}function ho(e,t){const n=typeof e=="string"?e:String(e||""),a=typeof t=="string"?t:String(t||"");return n===a?0:n<a?-1:1}function rc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]),s=Number(n[3]);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s))return null;const l=new Date(Date.UTC(a,r-1,s));return!Number.isFinite(l.getTime())||l.getUTCFullYear()!==a||l.getUTCMonth()+1!==r||l.getUTCDate()!==s?null:l.getTime()}function oc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]);if(!Number.isFinite(a)||!Number.isFinite(r)||r<1||r>12)return null;const s=new Date(Date.UTC(a,r-1,1));return Number.isFinite(s.getTime())?s.getTime():null}function sc(e){if(!e)return null;const n=String(e).trim().match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?Z?$/);if(!n)return null;const a=Number(n[1]),r=Number(n[2]),s=Number(n[3]),l=Number(n[4]),i=Number(n[5]),c=Number(n[6]||0);if(!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(l)||!Number.isFinite(i)||!Number.isFinite(c)||r<1||r>12||s<1||s>31||l<0||l>23||i<0||i>59||c<0||c>59)return null;const u=new Date(Date.UTC(a,r-1,s,l,i,c));return Number.isFinite(u.getTime())?u.getTime():null}function ic(e,t,n){const a=n==="hour"?sc:n==="month"?oc:rc,r=a(e),s=a(t);return r!=null&&s!=null?r===s?0:r<s?-1:1:ho(e,t)}function go(e,{key:t,dir:n}){const a=n==="asc"?1:-1,r=Array.isArray(e)?e:[],s=mo.has(t)?(i,c)=>ic(i,c,t):t==="top_model"?ho:ac,l=i=>t==="total_tokens"&&i?.billable_total_tokens!=null?i.billable_total_tokens:i?.[t];return r.map((i,c)=>({row:i,index:c})).sort((i,c)=>{const u=l(i.row),f=l(c.row),d=u==null,m=f==null;if(d&&m)return i.index-c.index;if(d)return 1;if(m)return-1;const g=s(u,f);return g!==0?g*a:i.index-c.index}).map(i=>i.row)}function lc(){return[{key:"day",label:y("daily.sort.date.label"),title:y("daily.sort.date.title")},{key:"total_tokens",label:y("daily.sort.total.label"),title:y("daily.sort.total.title")},{key:"input_tokens",label:y("daily.sort.input.label"),title:y("daily.sort.input.title")},{key:"output_tokens",label:y("daily.sort.output.label"),title:y("daily.sort.output.title")},{key:"cached_input_tokens",label:y("daily.sort.cached.label"),title:y("daily.sort.cached.title")},{key:"reasoning_output_tokens",label:y("daily.sort.reasoning.label"),title:y("daily.sort.reasoning.title")},{key:"conversation_count",label:y("daily.sort.conversations.label"),title:y("daily.sort.conversations.title")}]}function Za(e){const t=nc(e)?e:"day";return lc().map((n,a)=>a===0?{...n,key:t}:n)}function er(e,{key:t,dir:n}){return go(e,{key:t,dir:n})}const jn=12,cc=["total_tokens","billable_total_tokens","input_tokens","cached_input_tokens","cache_creation_input_tokens","output_tokens","reasoning_output_tokens"];function dc(e){if(typeof e=="bigint")return e!==0n;if(typeof e=="number")return Number.isFinite(e)&&e!==0;if(e==null)return!1;const t=String(e).trim();if(!t||!/^-?\d+$/.test(t))return!1;const n=t.startsWith("-")?t.slice(1):t;return/[1-9]/.test(n)}function uc(e){return cc.some(t=>dc(e?.[t]))}function fc(e){const t=Array.isArray(e)?e:[];if(!t.length)return[];const n=go(t,{key:"month",dir:"asc"}),a=n.findIndex(r=>r?.month&&uc(r));return a===-1?t:n.slice(a)}function mc(e,t,n=jn){const a=Array.isArray(e)?e:[],r=Number.isFinite(n)&&n>0?n:jn,l=(Number.isFinite(t)&&t>=0?Math.floor(t):0)*r;return a.slice(l,l+r)}function hc(e){if(typeof e!="string")return null;const t=e.trim();return t?t.toLowerCase():null}function gc(e){const t=hc(e?.model_id);return t||null}function yc(e,t){return e?.model?String(e.model):t}const pc=new Set(["curated:fuzzy","litellm:fuzzy","litellm:prefix-strip"]),bc=new Set(["miss","unattributed","empty"]);function xc(e){const t=String(e||"").toLowerCase();return t.includes("free")||t.includes("hy3-preview")||/^glm-[\d.]+-flash(?![a-z])/.test(t)}function Sn(e,t=0){const n=Le(e?.billable_total_tokens),a=Le(e?.total_tokens);return n!=null&&n>0?n:a!=null&&a>0?a:n??a??t}function yo(e,{copyFn:t}={}){const n=typeof t=="function"?t:l=>l,r=(Array.isArray(e?.sources)?e.sources:[]).map(l=>{const i=Sn(l?.totals),c=Le(l?.totals?.total_cost_usd)??0;return{source:l?.source,totalTokens:Number.isFinite(i)?i:0,totalCost:Number.isFinite(c)?c:0,models:Array.isArray(l?.models)?l.models:[]}}).filter(l=>l.totalTokens>0);if(!r.length)return[];const s=r.reduce((l,i)=>l+i.totalTokens,0);return typeof e?.pricing?.pricing_mode=="string"&&e.pricing.pricing_mode.toUpperCase(),r.slice().sort((l,i)=>i.totalTokens-l.totalTokens).map(l=>{const i=l.source?String(l.source).toUpperCase():n("shared.placeholder.short"),c=s>0?l.totalTokens/s*100:0,u=Number.isFinite(c)?c.toFixed(1):"0.0",f=l.models.map(p=>{const b=Sn(p?.totals);if(!Number.isFinite(b)||b<=0)return null;const v=l.totalTokens>0?Math.round(b/l.totalTokens*1e3)/10:0,k=yc(p,n("shared.placeholder.short")),j=gc(p),x=Le(p?.totals?.total_cost_usd),N=x??(l.totalCost>0&&l.totalTokens>0?b/l.totalTokens*l.totalCost:null),C=typeof p?.pricing_tier=="string"?p.pricing_tier:null,T=C?bc.has(C)&&b>0:b>0&&(N==null||N<=0)&&!xc(k),z=!!(C&&pc.has(C));return{id:j,name:k,share:v,usage:b,cost:N,pricingTier:C,pricingMissing:T,pricingFuzzy:z}}).filter(Boolean),d=f.filter(p=>Number.isFinite(Number(p?.cost))&&Number(p.cost)>0).sort((p,b)=>Number(b.cost)-Number(p.cost))[0]||null,m=f.filter(p=>p?.pricingMissing),g=f.filter(p=>p?.pricingFuzzy);return{source:l.source,label:i,totalPercent:String(u),usd:l.totalCost,usage:l.totalTokens,topCostModel:d,missingPricingModels:m,fuzzyPricingModels:g,models:f}})}function kc(e,{copyFn:t}={}){const a=yo(e,{copyFn:typeof t=="function"?t:d=>d}),r=a.reduce((d,m)=>d+(Number(m?.usage)||0),0),s=a.reduce((d,m)=>d+(Number(m?.usd)||0),0),l=a.flatMap(d=>(d.models||[]).map(m=>({...m,source:d.label}))),i=l.filter(d=>Number.isFinite(Number(d?.cost))&&Number(d.cost)>0).sort((d,m)=>Number(m.cost)-Number(d.cost))[0]||null,c=l.filter(d=>Number.isFinite(Number(d?.usage))&&Number(d.usage)>0).sort((d,m)=>Number(m.usage)-Number(d.usage))[0]||null,u=l.filter(d=>d?.pricingMissing);return{fuzzyPricingModels:l.filter(d=>d?.pricingFuzzy),totalTokens:r,totalCost:s,costPerMillionTokens:r>0?s/(r/1e6):null,topCostModel:i,topUsageModel:c,missingPricingModels:u}}function wc(e,t="—"){const n=Object.entries(e?.models||{});if(!n.length)return t;let a=null,r=-1;for(const[s,l]of n){const i=Number(l);!Number.isFinite(i)||i<=r||(a=s,r=i)}return a||t}function vc(e,{fallback:t="—"}={}){const n=(Array.isArray(e)?e:[]).map(s=>{const l=Sn(s),i=Le(s?.total_cost_usd)??0,c=Number.isFinite(l)&&l>0?i/(l/1e6):null;return{...s,cost_per_million_tokens:c,top_model:wc(s,t)}}),a=n.reduce((s,l)=>{const i=Le(l?.cost_per_million_tokens);return i!=null&&i>0&&s.push(i),s},[]),r=a.length>0?a.reduce((s,l)=>s+l,0)/a.length:null;return n.map(s=>{const l=Le(s?.cost_per_million_tokens),i=l!=null&&r!=null&&r>0&&l>r*1.15;return{...s,cost_per_million_baseline:r,cost_per_million_status:i?"high":"normal"}})}const ut={emerald:{light:["#ebedf0","#a7f3d0","#6ee7b7","#34d399","#10b981"],dark:["#2d333b","#065f46","#059669","#10b981","#34d399"],gridColor:{light:"rgba(16, 185, 129, 0.12)",dark:"rgba(52, 211, 153, 0.08)"}},ocean:{light:["#f1f5f9","#93c5fd","#60a5fa","#3b82f6","#1d4ed8"],dark:["#1e293b","#1e3a8a","#2563eb","#3b82f6","#60a5fa"],gridColor:{light:"rgba(59, 130, 246, 0.12)",dark:"rgba(96, 165, 250, 0.08)"}},neon:{light:["#faf5ff","#ebd5ff","#c084fc","#a855f7","#7e22ce"],dark:["#2e1065","#581c87","#8b5cf6","#a855f7","#c084fc"],gridColor:{light:"rgba(168, 85, 247, 0.12)",dark:"rgba(192, 132, 252, 0.08)"}},amber:{light:["#fffbeb","#fde68a","#f59e0b","#d97706","#b45309"],dark:["#451a03","#78350f","#b45309","#d97706","#f59e0b"],gridColor:{light:"rgba(245, 158, 11, 0.12)",dark:"rgba(245, 158, 11, 0.08)"}}};function Nc(e,t){const n=/^#([0-9a-f]{6})$/i.exec(e);if(!n)return e;const a=parseInt(n[1],16),r=a>>16&255,s=a>>8&255,l=a&255,i=c=>Math.max(0,Math.min(255,Math.round(c*t)));return`rgb(${i(r)}, ${i(s)}, ${i(l)})`}function tt(e,t,n,a,r){const s=Math.cos(a),l=Math.sin(a),i=e*s-t*l,c=e*l+t*s,u=n,f=Math.cos(r),d=Math.sin(r),m=i,g=c*f-u*d,p=c*d+u*f;return{x:m,y:g,z:p}}function _c(e,t,n,a,r){return tt(e,t,n,a,r)}function po(e,t){const n=Number(t).toLocaleString();if(e>=4){const a=Math.floor(Math.random()*3)+1;return y(`heatmap.3d.voxel.joke.${a}`,{value:n})}else return e===3?y("heatmap.3d.voxel.level3",{value:n}):e===2?y("heatmap.3d.voxel.level2",{value:n}):e===1?y("heatmap.3d.voxel.level1",{value:n}):y("heatmap.3d.voxel.level0")}function tr({weeks:e,palette:t="auto",isDark:n=!1,interactive:a=!1,autoRotateInit:r=!1,onResetViewRef:s=null}){const l=ut[t]||(t==="auto"?ut.emerald:null),i=l?n?l.dark:l.light:Array.isArray(t)?t:n?ut.emerald.dark:ut.emerald.light,c=l?n?l.gridColor.dark:l.gridColor.light:n?"rgba(255,255,255,0.06)":"rgba(0,0,0,0.06)",u=-.2,f=.88,[d,m]=h.useState({yaw:u,pitch:f}),[g,p]=h.useState(r),[b,v]=h.useState(1),k=a?13:10.5,j=h.useMemo(()=>{const F=[],U=e.length;if(U===0||!a)return[];for(let Q=0;Q<=7;Q++){const G=(Q-3.5)*k,ne=tt(-U/2*k,G,0,d.yaw,d.pitch),se=tt(U/2*k,G,0,d.yaw,d.pitch);F.push({d:`M${ne.x},${ne.y} L${se.x},${se.y}`,key:`horiz-${Q}`})}for(let Q=0;Q<=U;Q+=4){const G=(Q-U/2)*k,ne=tt(G,-3.5*k,0,d.yaw,d.pitch),se=tt(G,3.5*k,0,d.yaw,d.pitch);F.push({d:`M${ne.x},${ne.y} L${se.x},${se.y}`,key:`vert-${Q}`})}if(U%4!==0){const Q=(U-U/2)*k,G=tt(Q,-3.5*k,0,d.yaw,d.pitch),ne=tt(Q,3.5*k,0,d.yaw,d.pitch);F.push({d:`M${G.x},${G.y} L${ne.x},${ne.y}`,key:"vert-last"})}return F},[e.length,d,k,a]);h.useEffect(()=>{s&&(s.current={reset:()=>{m({yaw:u,pitch:f}),p(!1),v(1),H()},toggleAutoRotate:F=>{p(F)}})},[s]);const x=h.useRef(null),N=h.useRef(null),C=h.useRef(!1),T=h.useRef({x:0,y:0}),z=h.useRef({yaw:u,pitch:f}),$=h.useRef({x:0,y:0}),D=h.useRef({x:0,y:0,time:0}),A=h.useRef(null),[K,B]=h.useState(0),E=h.useRef(null),W=h.useRef(!0);h.useEffect(()=>(W.current=!0,()=>{W.current=!1}),[]);const H=()=>{E.current&&cancelAnimationFrame(E.current),B(0);const F=performance.now(),U=1200,Q=G=>{if(!W.current)return;const ne=G-F,se=Math.min(1,ne/U),ue=1-Math.pow(1-se,3);B(ue),se<1?E.current=requestAnimationFrame(Q):E.current=null};E.current=requestAnimationFrame(Q)};h.useEffect(()=>(H(),()=>{E.current&&cancelAnimationFrame(E.current)}),[a]),h.useEffect(()=>{if(!g||C.current||typeof window>"u"||typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;let U;const Q=()=>{if(typeof document<"u"&&document.visibilityState==="hidden"){U=requestAnimationFrame(Q);return}m(G=>({yaw:G.yaw+.002,pitch:G.pitch})),U=requestAnimationFrame(Q)};return U=requestAnimationFrame(Q),()=>cancelAnimationFrame(U)},[g]);const _=(F,U)=>{a&&(C.current=!0,T.current={x:F,y:U},z.current={yaw:d.yaw,pitch:d.pitch},$.current={x:0,y:0},D.current={x:F,y:U,time:performance.now()},A.current&&cancelAnimationFrame(A.current))},w=(F,U)=>{if(!C.current)return;const Q=F-T.current.x,G=U-T.current.y,ne=performance.now(),se=ne-D.current.time;se>0&&($.current={x:(F-D.current.x)/se,y:(U-D.current.y)/se}),D.current={x:F,y:U,time:ne};const ue=.005,ie=z.current.yaw-Q*ue,me=Math.PI/2.3,De=Math.max(-me,Math.min(me,z.current.pitch-G*ue));m({yaw:ie,pitch:De})},I=()=>{if(!C.current)return;C.current=!1;let F=-$.current.x*12,U=-$.current.y*12;const Q=.95,G=()=>{C.current||(F*=Q,U*=Q,!(Math.abs(F)<.01&&Math.abs(U)<.01)&&(m(ne=>{const se=ne.yaw+F*.005,ue=Math.PI/2.3,ie=Math.max(-ue,Math.min(ue,ne.pitch+U*.005));return{yaw:se,pitch:ie}}),A.current=requestAnimationFrame(G)))};A.current=requestAnimationFrame(G)},[M,J]=h.useState(null),[P,L]=h.useState({x:0,y:0,shiftX:0}),V=h.useRef(null);h.useEffect(()=>()=>{V.current&&clearTimeout(V.current)},[]),h.useEffect(()=>{if(!a||!N.current)return;const F=Q=>{Q.preventDefault();const G=-Q.deltaY*.0025;v(ne=>{const se=ne+G;return Math.max(.5,Math.min(3,se))})},U=N.current;return U.addEventListener("wheel",F,{passive:!1}),()=>{U.removeEventListener("wheel",F)}},[a]);const q=h.useMemo(()=>{const F=[];return e.forEach((U,Q)=>{(Array.isArray(U)?U:[]).forEach((G,ne)=>{G&&F.push({key:G.day||`${Q}-${ne}`,col:Q,row:ne,level:G.level||0,value:G.value||0,total_tokens:G.total_tokens||0,day:G.day,models:G.models||null})})}),F},[e]),ve=k-(a?1.8:1.5),xe=a?38:28,pe=F=>Math.max(1.8,Number(F)/4*xe),Me=h.useMemo(()=>{if(q.length===0)return[];const F=e.length;return q.map(U=>{const Q=pe(U.level),G=Math.sqrt(Math.pow(U.col-F/2,2)+Math.pow(U.row-3.5,2)),ne=Math.sqrt(Math.pow(F/2,2)+Math.pow(3.5,2)),se=G/ne*.4,ue=Math.min(1,Math.max(0,(K-se)*(1/.6))),ie=Q*ue,me=(U.col-F/2)*k,De=(U.row-3.5)*k,ge=ve/2,Ee=[{x:me-ge,y:De-ge,z:0},{x:me+ge,y:De-ge,z:0},{x:me+ge,y:De+ge,z:0},{x:me-ge,y:De+ge,z:0},{x:me-ge,y:De-ge,z:ie},{x:me+ge,y:De-ge,z:ie},{x:me+ge,y:De+ge,z:ie},{x:me-ge,y:De+ge,z:ie}].map(ae=>tt(ae.x,ae.y,ae.z,d.yaw,d.pitch)),Ye=tt(me,De,ie/2,d.yaw,d.pitch),Mt=[{name:"top",indices:[4,5,6,7],scale:1,normal:[0,0,1]},{name:"bottom",indices:[3,2,1,0],scale:.4,normal:[0,0,-1]},{name:"left",indices:[3,0,4,7],scale:.55,normal:[-1,0,0]},{name:"right",indices:[1,2,6,5],scale:.75,normal:[1,0,0]},{name:"front",indices:[0,1,5,4],scale:.85,normal:[0,-1,0]},{name:"back",indices:[2,3,7,6],scale:.65,normal:[0,1,0]}],yt=i[Math.min(4,Math.max(0,Number(U.level)||0))],Ue=[],pt=.35,bt=-.4,re=.83;return Mt.forEach(ae=>{const ee=_c(ae.normal[0],ae.normal[1],ae.normal[2],d.yaw,d.pitch);if(ee.z>.001){const de=Ee[ae.indices[0]],Te=Ee[ae.indices[1]],le=Ee[ae.indices[2]],Ot=Ee[ae.indices[3]],Bt=`M${de.x},${de.y} L${Te.x},${Te.y} L${le.x},${le.y} L${Ot.x},${Ot.y} Z`,Ht=ee.x*pt+ee.y*bt+ee.z*re,jt=n?.18:0,xt=ae.scale*(.82+.28*Math.max(0,Ht))+jt;Ue.push({name:ae.name,d:Bt,fill:Nc(yt,xt)})}}),{...U,centerProj:Ye,renderedFaces:Ue}})},[q,d,i,e.length,K,k,ve,xe]),je=h.useMemo(()=>[...Me].sort((F,U)=>F.centerProj.z-U.centerProj.z),[Me]),ke=h.useMemo(()=>{if(je.length===0)return{minX:-100,minY:-100,maxX:100,maxY:100};let F=1/0,U=1/0,Q=-1/0,G=-1/0;return je.forEach(ne=>{const se=k*2,ue=ne.centerProj.x,ie=ne.centerProj.y;ue-se<F&&(F=ue-se),ue+se>Q&&(Q=ue+se),ie-se<U&&(U=ie-se),ie+se>G&&(G=ie+se)}),{minX:F,minY:U,maxX:Q,maxY:G}},[je,k]),Ce=12,O=ke.maxX-ke.minX+Ce*2,Y=ke.maxY-ke.minY+Ce*2,he=O/b,oe=Y/b,ye=ke.minX-Ce+(O-he)/2,Oe=ke.minY-Ce+(Y-oe)/2,$e=`${ye} ${Oe} ${he} ${oe}`;return q.length===0?o.jsx("div",{className:"py-8 text-center text-sm text-oai-gray-500",children:y("heatmap.empty")}):o.jsxs("div",{ref:N,className:`relative select-none outline-none ${a?"cursor-grab active:cursor-grabbing w-full h-full flex items-center justify-center":"w-full overflow-hidden flex justify-center"}`,onMouseDown:F=>{if(!a)return;_(F.clientX,F.clientY);const U=G=>w(G.clientX,G.clientY),Q=()=>{I(),window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Q)};window.addEventListener("mousemove",U),window.addEventListener("mouseup",Q)},onTouchStart:F=>{!a||F.touches.length===0||_(F.touches[0].clientX,F.touches[0].clientY)},onTouchMove:F=>{!a||F.touches.length===0||w(F.touches[0].clientX,F.touches[0].clientY)},onTouchEnd:()=>{a&&I()},children:[o.jsxs("svg",{ref:x,viewBox:$e,width:a?"95%":"100%",height:a?"95%":"auto",role:"img","aria-label":y("heatmap.iso.aria")||"3D interactive activity heatmap",style:{display:"block",width:"100%",height:"auto",maxWidth:a?"none":`${O}px`,maxHeight:a?"78vh":"none"},className:"transition-transform duration-300 ease-out",children:[a&&j.map(F=>o.jsx("path",{d:F.d,fill:"none",stroke:c,strokeWidth:.25,strokeDasharray:"1.5 2.5",strokeLinecap:"round"},F.key)),je.map(F=>{const U=M&&M.key===F.key;return o.jsxs("g",{onMouseEnter:Q=>{if(V.current&&(clearTimeout(V.current),V.current=null),J(F),a&&x.current){const G=tt((F.col-e.length/2)*k,(F.row-3.5)*k,pe(F.level),d.yaw,d.pitch);let ne=0,se=0;const ue=x.current;if(N.current&&typeof ue.createSVGPoint=="function"&&typeof ue.getScreenCTM=="function")try{const ge=ue.createSVGPoint();ge.x=G.x,ge.y=G.y;const Fe=ue.getScreenCTM();if(Fe){const Ee=ge.matrixTransform(Fe),Ye=N.current.getBoundingClientRect();ne=Ee.x-Ye.left,se=Ee.y-Ye.top}}catch{const Fe=ue.getBoundingClientRect(),Ee=ke.maxX-ke.minX+Ce*2,Ye=ke.maxY-ke.minY+Ce*2;ne=(G.x-(ke.minX-Ce))/Ee*Fe.width,se=(G.y-(ke.minY-Ce))/Ye*Fe.height}else{const ge=ue.getBoundingClientRect(),Fe=ke.maxX-ke.minX+Ce*2,Ee=ke.maxY-ke.minY+Ce*2;ne=(G.x-(ke.minX-Ce))/Fe*ge.width,se=(G.y-(ke.minY-Ce))/Ee*ge.height}const ie=140;let me=0;const De=N.current?N.current.getBoundingClientRect().width:ue.getBoundingClientRect().width;ne<ie?me=ie-ne:ne>De-ie&&(me=De-ie-ne),L({x:ne,y:se,shiftX:me})}},onMouseLeave:()=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{J(null)},150)},className:"transition-all duration-200",style:{filter:U?"brightness(1.15) drop-shadow(0 4px 6px rgba(0,0,0,0.15))":"none",cursor:a?"pointer":"default"},children:[!a&&F.day&&o.jsx("title",{children:`${F.day}: ${Number(F.value).toLocaleString()} conversations`}),F.renderedFaces.map((Q,G)=>o.jsx("path",{d:Q.d,fill:Q.fill,stroke:Q.fill,strokeWidth:.25,strokeLinejoin:"round"},G))]},F.key)})]}),a&&M&&o.jsxs("div",{onMouseEnter:()=>{V.current&&(clearTimeout(V.current),V.current=null)},onMouseLeave:()=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{J(null)},150)},className:"absolute z-[9999] w-0 h-0 transition-all duration-100 ease-out",style:{left:`${P.x}px`,top:`${P.y}px`},children:[o.jsxs("div",{className:"absolute left-0 bottom-[10px] backdrop-blur-md bg-white/90 dark:bg-oai-gray-900/90 border border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-xl rounded-xl p-3.5 max-w-[280px] min-w-[200px] flex flex-col gap-2 animate-in fade-in zoom-in-95 duration-100",style:{transform:`translateX(calc(-50% + ${P.shiftX}px))`},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-oai-gray-100 dark:border-oai-gray-800/80 pb-1.5",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400",children:M.day}),(()=>{const F=M.level===0?n?"#9ca3af":"#6b7280":i[M.level];return o.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:F+"22",color:F,border:`1px solid ${F}44`},children:["Level ",M.level]})})()]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-lg font-bold text-oai-gray-900 dark:text-white leading-none tabular-nums",children:Number(M.value??0).toLocaleString()}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 uppercase tracking-wider font-semibold",children:"Conversations"})]}),o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400 leading-none tabular-nums",children:Number(M.total_tokens??0).toLocaleString()}),o.jsx("span",{className:"text-[9px] text-oai-gray-400 uppercase tracking-wider",children:"tokens"})]})]}),M.models&&Object.keys(M.models).length>0?o.jsxs("div",{className:"mt-1.5 border-t border-oai-gray-100 dark:border-oai-gray-800/60 pt-2 flex flex-col gap-1.5",children:[o.jsx("div",{className:"text-[10px] font-semibold text-oai-gray-400 dark:text-oai-gray-500 uppercase tracking-wider",children:"Model Breakdown"}),o.jsx("div",{className:"flex flex-col gap-2 max-h-[150px] overflow-y-auto pr-1.5 scrollbar-thin",children:Object.entries(M.models).map(([F,U])=>({name:F,val:Number(U)})).sort((F,U)=>U.val-F.val).map(({name:F,val:U})=>{const Q=Number(M.total_tokens)||Object.values(M.models).reduce((ne,se)=>ne+Number(se||0),0)||1,G=Math.round(U/Q*100);return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] gap-3",children:[o.jsx("span",{className:"font-medium text-oai-gray-750 dark:text-oai-gray-200 truncate max-w-[120px]",title:F,children:F}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx("span",{className:"font-mono text-oai-gray-900 dark:text-oai-gray-100 font-semibold",children:U.toLocaleString()}),o.jsxs("span",{className:"text-[9px] text-oai-gray-450 dark:text-oai-gray-500 min-w-[28px] text-right font-medium",children:[G,"%"]})]})]}),o.jsx("div",{className:"w-full h-1 bg-oai-gray-100 dark:bg-oai-gray-800/85 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${G}%`,backgroundColor:i[4],boxShadow:`0 0 4px ${i[4]}55`}})})]},F)})})]}):o.jsx("p",{className:"text-[11px] text-oai-gray-600 dark:text-oai-gray-300 leading-relaxed font-normal mt-1 border-t border-dashed border-oai-gray-100 dark:border-oai-gray-800/60 pt-1.5",children:po(M.level,M.value)})]})]}),o.jsx("div",{className:"absolute bottom-[6px] left-0 -translate-x-1/2 w-2.5 h-2.5 rotate-45 bg-white dark:bg-oai-gray-900 border-r border-b border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-sm",style:{marginBottom:"1px"}})]})]})}const Mc=12,jc=3,Sc=26,Cc=["#ebedf0","#f7d08a","#f2b757","#eca02f","#d9861a"],Dc=["#30363d","#7a4711","#bf7015","#eca02f","#f7c877"];function nr(e){const t=Number(e);return Number.isFinite(t)?t<1e3?t.toLocaleString():Ae(t,{decimals:2}):"0"}function Tc(e){if(typeof e!="string")return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;const n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return Number.isFinite(n.getTime())?n:null}function bo(e,t){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+t))}function Pc(e,t){return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))/864e5)}function Oc(e,t){const n=t==="mon"?1:0,a=e.getUTCDay();return bo(e,-((a-n+7)%7))}function $c(e,t,n,a){if(!e)return[];const r=Tc(t)||new Date,s=[];for(let f=11;f>=0;f-=1)s.push(new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth()-f,1)));const l=Oc(r,n),i=bo(l,-(e-1)*7),c=[],u=new Set;for(const f of s){const d=Math.floor(Pc(i,f)/7);d<0||d>=e||u.has(d)||(u.add(d),c.push({label:a[f.getUTCMonth()],index:d}))}return c}function Ec({heatmap:e,timeZoneLabel:t,timeZoneShortLabel:n,hideLegend:a=!1,embedded:r=!1}){const{resolvedTheme:s}=Gr(),{currency:l,rate:i}=_t(),c=s==="dark",u=c?Dc:Cc,f=h.useRef(null),d=h.useRef(null),[m,g]=h.useState(null),[p,b]=h.useState({x:0,y:0,shiftX:0}),v=h.useRef(null);h.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const[k,j]=h.useState(!1),[x,N]=h.useState(!1),[C,T]=h.useState(!1),z=h.useRef(null),[$,D]=h.useState("amber"),A=[y("heatmap.month.jan"),y("heatmap.month.feb"),y("heatmap.month.mar"),y("heatmap.month.apr"),y("heatmap.month.may"),y("heatmap.month.jun"),y("heatmap.month.jul"),y("heatmap.month.aug"),y("heatmap.month.sep"),y("heatmap.month.oct"),y("heatmap.month.nov"),y("heatmap.month.dec")],K=(O,Y)=>{if(!Y||!Y.day)return;v.current&&(clearTimeout(v.current),v.current=null),g(Y);const he=O.currentTarget.getBoundingClientRect(),oe=typeof window<"u"?window.innerWidth:1024,ye=he.left+he.width/2,Oe=he.top,$e=140;let F=0;ye<$e?F=$e-ye:ye>oe-$e&&(F=oe-$e-ye),b({x:ye,y:Oe,shiftX:F})},B=()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{g(null)},150)},E=()=>{N(!1),j(!0)},W=()=>{N(!0)},H=O=>{O.target===O.currentTarget&&x&&(j(!1),N(!1))};h.useEffect(()=>{if(!k||x)return;const O=Y=>{Y.key==="Escape"&&W()};return window.addEventListener("keydown",O),()=>{window.removeEventListener("keydown",O)}},[k,x]);const _=h.useMemo(()=>({emerald:{accentText:"text-emerald-500 dark:text-emerald-400",accentBg:"bg-emerald-500/10 dark:bg-emerald-400/10",accentBorder:"border-emerald-500/20 dark:border-emerald-400/15",hoverBorder:"hover:border-emerald-500/30 dark:hover:border-emerald-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(16,185,129,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(52,211,153,0.25)]",rawColor:"#10b981"},ocean:{accentText:"text-blue-500 dark:text-blue-400",accentBg:"bg-blue-500/10 dark:bg-blue-400/10",accentBorder:"border-blue-500/20 dark:border-blue-400/15",hoverBorder:"hover:border-blue-500/30 dark:hover:border-blue-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(59,130,246,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(96,165,250,0.25)]",rawColor:"#3b82f6"},neon:{accentText:"text-purple-500 dark:text-purple-400",accentBg:"bg-purple-500/10 dark:bg-purple-400/10",accentBorder:"border-purple-500/20 dark:border-purple-400/15",hoverBorder:"hover:border-purple-500/30 dark:hover:border-purple-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(168,85,247,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(192,132,252,0.25)]",rawColor:"#a855f7"},amber:{accentText:"text-amber-500 dark:text-amber-400",accentBg:"bg-amber-500/10 dark:bg-amber-400/10",accentBorder:"border-amber-500/20 dark:border-amber-400/15",hoverBorder:"hover:border-amber-500/30 dark:hover:border-amber-400/30",hoverGlow:"hover:shadow-[0_0_20px_-3px_rgba(245,158,11,0.15)] hover:dark:shadow-[0_0_20px_-3px_rgba(245,158,11,0.25)]",rawColor:"#f59e0b"}}),[]),w=_[$]||_.emerald,I=ut[$]?c?ut[$].dark:ut[$].light:c?ut.emerald.dark:ut.emerald.light,[M,J]=h.useState(()=>{if(r)return"2d";try{return window.localStorage?.getItem("tt:heatmap-view")==="3d"?"3d":"2d"}catch{return"2d"}});h.useEffect(()=>{if(!r)try{window.localStorage?.setItem("tt:heatmap-view",M)}catch{}},[M,r]),h.useEffect(()=>{if(M!=="2d")return;const O=f.current;O&&(O.scrollLeft=O.scrollWidth)},[e?.weeks,M]),h.useEffect(()=>{const O=f.current;if(!O)return;const Y=()=>{v.current&&(clearTimeout(v.current),v.current=null),g(null)};return O.addEventListener("scroll",Y),()=>O.removeEventListener("scroll",Y)},[]);const P=e?.week_starts_on==="mon"?"mon":"sun",L=h.useMemo(()=>{const O=Array.isArray(e?.weeks)?e.weeks:[];if(!O.length)return{weeks:[]};const Y=[];for(const he of O)for(const oe of Array.isArray(he)?he:[])oe?.day&&Y.push({day:oe.day,conversation_count:oe.conversation_count??0,total_tokens:oe.total_tokens??0,billable_total_tokens:oe.billable_total_tokens??oe.total_tokens??0,models:oe.models??null});return Zn({dailyRows:Y,weeks:Math.max(52,O.length),to:e?.to,weekStartsOn:P})},[e?.to,e?.weeks,P]),V=L?.weeks||[],q=h.useMemo(()=>{let O=0,Y=0,he={day:"无数据",value:0},oe=0,ye=0;const Oe=[];V.forEach(ie=>{(Array.isArray(ie)?ie:[]).forEach(me=>{me&&me.day&&Oe.push(me)})}),Oe.sort((ie,me)=>ie.day.localeCompare(me.day)),Oe.forEach(ie=>{const me=Number(ie.value)||0;O+=Number(ie.total_tokens)||0,me>0?(Y++,oe++,oe>ye&&(ye=oe)):oe=0,me>he.value&&(he={day:ie.day,value:me})});const $e=Oe.length||365,F=(Y/$e*100).toFixed(1);let U="heatmap.3d.modal.ai.eval.default",Q="heatmap.3d.modal.ai.title.default";O>=15e6?(Q="heatmap.3d.modal.ai.title.peak",U="heatmap.3d.modal.ai.eval.peak"):O>=5e6?(Q="heatmap.3d.modal.ai.title.heavy",U="heatmap.3d.modal.ai.eval.heavy"):O>=1e6?(Q="heatmap.3d.modal.ai.title.core",U="heatmap.3d.modal.ai.eval.core"):O>=2e4&&(Q="heatmap.3d.modal.ai.title.steady",U="heatmap.3d.modal.ai.eval.steady");const G=e?.total_cost_usd,ne=Number(G),ue=G!=null&&(typeof G!="string"||G.trim()!=="")&&Number.isFinite(ne)?ne:O/15e5;return{totalTokens:O,activeDays:Y,activeRate:F,maxSingleDay:he,maxStreak:ye,aiEvaluationTitleKey:Q,aiEvaluationKey:U,totalCostUsd:ue}},[V,e?.total_cost_usd]),fe=h.useMemo(()=>et(q.totalCostUsd,{currency:l,rate:i}),[q.totalCostUsd,l,i]),ve=P==="mon"?["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(O=>y(`heatmap.day.${O.toLowerCase()}`)):["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(O=>y(`heatmap.day.${O.toLowerCase()}`)),xe=h.useMemo(()=>$c(V.length,L?.to,P,A),[L?.to,V.length,P,A]);if(!V.length)return o.jsx("div",{className:"py-8 text-center text-sm text-oai-gray-500",children:y("heatmap.empty")});const pe=r?10:Mc,Me=r?2:jc,je=r?22:Sc,ke=je+V.length*pe+Math.max(0,V.length-1)*Me,Ce=`${je}px repeat(${V.length}, ${pe}px)`;return o.jsxs("div",{ref:d,className:r?"relative":"relative rounded-xl border border-oai-gray-200 dark:border-oai-gray-800 bg-white dark:bg-oai-gray-900 p-5",children:[!r&&o.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[o.jsx("h3",{className:"text-sm font-medium text-oai-gray-500 dark:text-oai-gray-300 uppercase tracking-wide",children:y("heatmap.title")}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("div",{role:"tablist","aria-label":"Heatmap view",className:"flex rounded-md border border-oai-gray-200 dark:border-oai-gray-800 p-0.5 text-[10px]",children:[o.jsx("button",{type:"button",role:"tab","aria-selected":M==="2d",onClick:()=>J("2d"),className:M==="2d"?"px-2 py-0.5 rounded bg-oai-gray-100 text-oai-black dark:bg-oai-gray-800 dark:text-oai-white font-medium":"px-2 py-0.5 rounded text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-700 dark:hover:text-oai-gray-200",children:y("heatmap.view.2d")}),o.jsx("button",{type:"button",role:"tab","aria-selected":M==="3d",onClick:()=>J("3d"),className:M==="3d"?"px-2 py-0.5 rounded bg-oai-gray-100 text-oai-black dark:bg-oai-gray-800 dark:text-oai-white font-medium":"px-2 py-0.5 rounded text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-700 dark:hover:text-oai-gray-200",children:y("heatmap.view.3d")})]}),o.jsx("span",{className:"text-xs text-oai-gray-400 dark:text-oai-gray-450",children:n||y("heatmap.legend.utc")})]})]}),M==="3d"&&o.jsxs("div",{onClick:E,className:"cursor-pointer group relative overflow-hidden rounded-lg hover:border-oai-gray-350 dark:hover:border-oai-gray-700 border border-transparent transition-all",title:y("heatmap.3d.hover_tip"),children:[o.jsx(tr,{weeks:V,isDark:c,palette:$}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-oai-gray-900/5 to-transparent pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-2",children:o.jsxs("span",{className:"text-[10px] bg-white/95 dark:bg-oai-gray-900/95 shadow border border-oai-gray-200/60 dark:border-oai-gray-800/80 px-2.5 py-1 rounded-full font-medium text-oai-gray-500 dark:text-oai-gray-400 flex items-center gap-1 transform translate-y-2 group-hover:translate-y-0 transition-transform duration-200",children:[o.jsx(ao,{size:9}),y("heatmap.3d.hover_tip")]})})]}),M==="2d"&&o.jsx("div",{ref:f,className:"overflow-x-auto overflow-y-hidden heatmap-scroll-thin",children:o.jsxs("div",{style:{minWidth:ke},children:[o.jsxs("div",{className:"grid text-[10px] uppercase text-oai-gray-400 dark:text-oai-gray-400 mb-1",style:{gridTemplateColumns:Ce,columnGap:Me},children:[o.jsx("span",{}),xe.map(O=>o.jsx("span",{style:{gridColumnStart:O.index+2},className:"whitespace-nowrap",children:O.label},`${O.label}-${O.index}`))]}),o.jsxs("div",{className:"grid",style:{gridTemplateColumns:Ce,columnGap:Me},children:[o.jsx("div",{className:"grid text-[10px] text-oai-gray-400 dark:text-oai-gray-400 sticky left-0 bg-white dark:bg-oai-gray-900 pr-2",style:{gridTemplateRows:`repeat(7, ${pe}px)`,rowGap:Me},children:ve.map(O=>o.jsx("span",{className:"leading-none",children:O},O))}),o.jsx("div",{className:"grid",style:{gridAutoFlow:"column",gridTemplateRows:`repeat(7, ${pe}px)`,gap:Me},children:V.map((O,Y)=>(Array.isArray(O)?O:[]).map((he,oe)=>{if(!he)return null;const ye=he.day||`e-${Y}-${oe}`,Oe=Number(he.level)||0,$e=u[Oe]||u[0];return o.jsx("span",{onMouseEnter:F=>K(F,he),onMouseLeave:B,className:"rounded-[2px] transition-transform hover:scale-125 hover:z-10 cursor-pointer",style:{width:pe,height:pe,background:$e}},ye)}))})]})]})}),!a&&o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[o.jsx("span",{className:"text-[10px] text-oai-gray-400 dark:text-oai-gray-400",children:y("heatmap.legend.less")}),o.jsx("div",{className:"flex gap-0.5",children:u.map((O,Y)=>o.jsx("span",{className:"rounded-[1px]",style:{width:10,height:10,background:O}},Y))}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 dark:text-oai-gray-400",children:y("heatmap.legend.more")})]}),k&&o.jsx("div",{onAnimationEnd:H,onClick:O=>{O.target===O.currentTarget&&W()},className:`fixed inset-0 z-50 flex items-center justify-center p-3 md:p-6 backdrop-blur-md bg-black/15 dark:bg-black/40 ${x?"animate-tt-fade-out":"animate-tt-fade-in"}`,children:o.jsxs("div",{className:`relative w-full max-w-6xl h-[88vh] backdrop-blur-2xl bg-white/90 dark:bg-oai-gray-900/90 border border-oai-gray-200/50 dark:border-white/10 shadow-2xl rounded-2xl flex flex-col md:flex-row overflow-hidden ${x?"animate-tt-modal-exit":"animate-tt-modal"}`,children:[o.jsx("button",{type:"button",onClick:W,className:"absolute top-4 right-4 z-50 p-2 rounded-full border border-oai-gray-200/60 dark:border-oai-gray-800/60 bg-white/50 dark:bg-oai-gray-900/50 text-oai-gray-500 dark:text-oai-gray-400 hover:text-oai-gray-900 dark:hover:text-white hover:rotate-90 hover:scale-105 active:scale-95 transition-all duration-300",children:o.jsx(da,{size:16})}),o.jsxs("div",{className:"w-full md:w-[340px] border-b md:border-b-0 md:border-r border-zinc-200/50 dark:border-zinc-800/40 p-5 md:p-6 flex flex-col gap-6 overflow-y-auto backdrop-blur-md bg-zinc-50/50 dark:bg-zinc-950/50",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1.5 select-none",children:[o.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",style:{backgroundColor:w.rawColor}}),o.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5",style:{backgroundColor:w.rawColor}})]}),o.jsx("span",{className:"text-[9px] font-extrabold uppercase tracking-widest font-mono text-zinc-400 dark:text-zinc-500",children:"3D Insight"})]}),o.jsx("h4",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight leading-none mt-2 select-none",children:y("heatmap.3d.modal.title")}),o.jsx("p",{className:"text-[11px] leading-relaxed text-zinc-400 dark:text-zinc-500 mt-2 font-normal select-none",children:y("heatmap.3d.modal.desc")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-x-5 gap-y-5 border-y border-zinc-200/50 dark:border-zinc-800/50 py-5 select-none",children:[o.jsxs("div",{className:"flex flex-col gap-1 relative group cursor-help",children:[o.jsx("div",{className:"absolute left-0 bottom-full mb-2 pointer-events-none opacity-0 translate-y-1 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-200 z-50",children:o.jsxs("div",{className:"bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50 text-[10px] font-semibold font-mono rounded-lg px-2.5 py-1.5 shadow-xl border border-zinc-200 dark:border-zinc-800/80 whitespace-nowrap flex flex-col",children:[o.jsx("span",{className:"text-[9px] text-zinc-400 dark:text-zinc-500",children:y("heatmap.3d.modal.stats.precision_total_tokens")}),o.jsxs("span",{className:"mt-0.5 font-bold text-zinc-900 dark:text-zinc-50",children:[q.totalTokens.toLocaleString()," Tokens"]})]})}),o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.total_tokens")}),o.jsxs("div",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:nr(q.totalTokens)}),o.jsx("div",{className:"opacity-30 group-hover:opacity-60 transition-opacity",children:o.jsx("svg",{width:"24",height:"10",viewBox:"0 0 24 10",fill:"none",children:o.jsx("path",{d:"M1 9C3 7 5 7 7 4C9 1 11 0 13 2C15 4 17 0 23 0",stroke:w.rawColor,strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.estimated_cost")}),o.jsx("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:fe})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.active_rate_days")}),o.jsxs("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.activeRate,"% ",o.jsxs("span",{className:"text-[10px] font-bold text-zinc-400 dark:text-zinc-500 font-mono",children:["(",q.activeDays,"D)"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 group cursor-default",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.max_streak")}),o.jsxs("span",{className:"text-xl font-black text-amber-500 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.maxStreak," ",o.jsx("span",{className:"text-[10px] font-bold text-amber-500/80 font-mono",children:y("heatmap.3d.modal.stats.days_suffix")})]})]}),o.jsxs("div",{className:"flex flex-col gap-1 col-span-2 relative group cursor-help",children:[o.jsx("div",{className:"absolute left-0 bottom-full mb-2 pointer-events-none opacity-0 translate-y-1 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-200 z-50",children:o.jsxs("div",{className:"bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50 text-[10px] font-semibold font-mono rounded-lg px-2.5 py-1.5 shadow-xl border border-zinc-200 dark:border-zinc-800/80 whitespace-nowrap flex flex-col",children:[o.jsx("span",{className:"text-[9px] text-zinc-400 dark:text-zinc-500",children:y("heatmap.3d.modal.stats.precision_peak_value")}),o.jsxs("span",{className:"mt-0.5 font-bold text-zinc-900 dark:text-zinc-50",children:[q.maxSingleDay.value>0?q.maxSingleDay.value.toLocaleString():y("heatmap.3d.modal.stats.no_data")," conversations"]}),o.jsx("span",{className:"text-[8px] text-zinc-400 dark:text-zinc-500 mt-0.5",children:q.maxSingleDay.day!=="无数据"?q.maxSingleDay.day:y("heatmap.3d.modal.stats.no_data")})]})}),o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.stats.peak_day")}),o.jsxs("span",{className:"text-xl font-black text-zinc-900 dark:text-zinc-50 tracking-tight font-mono transition-transform duration-200 group-hover:-translate-y-[1px]",children:[q.maxSingleDay.value>0?nr(q.maxSingleDay.value):y("heatmap.3d.modal.stats.no_data")," ",o.jsxs("span",{className:"text-[10px] font-bold text-zinc-400 dark:text-zinc-500 font-mono",children:["(",q.maxSingleDay.day!=="无数据"?q.maxSingleDay.day:y("heatmap.3d.modal.stats.no_data"),")"]})]})]})]}),o.jsxs("div",{className:"flex flex-col gap-2.5 py-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5 select-none",children:[o.jsx(ro,{size:11,style:{color:w.rawColor}}),o.jsx("span",{className:"text-[9px] font-extrabold uppercase tracking-widest font-mono",style:{color:w.rawColor},children:y(q.aiEvaluationTitleKey)})]}),o.jsxs("div",{className:"pl-3.5 border-l-2 relative transition-all duration-300 group",style:{borderColor:w.rawColor},children:[o.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px] blur-[2px] opacity-15 pointer-events-none rounded-full",style:{backgroundColor:w.rawColor}}),o.jsx("p",{className:"text-[11px] leading-relaxed text-zinc-600 dark:text-zinc-400 font-normal",children:y(q.aiEvaluationKey)})]})]}),o.jsx("div",{className:"mt-auto border-t border-zinc-200/50 dark:border-zinc-800/50 pt-4 select-none",children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[9px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-widest font-mono",children:y("heatmap.3d.modal.legend.title")}),o.jsx("span",{className:"text-[10px] font-medium text-zinc-500 dark:text-zinc-400",children:y(`heatmap.3d.modal.palette.${$}`)})]}),o.jsx("div",{className:"flex gap-1",children:I.map((O,Y)=>o.jsx("div",{className:"flex-1 h-1 rounded-[2px]",style:{backgroundColor:O},title:`Level ${Y}`},Y))})]})})]}),o.jsxs("div",{className:"flex-1 h-full relative flex items-center justify-center overflow-hidden p-4",children:[o.jsx("div",{className:"absolute top-1/4 left-1/3 w-96 h-96 rounded-full blur-[130px] pointer-events-none -translate-x-1/2 -translate-y-1/2 transition-all duration-500",style:{backgroundColor:w.rawColor+"15"}}),o.jsx("div",{className:"absolute bottom-1/4 right-1/3 w-80 h-80 rounded-full blur-[120px] pointer-events-none translate-x-1/2 translate-y-1/2 bg-purple-500/[0.04] dark:bg-purple-500/[0.08]"}),o.jsxs("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 flex items-center gap-3 p-1.5 backdrop-blur-md bg-white/70 dark:bg-oai-gray-900/75 border border-oai-gray-200/60 dark:border-oai-gray-800/80 rounded-full shadow-lg z-30 select-none",children:[o.jsx("div",{className:"flex items-center gap-1.5 px-2",children:Object.keys(_).map(O=>{const Y=$===O;return o.jsx("button",{type:"button",onClick:()=>D(O),title:y(`heatmap.3d.modal.palette.${O}`),className:`w-3.5 h-3.5 rounded-full transition-all duration-200 relative hover:scale-125 ${O==="emerald"?"bg-[#10b981]":O==="ocean"?"bg-[#3b82f6]":O==="neon"?"bg-[#a855f7]":"bg-[#f59e0b]"}`,children:Y&&o.jsx("span",{className:"absolute inset-0 rounded-full ring-2 ring-offset-1 ring-offset-white dark:ring-offset-oai-gray-900 ring-oai-gray-900 dark:ring-white scale-110"})},O)})}),o.jsx("div",{className:"w-[1px] h-4 bg-oai-gray-200 dark:bg-oai-gray-800"}),o.jsxs("div",{className:"flex items-center gap-1 pr-1",children:[o.jsx("button",{type:"button",onClick:()=>{const O=!C;T(O),z.current&&z.current.toggleAutoRotate(O)},title:C?y("heatmap.3d.modal.control.pause"):y("heatmap.3d.modal.control.play"),className:`p-1.5 rounded-full transition-all duration-200 hover:bg-oai-gray-100 dark:hover:bg-oai-gray-800 ${C?w.accentText:"text-oai-gray-400 hover:text-oai-gray-600 dark:hover:text-oai-gray-250"}`,children:C?o.jsx(qi,{size:12}):o.jsx(Gi,{size:12})}),o.jsx("button",{type:"button",onClick:()=>{T(!1),z.current&&z.current.reset()},title:y("heatmap.3d.modal.control.reset"),className:"p-1.5 rounded-full text-oai-gray-400 hover:text-oai-gray-600 dark:hover:text-oai-gray-250 hover:bg-oai-gray-100 dark:hover:bg-oai-gray-800 transition-all duration-200",children:o.jsx(Qi,{size:12})})]})]}),o.jsx(tr,{weeks:V,isDark:c,interactive:!0,palette:$,autoRotateInit:C,onResetViewRef:z}),o.jsxs("div",{className:"absolute bottom-4 right-4 flex items-center gap-1.5 text-[9px] font-bold text-oai-gray-400 bg-white/80 dark:bg-oai-gray-900/80 border border-oai-gray-200/50 dark:border-oai-gray-800/80 rounded-md px-2.5 py-1.5 select-none pointer-events-none backdrop-blur-md shadow-sm",children:[o.jsx(ma,{size:10,className:w.accentText}),o.jsx("span",{children:y("heatmap.3d.modal.footer.tip")})]})]})]})}),m&&!k&&typeof document<"u"&&gi.createPortal(o.jsxs("div",{className:"fixed z-[9999] w-0 h-0 transition-all duration-100 ease-out pointer-events-none",style:{left:`${p.x}px`,top:`${p.y}px`},children:[o.jsxs("div",{className:"absolute left-0 bottom-[10px] backdrop-blur-md bg-white/95 dark:bg-oai-gray-900/95 border border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-xl rounded-xl p-3.5 max-w-[280px] min-w-[200px] flex flex-col gap-2 animate-in fade-in zoom-in-95 duration-100",style:{transform:`translateX(calc(-50% + ${p.shiftX}px))`},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-oai-gray-100 dark:border-oai-gray-800/80 pb-1.5",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400",children:m.day}),(()=>{const O=m.level===0?c?"#9ca3af":"#6b7280":u[m.level];return o.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:O+"22",color:O,border:`1px solid ${O}44`},children:["Level ",m.level]})})()]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-lg font-bold text-oai-gray-900 dark:text-white leading-none tabular-nums",children:Number(m.value??0).toLocaleString()}),o.jsx("span",{className:"text-[10px] text-oai-gray-400 uppercase tracking-wider font-semibold",children:"Conversations"})]}),o.jsxs("div",{className:"flex items-baseline gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-oai-gray-500 dark:text-oai-gray-400 leading-none tabular-nums",children:Number(m.total_tokens??0).toLocaleString()}),o.jsx("span",{className:"text-[9px] text-oai-gray-400 uppercase tracking-wider",children:"tokens"})]})]}),m.models&&Object.keys(m.models).length>0?o.jsxs("div",{className:"mt-1.5 border-t border-oai-gray-100 dark:border-oai-gray-800/60 pt-2 flex flex-col gap-1.5",children:[o.jsx("div",{className:"text-[10px] font-semibold text-oai-gray-400 dark:text-oai-gray-500 uppercase tracking-wider",children:"Model Breakdown"}),o.jsx("div",{className:"flex flex-col gap-2 max-h-[150px] overflow-y-auto pr-1.5 oai-scrollbar",children:Object.entries(m.models).map(([O,Y])=>({name:O,val:Number(Y)})).sort((O,Y)=>Y.val-O.val).map(({name:O,val:Y})=>{const he=Number(m.total_tokens??m.value)||1,oe=Math.round(Y/he*100);return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] gap-3",children:[o.jsx("span",{className:"font-medium text-oai-gray-750 dark:text-oai-gray-200 truncate max-w-[120px]",title:O,children:O}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx("span",{className:"font-mono text-oai-gray-900 dark:text-oai-gray-100 font-semibold",children:Y.toLocaleString()}),o.jsxs("span",{className:"text-[9px] text-oai-gray-450 dark:text-oai-gray-500 min-w-[28px] text-right font-medium",children:[oe,"%"]})]})]}),o.jsx("div",{className:"w-full h-1 bg-oai-gray-100 dark:bg-oai-gray-800/85 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${oe}%`,backgroundColor:u[4],boxShadow:`0 0 4px ${u[4]}55`}})})]},O)})})]}):o.jsx("p",{className:"text-[11px] text-oai-gray-600 dark:text-oai-gray-300 leading-relaxed font-normal mt-1 border-t border-dashed border-oai-gray-100 dark:border-oai-gray-800/60 pt-1.5",children:po(m.level,m.total_tokens??m.value)})]})]}),o.jsx("div",{className:"absolute bottom-[6px] left-0 -translate-x-1/2 w-2.5 h-2.5 rotate-45 bg-white dark:bg-oai-gray-900 border-r border-b border-oai-gray-200/50 dark:border-oai-gray-800/50 shadow-sm",style:{marginBottom:"1px"}})]}),document.body),o.jsx("style",{children:`
2
2
  @keyframes tt-fade-in {
3
3
  from { opacity: 0; }
4
4
  to { opacity: 1; }
@@ -1 +1 @@
1
- import{n as d,j as n,o as a}from"./main-DBDTVhz8.js";function v({children:i,delay:t=0,duration:o=.35,y:e=12,className:s="",once:r=!0}){return d()?n.jsx("div",{className:s,children:i}):n.jsx(a.div,{initial:{opacity:0,y:e},animate:{opacity:1,y:0},transition:{duration:o,delay:t,ease:[.16,1,.3,1]},className:s,children:i})}function x({children:i,staggerDelay:t=.1,initialDelay:o=0,className:e=""}){return d()?n.jsx("div",{className:e,children:i}):n.jsx(a.div,{initial:"hidden",animate:"visible",variants:{hidden:{},visible:{transition:{staggerChildren:t,delayChildren:o}}},className:e,children:i})}function h({children:i,className:t="",y:o=12}){return d()?n.jsx("div",{className:t,children:i}):n.jsx(a.div,{variants:{hidden:{opacity:0,y:o},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}},className:t,children:i})}export{v as F,x as S,h as a};
1
+ import{n as d,j as n,o as a}from"./main-rZD26_5f.js";function v({children:i,delay:t=0,duration:o=.35,y:e=12,className:s="",once:r=!0}){return d()?n.jsx("div",{className:s,children:i}):n.jsx(a.div,{initial:{opacity:0,y:e},animate:{opacity:1,y:0},transition:{duration:o,delay:t,ease:[.16,1,.3,1]},className:s,children:i})}function x({children:i,staggerDelay:t=.1,initialDelay:o=0,className:e=""}){return d()?n.jsx("div",{className:e,children:i}):n.jsx(a.div,{initial:"hidden",animate:"visible",variants:{hidden:{},visible:{transition:{staggerChildren:t,delayChildren:o}}},className:e,children:i})}function h({children:i,className:t="",y:o=12}){return d()?n.jsx("div",{className:t,children:i}):n.jsx(a.div,{variants:{hidden:{opacity:0,y:o},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}},className:t,children:i})}export{v as F,x as S,h as a};