ldrouter 1.18.0 → 1.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/server/config/index.js +10 -1
- package/dist/server/routes/admin/api-keys.js +1 -2
- package/dist/server/routes/admin/backup.js +21 -6
- package/dist/server/routes/admin/combos.js +2 -1
- package/dist/server/routes/admin/models.js +7 -7
- package/dist/server/routes/admin/providers.js +15 -14
- package/dist/server/routes/admin/setup.js +4 -1
- package/dist/web/assets/{index-CyboDiyN.js → index-DYrnLQwk.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
|
@@ -338,12 +338,12 @@ Please change the parent <Route path="${N}"> to <Route path="${N==="/"?"*":`${N}
|
|
|
338
338
|
.block-interactivity-`.concat(n,` {pointer-events: none;}
|
|
339
339
|
.allow-interactivity-`).concat(n,` {pointer-events: all;}
|
|
340
340
|
`)},aA=0,Ms=[];function rA(n){var a=m.useRef([]),l=m.useRef([0,0]),s=m.useRef(),c=m.useState(aA++)[0],u=m.useState(J1)[0],f=m.useRef(n);m.useEffect(function(){f.current=n},[n]),m.useEffect(function(){if(n.inert){document.body.classList.add("block-interactivity-".concat(c));var j=EM([n.lockRef.current],(n.shards||[]).map(Sb),!0).filter(Boolean);return j.forEach(function(C){return C.classList.add("allow-interactivity-".concat(c))}),function(){document.body.classList.remove("block-interactivity-".concat(c)),j.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(c))})}}},[n.inert,n.lockRef.current,n.shards]);var p=m.useCallback(function(j,C){if("touches"in j&&j.touches.length===2||j.type==="wheel"&&j.ctrlKey)return!f.current.allowPinchZoom;var N=Bc(j),M=l.current,T="deltaX"in j?j.deltaX:M[0]-N[0],D="deltaY"in j?j.deltaY:M[1]-N[1],O,A=j.target,U=Math.abs(T)>Math.abs(D)?"h":"v";if("touches"in j&&U==="h"&&A.type==="range")return!1;var k=window.getSelection(),$=k&&k.anchorNode,X=$?$===A||$.contains(A):!1;if(X)return!1;var te=bb(U,A);if(!te)return!0;if(te?O=U:(O=U==="v"?"h":"v",te=bb(U,A)),!te)return!1;if(!s.current&&"changedTouches"in j&&(T||D)&&(s.current=O),!O)return!0;var G=s.current||O;return eA(G,C,j,G==="h"?T:D)},[]),g=m.useCallback(function(j){var C=j;if(!(!Ms.length||Ms[Ms.length-1]!==u)){var N="deltaY"in C?wb(C):Bc(C),M=a.current.filter(function(O){return O.name===C.type&&(O.target===C.target||C.target===O.shadowParent)&&tA(O.delta,N)})[0];if(M&&M.should){C.cancelable&&C.preventDefault();return}if(!M){var T=(f.current.shards||[]).map(Sb).filter(Boolean).filter(function(O){return O.contains(C.target)}),D=T.length>0?p(C,T[0]):!f.current.noIsolation;D&&C.cancelable&&C.preventDefault()}}},[]),v=m.useCallback(function(j,C,N,M){var T={name:j,delta:C,target:N,should:M,shadowParent:lA(N)};a.current.push(T),setTimeout(function(){a.current=a.current.filter(function(D){return D!==T})},1)},[]),x=m.useCallback(function(j){l.current=Bc(j),s.current=void 0},[]),y=m.useCallback(function(j){v(j.type,wb(j),j.target,p(j,n.lockRef.current))},[]),b=m.useCallback(function(j){v(j.type,Bc(j),j.target,p(j,n.lockRef.current))},[]);m.useEffect(function(){return Ms.push(u),n.setCallbacks({onScrollCapture:y,onWheelCapture:y,onTouchMoveCapture:b}),document.addEventListener("wheel",g,Ts),document.addEventListener("touchmove",g,Ts),document.addEventListener("touchstart",x,Ts),function(){Ms=Ms.filter(function(j){return j!==u}),document.removeEventListener("wheel",g,Ts),document.removeEventListener("touchmove",g,Ts),document.removeEventListener("touchstart",x,Ts)}},[]);var w=n.removeScrollBar,E=n.inert;return m.createElement(m.Fragment,null,E?m.createElement(u,{styles:nA(c)}):null,w?m.createElement(KM,{noRelative:n.noRelative,gapMode:n.gapMode}):null)}function lA(n){for(var a=null;n!==null;)n instanceof ShadowRoot&&(a=n.host,n=n.host),n=n.parentNode;return a}const sA=kM(Z1,rA);var Bu=m.forwardRef(function(n,a){return m.createElement(Uu,ka({},n,{ref:a,sideCar:sA}))});Bu.classNames=Uu.classNames;var oA=Object.defineProperty,pt=(n,a)=>oA(n,"name",{value:a,configurable:!0}),iA=["Enter"," "],cA=["ArrowDown","PageUp","Home"],nw=["ArrowUp","PageDown","End"],uA=[...cA,...nw],Hu="Menu",[rm,dA,fA]=Ru(Hu),[Ul,aw]=kn(Hu,[fA,Ks,Lu]),tp=Ks(),rw=Lu(),[hA,hi]=Ul(Hu),[mA,np]=Ul(Hu),pA=pt(n=>{const{__scopeMenu:a,open:l=!1,children:s,dir:c,onOpenChange:u,modal:f=!0}=n,p=tp(a),[g,v]=m.useState(null),x=m.useRef(!1),y=ia(u),b=di(c);return m.useEffect(()=>{const w=pt(()=>{x.current=!0,document.addEventListener("pointerdown",E,{capture:!0,once:!0}),document.addEventListener("pointermove",E,{capture:!0,once:!0})},"handleKeyDown"),E=pt(()=>x.current=!1,"handlePointer");return document.addEventListener("keydown",w,{capture:!0}),()=>{document.removeEventListener("keydown",w,{capture:!0}),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointermove",E,{capture:!0})}},[]),m.useEffect(()=>{if(!l)return;const w=pt(()=>y(!1),"handleBlur");return window.addEventListener("blur",w),()=>window.removeEventListener("blur",w)},[l,y]),o.jsx(O1,{...p,children:o.jsx(hA,{scope:a,open:l,onOpenChange:y,content:g,onContentChange:v,children:o.jsx(mA,{scope:a,onClose:m.useCallback(()=>y(!1),[y]),isUsingKeyboardRef:x,dir:b,modal:f,children:s})})})},"Menu"),gA=m.forwardRef(pt(function(a,l){const{__scopeMenu:s,...c}=a,u=tp(s);return o.jsx(_1,{...u,...c,ref:l})},"MenuAnchor")),lw="MenuPortal",[vA,xA]=Ul(lw,{forceMount:void 0}),yA=pt(n=>{const{__scopeMenu:a,forceMount:l,children:s,container:c}=n,u=hi(lw,a);return o.jsx(vA,{scope:a,forceMount:l,children:o.jsx(Cr,{present:l||u.open,children:o.jsx(Zm,{asChild:!0,container:c,children:s})})})},"MenuPortal"),ll="MenuContent",[bA,sw]=Ul(ll),wA=m.forwardRef(pt(function(a,l){const s=xA(ll,a.__scopeMenu),{forceMount:c=s.forceMount,...u}=a,f=hi(ll,a.__scopeMenu),p=np(ll,a.__scopeMenu);return o.jsx(rm.Provider,{scope:a.__scopeMenu,children:o.jsx(Cr,{present:c||f.open,children:o.jsx(rm.Slot,{scope:a.__scopeMenu,children:p.modal?o.jsx(SA,{...u,ref:l}):o.jsx(jA,{...u,ref:l})})})})},"MenuContent")),SA=m.forwardRef(pt(function(a,l){const s=hi(ll,a.__scopeMenu),c=m.useRef(null),u=Xe(l,c);return m.useEffect(()=>{const f=c.current;if(f)return ep(f)},[]),o.jsx(ow,{...a,ref:u,trapFocus:s.open,disableOutsidePointerEvents:s.open,disableOutsideScroll:!0,onFocusOutside:Ne(a.onFocusOutside,f=>f.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>s.onOpenChange(!1)})},"MenuRootContentModal")),jA=m.forwardRef(pt(function(a,l){const s=hi(ll,a.__scopeMenu);return o.jsx(ow,{...a,ref:l,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>s.onOpenChange(!1)})},"MenuRootContentNonModal")),CA=Ha("MenuContent.ScrollLock"),ow=m.forwardRef(pt(function(a,l){const{__scopeMenu:s,loop:c=!1,trapFocus:u,onOpenAutoFocus:f,onCloseAutoFocus:p,disableOutsidePointerEvents:g,onEntryFocus:v,onEscapeKeyDown:x,onPointerDownOutside:y,onFocusOutside:b,onInteractOutside:w,onDismiss:E,disableOutsideScroll:j,...C}=a,N=hi(ll,s),M=np(ll,s),T=tp(s),D=rw(s),O=dA(s),[A,U]=m.useState(null),k=m.useRef(null),$=Xe(l,k,N.onContentChange),X=m.useRef(0),te=m.useRef(""),G=m.useRef(0),ie=m.useRef(null),ce=m.useRef("right"),se=m.useRef(0),_=j?Bu:m.Fragment,H=j?{as:CA,allowPinchZoom:!0}:void 0,Q=pt(ee=>{var oe,de;const z=te.current+ee,I=O().filter(fe=>!fe.disabled),F=document.activeElement,re=(oe=I.find(fe=>fe.ref.current===F))==null?void 0:oe.textValue,he=I.map(fe=>fe.textValue),ge=fw(he,z,re),q=(de=I.find(fe=>fe.textValue===ge))==null?void 0:de.ref.current;pt((function fe(Te){te.current=Te,window.clearTimeout(X.current),Te!==""&&(X.current=window.setTimeout(()=>fe(""),1e3))}),"updateSearch")(z),q&&setTimeout(()=>q.focus())},"handleTypeaheadSearch");m.useEffect(()=>()=>window.clearTimeout(X.current),[]),fi();const J=m.useCallback(ee=>{var I,F;return ce.current===((I=ie.current)==null?void 0:I.side)&&mw(ee,(F=ie.current)==null?void 0:F.area)},[]);return o.jsx(bA,{scope:s,searchRef:te,onItemEnter:m.useCallback(ee=>{J(ee)&&ee.preventDefault()},[J]),onItemLeave:m.useCallback(ee=>{var z;J(ee)||((z=k.current)==null||z.focus(),U(null))},[J]),onTriggerLeave:m.useCallback(ee=>{J(ee)&&ee.preventDefault()},[J]),pointerGraceTimerRef:G,onPointerGraceIntentChange:m.useCallback(ee=>{ie.current=ee},[]),children:o.jsx(_,{...H,children:o.jsx(qm,{asChild:!0,trapped:u,onMountAutoFocus:Ne(f,ee=>{var z;ee.preventDefault(),(z=k.current)==null||z.focus({preventScroll:!0})}),onUnmountAutoFocus:p,children:o.jsx(Nu,{asChild:!0,disableOutsidePointerEvents:g,onEscapeKeyDown:x,onPointerDownOutside:y,onFocusOutside:b,onInteractOutside:w,onDismiss:E,children:o.jsx(G1,{asChild:!0,...D,dir:M.dir,orientation:"vertical",loop:c,currentTabStopId:A,onCurrentTabStopIdChange:U,onEntryFocus:Ne(v,ee=>{M.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Qm,{role:"menu","aria-orientation":"vertical","data-state":iw(N.open),"data-radix-menu-content":"",dir:M.dir,...T,...C,ref:$,style:{outline:"none",...C.style},onKeyDown:Ne(C.onKeyDown,ee=>{const I=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,F=ee.ctrlKey||ee.altKey||ee.metaKey,re=ee.key.length===1;I&&(ee.key==="Tab"&&ee.preventDefault(),!F&&re&&Q(ee.key));const he=k.current;if(ee.target!==he||!uA.includes(ee.key))return;ee.preventDefault();const q=O().filter(oe=>!oe.disabled).map(oe=>oe.ref.current);nw.includes(ee.key)&&q.reverse(),uw(q)}),onBlur:Ne(a.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(X.current),te.current="")}),onPointerMove:Ne(a.onPointerMove,cu(ee=>{const z=ee.target,I=se.current!==ee.clientX;if(ee.currentTarget.contains(z)&&I){const F=ee.clientX>se.current?"right":"left";ce.current=F,se.current=ee.clientX}}))})})})})})})},"MenuContentImpl")),EA=m.forwardRef(pt(function(a,l){const{__scopeMenu:s,...c}=a;return o.jsx(Ve.div,{...c,ref:l})},"MenuLabel")),lm="MenuItem",jb="menu.itemSelect",RA=m.forwardRef(pt(function(a,l){const{disabled:s=!1,onSelect:c,...u}=a,f=m.useRef(null),p=np(lm,a.__scopeMenu),g=sw(lm,a.__scopeMenu),v=Xe(l,f),x=m.useRef(!1),y=pt(()=>{const b=f.current;if(!s&&b){const w=new CustomEvent(jb,{bubbles:!0,cancelable:!0});b.addEventListener(jb,E=>c==null?void 0:c(E),{once:!0}),Bm(b,w),w.defaultPrevented?x.current=!1:p.onClose()}},"handleSelect");return o.jsx(NA,{...u,ref:v,disabled:s,onClick:Ne(a.onClick,y),onPointerDown:b=>{var w;(w=a.onPointerDown)==null||w.call(a,b),x.current=!0},onPointerUp:Ne(a.onPointerUp,b=>{var w;x.current||(w=b.currentTarget)==null||w.click()}),onKeyDown:Ne(a.onKeyDown,b=>{s||b.target!==b.currentTarget||g.searchRef.current!==""&&b.key===" "||iA.includes(b.key)&&(b.currentTarget.click(),b.preventDefault())})})},"MenuItem")),NA=m.forwardRef(pt(function(a,l){const{__scopeMenu:s,disabled:c=!1,textValue:u,...f}=a,p=sw(lm,s),g=rw(s),v=m.useRef(null),x=Xe(l,v),[y,b]=m.useState(!1),[w,E]=m.useState("");return m.useEffect(()=>{const j=v.current;j&&E((j.textContent??"").trim())},[f.children]),o.jsx(rm.ItemSlot,{scope:s,disabled:c,textValue:u??w,children:o.jsx(K1,{asChild:!0,...g,focusable:!c,children:o.jsx(Ve.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":c||void 0,"data-disabled":c?"":void 0,...f,ref:x,onPointerMove:Ne(a.onPointerMove,cu(j=>{c?p.onItemLeave(j):(p.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ne(a.onPointerLeave,cu(j=>p.onItemLeave(j))),onFocus:Ne(a.onFocus,()=>b(!0)),onBlur:Ne(a.onBlur,()=>b(!1))})})})},"MenuItemImpl")),TA="MenuRadioGroup",[B4,H4]=Ul(TA,{value:void 0,onValueChange:pt(()=>{},"onValueChange")}),MA="MenuItemIndicator",[I4,P4]=Ul(MA,{checked:!1}),AA=m.forwardRef(pt(function(a,l){const{__scopeMenu:s,...c}=a;return o.jsx(Ve.div,{role:"separator","aria-orientation":"horizontal",...c,ref:l})},"MenuSeparator")),DA="MenuSub",[q4,V4]=Ul(DA);function iw(n){return n?"open":"closed"}pt(iw,"getOpenState");function cw(n){return n==="indeterminate"}pt(cw,"isIndeterminate");function OA(n){return cw(n)?"indeterminate":n?"checked":"unchecked"}pt(OA,"getCheckedState");function uw(n){const a=document.activeElement;for(const l of n)if(l===a||(l.focus(),document.activeElement!==a))return}pt(uw,"focusFirst");function dw(n,a){return n.map((l,s)=>n[(a+s)%n.length])}pt(dw,"wrapArray");function fw(n,a,l){const c=a.length>1&&Array.from(a).every(v=>v===a[0])?a[0]:a,u=l?n.indexOf(l):-1;let f=dw(n,Math.max(u,0));c.length===1&&(f=f.filter(v=>v!==l));const g=f.find(v=>v.toLowerCase().startsWith(c.toLowerCase()));return g!==l?g:void 0}pt(fw,"getNextMatch");function hw(n,a){const{x:l,y:s}=n;let c=!1;for(let u=0,f=a.length-1;u<a.length;f=u++){const p=a[u],g=a[f],v=p.x,x=p.y,y=g.x,b=g.y;x>s!=b>s&&l<(y-v)*(s-x)/(b-x)+v&&(c=!c)}return c}pt(hw,"isPointInPolygon");function mw(n,a){if(!a)return!1;const l={x:n.clientX,y:n.clientY};return hw(l,a)}pt(mw,"isPointerInGraceArea");function cu(n){return a=>a.pointerType==="mouse"?n(a):void 0}pt(cu,"whenMouse");var _A=pA,kA=gA,zA=yA,LA=wA,UA=EA,BA=RA,HA=AA,IA=Object.defineProperty,Bl=(n,a)=>IA(n,"name",{value:a,configurable:!0}),ap="DropdownMenu",[PA,$4]=kn(ap,[aw]),Hl=aw(),[qA,pw]=PA(ap),VA=Bl(n=>{const{__scopeDropdownMenu:a,children:l,dir:s,open:c,defaultOpen:u,onOpenChange:f,modal:p=!0}=n,g=Hl(a),v=m.useRef(null),[x,y]=yr({prop:c,defaultProp:u??!1,onChange:f,caller:ap});return o.jsx(qA,{scope:a,triggerId:La(),triggerRef:v,contentId:La(),open:x,onOpenChange:y,onOpenToggle:m.useCallback(()=>y(b=>!b),[y]),modal:p,children:o.jsx(_A,{...g,open:x,onOpenChange:y,dir:s,modal:p,children:l})})},"DropdownMenu"),$A="DropdownMenuTrigger",YA=m.forwardRef(Bl(function(a,l){const{__scopeDropdownMenu:s,disabled:c=!1,...u}=a,f=pw($A,s),p=Hl(s),g=Xe(l,f.triggerRef);return o.jsx(kA,{asChild:!0,...p,children:o.jsx(Ve.button,{type:"button",id:f.triggerId,"aria-haspopup":"menu","aria-expanded":f.open,"aria-controls":f.open?f.contentId:void 0,"data-state":f.open?"open":"closed","data-disabled":c?"":void 0,disabled:c,...u,ref:g,onPointerDown:Ne(a.onPointerDown,v=>{!c&&v.button===0&&v.ctrlKey===!1&&(f.onOpenToggle(),f.open||v.preventDefault())}),onKeyDown:Ne(a.onKeyDown,v=>{c||(["Enter"," "].includes(v.key)&&f.onOpenToggle(),v.key==="ArrowDown"&&f.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(v.key)&&v.preventDefault())})})})},"DropdownMenuTrigger")),GA=Bl(n=>{const{__scopeDropdownMenu:a,...l}=n,s=Hl(a);return o.jsx(zA,{...s,...l})},"DropdownMenuPortal"),KA="DropdownMenuContent",XA=m.forwardRef(Bl(function(a,l){const{__scopeDropdownMenu:s,...c}=a,u=pw(KA,s),f=Hl(s),p=m.useRef(!1);return o.jsx(LA,{id:u.contentId,"aria-labelledby":u.triggerId,...f,...c,ref:l,onCloseAutoFocus:Ne(a.onCloseAutoFocus,g=>{var v;p.current||(v=u.triggerRef.current)==null||v.focus(),p.current=!1,g.preventDefault()}),onInteractOutside:Ne(a.onInteractOutside,g=>{const v=g.detail.originalEvent,x=v.button===0&&v.ctrlKey===!0,y=v.button===2||x;(!u.modal||y)&&(p.current=!0)}),style:{...a.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),FA=m.forwardRef(Bl(function(a,l){const{__scopeDropdownMenu:s,...c}=a,u=Hl(s);return o.jsx(UA,{...u,...c,ref:l})},"DropdownMenuLabel")),QA=m.forwardRef(Bl(function(a,l){const{__scopeDropdownMenu:s,...c}=a,u=Hl(s);return o.jsx(BA,{...u,...c,ref:l})},"DropdownMenuItem")),ZA=m.forwardRef(Bl(function(a,l){const{__scopeDropdownMenu:s,...c}=a,u=Hl(s);return o.jsx(HA,{...u,...c,ref:l})},"DropdownMenuSeparator")),JA=VA,WA=YA,eD=GA,gw=XA,vw=FA,xw=QA,yw=ZA;const tD=JA,nD=WA,bw=m.forwardRef(({className:n,sideOffset:a=4,...l},s)=>o.jsx(eD,{children:o.jsx(gw,{ref:s,sideOffset:a,className:Ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",n),...l})}));bw.displayName=gw.displayName;const ww=m.forwardRef(({className:n,inset:a,...l},s)=>o.jsx(xw,{ref:s,className:Ee("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",n),...l}));ww.displayName=xw.displayName;const aD=m.forwardRef(({className:n,...a},l)=>o.jsx(vw,{ref:l,className:Ee("px-2 py-1.5 text-sm font-semibold",n),...a}));aD.displayName=vw.displayName;const rD=m.forwardRef(({className:n,...a},l)=>o.jsx(yw,{ref:l,className:Ee("-mx-1 my-1 h-px bg-muted",n),...a}));rD.displayName=yw.displayName;function lD(){const{theme:n,setTheme:a}=mN(),{user:l,logout:s}=_m(),[c,u]=m.useState(!1),[f,p]=m.useState(null),g=oi(),v=n==="light"?yR:n==="dark"?fR:dR;return m.useEffect(()=>{Se.get("/api/admin/update/check?force=1").then(x=>p(x)).catch(()=>{})},[]),o.jsxs("header",{className:"flex h-14 items-center justify-between border-b bg-background px-4",children:[o.jsx("div",{className:"text-sm text-muted-foreground",children:"Admin"}),o.jsxs("div",{className:"flex items-center gap-2",children:[(f==null?void 0:f.hasUpdate)&&o.jsxs(me,{variant:"ghost",size:"sm",title:`New version available: v${f.latestVersion} — go to Settings → System to update`,onClick:()=>g("/settings?tab=system"),children:[o.jsx(WE,{className:"mr-1 h-4 w-4 text-blue-500"}),"Update v",f.latestVersion]}),o.jsx(me,{variant:"ghost",size:"icon",onClick:()=>a(n==="dark"?"light":"dark"),children:o.jsx(v,{className:"h-4 w-4"})}),o.jsxs(tD,{open:c,onOpenChange:u,children:[o.jsx(nD,{asChild:!0,children:o.jsx(me,{variant:"ghost",children:(l==null?void 0:l.username)??"admin"})}),o.jsx(bw,{align:"end",children:o.jsxs(ww,{onClick:()=>void s(),children:[o.jsx(uR,{className:"mr-2 h-4 w-4"})," Sign out"]})})]})]})]})}const Ae=m.forwardRef(({className:n,type:a,...l},s)=>o.jsx("input",{type:a,className:Ee("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",n),ref:s,...l}));Ae.displayName="Input";var sD=Object.defineProperty,oD=(n,a)=>sD(n,"name",{value:a,configurable:!0}),iD=m.forwardRef(oD(function(a,l){return o.jsx(Ve.label,{...a,ref:l,onMouseDown:s=>{var u;s.target.closest("button, input, select, textarea")||((u=a.onMouseDown)==null||u.call(a,s),!s.defaultPrevented&&s.detail>1&&s.preventDefault())}})},"Label")),Sw=iD;const we=m.forwardRef(({className:n,...a},l)=>o.jsx(Sw,{ref:l,className:Ee("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",n),...a}));we.displayName=Sw.displayName;const nt=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{ref:l,className:Ee("rounded-lg border bg-card text-card-foreground shadow-sm",n),...a}));nt.displayName="Card";const at=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{ref:l,className:Ee("flex flex-col space-y-1.5 p-6",n),...a}));at.displayName="CardHeader";const rt=m.forwardRef(({className:n,...a},l)=>o.jsx("h3",{ref:l,className:Ee("text-lg font-semibold leading-none tracking-tight",n),...a}));rt.displayName="CardTitle";const gn=m.forwardRef(({className:n,...a},l)=>o.jsx("p",{ref:l,className:Ee("text-sm text-muted-foreground",n),...a}));gn.displayName="CardDescription";const lt=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{ref:l,className:Ee("p-6 pt-0",n),...a}));lt.displayName="CardContent";const jw=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{ref:l,className:Ee("flex items-center p-6 pt-0",n),...a}));jw.displayName="CardFooter";var cD=n=>{switch(n){case"success":return fD;case"info":return mD;case"warning":return hD;case"error":return pD;default:return null}},uD=Array(12).fill(0),dD=({visible:n,className:a})=>ue.createElement("div",{className:["sonner-loading-wrapper",a].filter(Boolean).join(" "),"data-visible":n},ue.createElement("div",{className:"sonner-spinner"},uD.map((l,s)=>ue.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),fD=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),hD=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),mD=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),pD=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),gD=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ue.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ue.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),vD=()=>{let[n,a]=ue.useState(document.hidden);return ue.useEffect(()=>{let l=()=>{a(document.hidden)};return document.addEventListener("visibilitychange",l),()=>window.removeEventListener("visibilitychange",l)},[]),n},sm=1,xD=class{constructor(){this.subscribe=n=>(this.subscribers.push(n),()=>{let a=this.subscribers.indexOf(n);this.subscribers.splice(a,1)}),this.publish=n=>{this.subscribers.forEach(a=>a(n))},this.addToast=n=>{this.publish(n),this.toasts=[...this.toasts,n]},this.create=n=>{var a;let{message:l,...s}=n,c=typeof(n==null?void 0:n.id)=="number"||((a=n.id)==null?void 0:a.length)>0?n.id:sm++,u=this.toasts.find(p=>p.id===c),f=n.dismissible===void 0?!0:n.dismissible;return this.dismissedToasts.has(c)&&this.dismissedToasts.delete(c),u?this.toasts=this.toasts.map(p=>p.id===c?(this.publish({...p,...n,id:c,title:l}),{...p,...n,id:c,dismissible:f,title:l}):p):this.addToast({title:l,...s,dismissible:f,id:c}),c},this.dismiss=n=>(this.dismissedToasts.add(n),n||this.toasts.forEach(a=>{this.subscribers.forEach(l=>l({id:a.id,dismiss:!0}))}),this.subscribers.forEach(a=>a({id:n,dismiss:!0})),n),this.message=(n,a)=>this.create({...a,message:n}),this.error=(n,a)=>this.create({...a,message:n,type:"error"}),this.success=(n,a)=>this.create({...a,type:"success",message:n}),this.info=(n,a)=>this.create({...a,type:"info",message:n}),this.warning=(n,a)=>this.create({...a,type:"warning",message:n}),this.loading=(n,a)=>this.create({...a,type:"loading",message:n}),this.promise=(n,a)=>{if(!a)return;let l;a.loading!==void 0&&(l=this.create({...a,promise:n,type:"loading",message:a.loading,description:typeof a.description!="function"?a.description:void 0}));let s=n instanceof Promise?n:n(),c=l!==void 0,u,f=s.then(async g=>{if(u=["resolve",g],ue.isValidElement(g))c=!1,this.create({id:l,type:"default",message:g});else if(bD(g)&&!g.ok){c=!1;let v=typeof a.error=="function"?await a.error(`HTTP error! status: ${g.status}`):a.error,x=typeof a.description=="function"?await a.description(`HTTP error! status: ${g.status}`):a.description;this.create({id:l,type:"error",message:v,description:x})}else if(a.success!==void 0){c=!1;let v=typeof a.success=="function"?await a.success(g):a.success,x=typeof a.description=="function"?await a.description(g):a.description;this.create({id:l,type:"success",message:v,description:x})}}).catch(async g=>{if(u=["reject",g],a.error!==void 0){c=!1;let v=typeof a.error=="function"?await a.error(g):a.error,x=typeof a.description=="function"?await a.description(g):a.description;this.create({id:l,type:"error",message:v,description:x})}}).finally(()=>{var g;c&&(this.dismiss(l),l=void 0),(g=a.finally)==null||g.call(a)}),p=()=>new Promise((g,v)=>f.then(()=>u[0]==="reject"?v(u[1]):g(u[1])).catch(v));return typeof l!="string"&&typeof l!="number"?{unwrap:p}:Object.assign(l,{unwrap:p})},this.custom=(n,a)=>{let l=(a==null?void 0:a.id)||sm++;return this.create({jsx:n(l),id:l,...a}),l},this.getActiveToasts=()=>this.toasts.filter(n=>!this.dismissedToasts.has(n.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Tn=new xD,yD=(n,a)=>{let l=(a==null?void 0:a.id)||sm++;return Tn.addToast({title:n,...a,id:l}),l},bD=n=>n&&typeof n=="object"&&"ok"in n&&typeof n.ok=="boolean"&&"status"in n&&typeof n.status=="number",wD=yD,SD=()=>Tn.toasts,jD=()=>Tn.getActiveToasts(),ve=Object.assign(wD,{success:Tn.success,info:Tn.info,warning:Tn.warning,error:Tn.error,custom:Tn.custom,message:Tn.message,promise:Tn.promise,dismiss:Tn.dismiss,loading:Tn.loading},{getHistory:SD,getToasts:jD});function CD(n,{insertAt:a}={}){if(typeof document>"u")return;let l=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",a==="top"&&l.firstChild?l.insertBefore(s,l.firstChild):l.appendChild(s),s.styleSheet?s.styleSheet.cssText=n:s.appendChild(document.createTextNode(n))}CD(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
|
|
341
|
-
`);function Hc(n){return n.label!==void 0}var ED=3,RD="32px",ND="16px",Cb=4e3,TD=356,MD=14,AD=20,DD=200;function xa(...n){return n.filter(Boolean).join(" ")}function OD(n){let[a,l]=n.split("-"),s=[];return a&&s.push(a),l&&s.push(l),s}var _D=n=>{var a,l,s,c,u,f,p,g,v,x,y;let{invert:b,toast:w,unstyled:E,interacting:j,setHeights:C,visibleToasts:N,heights:M,index:T,toasts:D,expanded:O,removeToast:A,defaultRichColors:U,closeButton:k,style:$,cancelButtonStyle:X,actionButtonStyle:te,className:G="",descriptionClassName:ie="",duration:ce,position:se,gap:_,loadingIcon:H,expandByDefault:Q,classNames:J,icons:ee,closeButtonAriaLabel:z="Close toast",pauseWhenPageIsHidden:I}=n,[F,re]=ue.useState(null),[he,ge]=ue.useState(null),[q,oe]=ue.useState(!1),[de,fe]=ue.useState(!1),[Te,je]=ue.useState(!1),[De,Fe]=ue.useState(!1),[et,le]=ue.useState(!1),[Le,Ie]=ue.useState(0),[kt,St]=ue.useState(0),Ft=ue.useRef(w.duration||ce||Cb),on=ue.useRef(null),Qt=ue.useRef(null),jt=T===0,fn=T+1<=N,Mt=w.type,At=w.dismissible!==!1,cn=w.className||"",fa=w.descriptionClassName||"",Ta=ue.useMemo(()=>M.findIndex(Ce=>Ce.toastId===w.id)||0,[M,w.id]),Gn=ue.useMemo(()=>{var Ce;return(Ce=w.closeButton)!=null?Ce:k},[w.closeButton,k]),dl=ue.useMemo(()=>w.duration||ce||Cb,[w.duration,ce]),ha=ue.useRef(0),Dt=ue.useRef(0),hn=ue.useRef(0),Tt=ue.useRef(null),[Js,Pl]=se.split("-"),ql=ue.useMemo(()=>M.reduce((Ce,ke,Ue)=>Ue>=Ta?Ce:Ce+ke.height,0),[M,Ta]),Ya=vD(),Nr=w.invert||b,vt=Mt==="loading";Dt.current=ue.useMemo(()=>Ta*_+ql,[Ta,ql]),ue.useEffect(()=>{Ft.current=dl},[dl]),ue.useEffect(()=>{oe(!0)},[]),ue.useEffect(()=>{let Ce=Qt.current;if(Ce){let ke=Ce.getBoundingClientRect().height;return St(ke),C(Ue=>[{toastId:w.id,height:ke,position:w.position},...Ue]),()=>C(Ue=>Ue.filter(gt=>gt.toastId!==w.id))}},[C,w.id]),ue.useLayoutEffect(()=>{if(!q)return;let Ce=Qt.current,ke=Ce.style.height;Ce.style.height="auto";let Ue=Ce.getBoundingClientRect().height;Ce.style.height=ke,St(Ue),C(gt=>gt.find(Ct=>Ct.toastId===w.id)?gt.map(Ct=>Ct.toastId===w.id?{...Ct,height:Ue}:Ct):[{toastId:w.id,height:Ue,position:w.position},...gt])},[q,w.title,w.description,C,w.id]);let st=ue.useCallback(()=>{fe(!0),Ie(Dt.current),C(Ce=>Ce.filter(ke=>ke.toastId!==w.id)),setTimeout(()=>{A(w)},DD)},[w,A,C,Dt]);ue.useEffect(()=>{if(w.promise&&Mt==="loading"||w.duration===1/0||w.type==="loading")return;let Ce;return O||j||I&&Ya?(()=>{if(hn.current<ha.current){let ke=new Date().getTime()-ha.current;Ft.current=Ft.current-ke}hn.current=new Date().getTime()})():Ft.current!==1/0&&(ha.current=new Date().getTime(),Ce=setTimeout(()=>{var ke;(ke=w.onAutoClose)==null||ke.call(w,w),st()},Ft.current)),()=>clearTimeout(Ce)},[O,j,w,Mt,I,Ya,st]),ue.useEffect(()=>{w.delete&&st()},[st,w.delete]);function Bt(){var Ce,ke,Ue;return ee!=null&&ee.loading?ue.createElement("div",{className:xa(J==null?void 0:J.loader,(Ce=w==null?void 0:w.classNames)==null?void 0:Ce.loader,"sonner-loader"),"data-visible":Mt==="loading"},ee.loading):H?ue.createElement("div",{className:xa(J==null?void 0:J.loader,(ke=w==null?void 0:w.classNames)==null?void 0:ke.loader,"sonner-loader"),"data-visible":Mt==="loading"},H):ue.createElement(dD,{className:xa(J==null?void 0:J.loader,(Ue=w==null?void 0:w.classNames)==null?void 0:Ue.loader),visible:Mt==="loading"})}return ue.createElement("li",{tabIndex:0,ref:Qt,className:xa(G,cn,J==null?void 0:J.toast,(a=w==null?void 0:w.classNames)==null?void 0:a.toast,J==null?void 0:J.default,J==null?void 0:J[Mt],(l=w==null?void 0:w.classNames)==null?void 0:l[Mt]),"data-sonner-toast":"","data-rich-colors":(s=w.richColors)!=null?s:U,"data-styled":!(w.jsx||w.unstyled||E),"data-mounted":q,"data-promise":!!w.promise,"data-swiped":et,"data-removed":de,"data-visible":fn,"data-y-position":Js,"data-x-position":Pl,"data-index":T,"data-front":jt,"data-swiping":Te,"data-dismissible":At,"data-type":Mt,"data-invert":Nr,"data-swipe-out":De,"data-swipe-direction":he,"data-expanded":!!(O||Q&&q),style:{"--index":T,"--toasts-before":T,"--z-index":D.length-T,"--offset":`${de?Le:Dt.current}px`,"--initial-height":Q?"auto":`${kt}px`,...$,...w.style},onDragEnd:()=>{je(!1),re(null),Tt.current=null},onPointerDown:Ce=>{vt||!At||(on.current=new Date,Ie(Dt.current),Ce.target.setPointerCapture(Ce.pointerId),Ce.target.tagName!=="BUTTON"&&(je(!0),Tt.current={x:Ce.clientX,y:Ce.clientY}))},onPointerUp:()=>{var Ce,ke,Ue,gt;if(De||!At)return;Tt.current=null;let Ct=Number(((Ce=Qt.current)==null?void 0:Ce.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ct=Number(((ke=Qt.current)==null?void 0:ke.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),$t=new Date().getTime()-((Ue=on.current)==null?void 0:Ue.getTime()),xt=F==="x"?Ct:ct,zt=Math.abs(xt)/$t;if(Math.abs(xt)>=AD||zt>.11){Ie(Dt.current),(gt=w.onDismiss)==null||gt.call(w,w),ge(F==="x"?Ct>0?"right":"left":ct>0?"down":"up"),st(),Fe(!0),le(!1);return}je(!1),re(null)},onPointerMove:Ce=>{var ke,Ue,gt,Ct;if(!Tt.current||!At||((ke=window.getSelection())==null?void 0:ke.toString().length)>0)return;let ct=Ce.clientY-Tt.current.y,$t=Ce.clientX-Tt.current.x,xt=(Ue=n.swipeDirections)!=null?Ue:OD(se);!F&&(Math.abs($t)>1||Math.abs(ct)>1)&&re(Math.abs($t)>Math.abs(ct)?"x":"y");let zt={x:0,y:0};F==="y"?(xt.includes("top")||xt.includes("bottom"))&&(xt.includes("top")&&ct<0||xt.includes("bottom")&&ct>0)&&(zt.y=ct):F==="x"&&(xt.includes("left")||xt.includes("right"))&&(xt.includes("left")&&$t<0||xt.includes("right")&&$t>0)&&(zt.x=$t),(Math.abs(zt.x)>0||Math.abs(zt.y)>0)&&le(!0),(gt=Qt.current)==null||gt.style.setProperty("--swipe-amount-x",`${zt.x}px`),(Ct=Qt.current)==null||Ct.style.setProperty("--swipe-amount-y",`${zt.y}px`)}},Gn&&!w.jsx?ue.createElement("button",{"aria-label":z,"data-disabled":vt,"data-close-button":!0,onClick:vt||!At?()=>{}:()=>{var Ce;st(),(Ce=w.onDismiss)==null||Ce.call(w,w)},className:xa(J==null?void 0:J.closeButton,(c=w==null?void 0:w.classNames)==null?void 0:c.closeButton)},(u=ee==null?void 0:ee.close)!=null?u:gD):null,w.jsx||m.isValidElement(w.title)?w.jsx?w.jsx:typeof w.title=="function"?w.title():w.title:ue.createElement(ue.Fragment,null,Mt||w.icon||w.promise?ue.createElement("div",{"data-icon":"",className:xa(J==null?void 0:J.icon,(f=w==null?void 0:w.classNames)==null?void 0:f.icon)},w.promise||w.type==="loading"&&!w.icon?w.icon||Bt():null,w.type!=="loading"?w.icon||(ee==null?void 0:ee[Mt])||cD(Mt):null):null,ue.createElement("div",{"data-content":"",className:xa(J==null?void 0:J.content,(p=w==null?void 0:w.classNames)==null?void 0:p.content)},ue.createElement("div",{"data-title":"",className:xa(J==null?void 0:J.title,(g=w==null?void 0:w.classNames)==null?void 0:g.title)},typeof w.title=="function"?w.title():w.title),w.description?ue.createElement("div",{"data-description":"",className:xa(ie,fa,J==null?void 0:J.description,(v=w==null?void 0:w.classNames)==null?void 0:v.description)},typeof w.description=="function"?w.description():w.description):null),m.isValidElement(w.cancel)?w.cancel:w.cancel&&Hc(w.cancel)?ue.createElement("button",{"data-button":!0,"data-cancel":!0,style:w.cancelButtonStyle||X,onClick:Ce=>{var ke,Ue;Hc(w.cancel)&&At&&((Ue=(ke=w.cancel).onClick)==null||Ue.call(ke,Ce),st())},className:xa(J==null?void 0:J.cancelButton,(x=w==null?void 0:w.classNames)==null?void 0:x.cancelButton)},w.cancel.label):null,m.isValidElement(w.action)?w.action:w.action&&Hc(w.action)?ue.createElement("button",{"data-button":!0,"data-action":!0,style:w.actionButtonStyle||te,onClick:Ce=>{var ke,Ue;Hc(w.action)&&((Ue=(ke=w.action).onClick)==null||Ue.call(ke,Ce),!Ce.defaultPrevented&&st())},className:xa(J==null?void 0:J.actionButton,(y=w==null?void 0:w.classNames)==null?void 0:y.actionButton)},w.action.label):null))};function Eb(){if(typeof window>"u"||typeof document>"u")return"ltr";let n=document.documentElement.getAttribute("dir");return n==="auto"||!n?window.getComputedStyle(document.documentElement).direction:n}function kD(n,a){let l={};return[n,a].forEach((s,c)=>{let u=c===1,f=u?"--mobile-offset":"--offset",p=u?ND:RD;function g(v){["top","right","bottom","left"].forEach(x=>{l[`${f}-${x}`]=typeof v=="number"?`${v}px`:v})}typeof s=="number"||typeof s=="string"?g(s):typeof s=="object"?["top","right","bottom","left"].forEach(v=>{s[v]===void 0?l[`${f}-${v}`]=p:l[`${f}-${v}`]=typeof s[v]=="number"?`${s[v]}px`:s[v]}):g(p)}),l}var zD=m.forwardRef(function(n,a){let{invert:l,position:s="bottom-right",hotkey:c=["altKey","KeyT"],expand:u,closeButton:f,className:p,offset:g,mobileOffset:v,theme:x="light",richColors:y,duration:b,style:w,visibleToasts:E=ED,toastOptions:j,dir:C=Eb(),gap:N=MD,loadingIcon:M,icons:T,containerAriaLabel:D="Notifications",pauseWhenPageIsHidden:O}=n,[A,U]=ue.useState([]),k=ue.useMemo(()=>Array.from(new Set([s].concat(A.filter(I=>I.position).map(I=>I.position)))),[A,s]),[$,X]=ue.useState([]),[te,G]=ue.useState(!1),[ie,ce]=ue.useState(!1),[se,_]=ue.useState(x!=="system"?x:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),H=ue.useRef(null),Q=c.join("+").replace(/Key/g,"").replace(/Digit/g,""),J=ue.useRef(null),ee=ue.useRef(!1),z=ue.useCallback(I=>{U(F=>{var re;return(re=F.find(he=>he.id===I.id))!=null&&re.delete||Tn.dismiss(I.id),F.filter(({id:he})=>he!==I.id)})},[]);return ue.useEffect(()=>Tn.subscribe(I=>{if(I.dismiss){U(F=>F.map(re=>re.id===I.id?{...re,delete:!0}:re));return}setTimeout(()=>{$E.flushSync(()=>{U(F=>{let re=F.findIndex(he=>he.id===I.id);return re!==-1?[...F.slice(0,re),{...F[re],...I},...F.slice(re+1)]:[I,...F]})})})}),[]),ue.useEffect(()=>{if(x!=="system"){_(x);return}if(x==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?_("dark"):_("light")),typeof window>"u")return;let I=window.matchMedia("(prefers-color-scheme: dark)");try{I.addEventListener("change",({matches:F})=>{_(F?"dark":"light")})}catch{I.addListener(({matches:re})=>{try{_(re?"dark":"light")}catch(he){console.error(he)}})}},[x]),ue.useEffect(()=>{A.length<=1&&G(!1)},[A]),ue.useEffect(()=>{let I=F=>{var re,he;c.every(ge=>F[ge]||F.code===ge)&&(G(!0),(re=H.current)==null||re.focus()),F.code==="Escape"&&(document.activeElement===H.current||(he=H.current)!=null&&he.contains(document.activeElement))&&G(!1)};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[c]),ue.useEffect(()=>{if(H.current)return()=>{J.current&&(J.current.focus({preventScroll:!0}),J.current=null,ee.current=!1)}},[H.current]),ue.createElement("section",{ref:a,"aria-label":`${D} ${Q}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},k.map((I,F)=>{var re;let[he,ge]=I.split("-");return A.length?ue.createElement("ol",{key:I,dir:C==="auto"?Eb():C,tabIndex:-1,ref:H,className:p,"data-sonner-toaster":!0,"data-theme":se,"data-y-position":he,"data-lifted":te&&A.length>1&&!u,"data-x-position":ge,style:{"--front-toast-height":`${((re=$[0])==null?void 0:re.height)||0}px`,"--width":`${TD}px`,"--gap":`${N}px`,...w,...kD(g,v)},onBlur:q=>{ee.current&&!q.currentTarget.contains(q.relatedTarget)&&(ee.current=!1,J.current&&(J.current.focus({preventScroll:!0}),J.current=null))},onFocus:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||ee.current||(ee.current=!0,J.current=q.relatedTarget)},onMouseEnter:()=>G(!0),onMouseMove:()=>G(!0),onMouseLeave:()=>{ie||G(!1)},onDragEnd:()=>G(!1),onPointerDown:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||ce(!0)},onPointerUp:()=>ce(!1)},A.filter(q=>!q.position&&F===0||q.position===I).map((q,oe)=>{var de,fe;return ue.createElement(_D,{key:q.id,icons:T,index:oe,toast:q,defaultRichColors:y,duration:(de=j==null?void 0:j.duration)!=null?de:b,className:j==null?void 0:j.className,descriptionClassName:j==null?void 0:j.descriptionClassName,invert:l,visibleToasts:E,closeButton:(fe=j==null?void 0:j.closeButton)!=null?fe:f,interacting:ie,position:I,style:j==null?void 0:j.style,unstyled:j==null?void 0:j.unstyled,classNames:j==null?void 0:j.classNames,cancelButtonStyle:j==null?void 0:j.cancelButtonStyle,actionButtonStyle:j==null?void 0:j.actionButtonStyle,removeToast:z,toasts:A.filter(Te=>Te.position==q.position),heights:$.filter(Te=>Te.position==q.position),setHeights:X,expandByDefault:u,gap:N,loadingIcon:M,expanded:te,pauseWhenPageIsHidden:O,swipeDirections:n.swipeDirections})})):null}))});function LD(){const{login:n}=_m(),[a,l]=m.useState("admin"),[s,c]=m.useState(""),[u,f]=m.useState(""),[p,g]=m.useState(""),[v,x]=m.useState(!1),[y,b]=m.useState(!1),w=oi(),E=_n();return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:o.jsxs(nt,{className:"w-full max-w-sm",children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("img",{src:"/logo.png",alt:"LateDev Router",className:"h-8 w-8 object-contain"}),o.jsx(rt,{children:"Sign in"})]}),o.jsx(gn,{children:"Enter your admin credentials."})]}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Username"}),o.jsx(Ae,{value:a,onChange:j=>l(j.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Password"}),o.jsx(Ae,{type:"password",value:s,onChange:j=>c(j.target.value)})]}),v&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"2FA code (or recovery code)"}),o.jsx(Ae,{value:u,onChange:j=>f(j.target.value),placeholder:"123456",maxLength:6})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Recovery code (alternative)"}),o.jsx(Ae,{value:p,onChange:j=>g(j.target.value),placeholder:"ABCD12-EF3456"})]})]})]}),o.jsx("div",{className:"px-6 pb-6",children:o.jsx(me,{className:"w-full",disabled:y,onClick:async()=>{var j,C;b(!0);try{if((await n(a,s,u||void 0,p||void 0)).totpRequired){x(!0);return}const M=((C=(j=E.state)==null?void 0:j.from)==null?void 0:C.pathname)??"/";w(M,{replace:!0})}catch(N){ve.error(N.message)}finally{b(!1)}},children:"Sign in"})})]})})}function UD(){const[n,a]=m.useState("admin"),[l,s]=m.useState(""),[c,u]=m.useState(""),[f,p]=m.useState(!1),[g,v]=m.useState(!0),[x,y]=m.useState(null),[b,w]=m.useState(""),[E,j]=m.useState(!1);m.useEffect(()=>{Se.get("/api/admin/setup/status").then(M=>v(!M.masterKeyConfigured)).catch(()=>v(!0))},[]);const C=!g||c.trim().length>=32,N=!f&&l.length>=12&&C;return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:o.jsxs(nt,{className:"w-full max-w-md",children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("img",{src:"/logo.png",alt:"LateDev Router",className:"h-8 w-8 object-contain rounded"}),o.jsx(rt,{children:"Welcome to LateDev Router"})]}),o.jsx(gn,{children:"Set up the administrator account to get started."})]}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Username"}),o.jsx(Ae,{value:n,onChange:M=>a(M.target.value)})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Password (12+ chars)"}),o.jsx(Ae,{type:"password",value:l,onChange:M=>s(M.target.value)})]}),g&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Master encryption key (required, 32+ chars)"}),o.jsx(Ae,{type:"password",value:c,onChange:M=>u(M.target.value),placeholder:"Paste or generate a 32+ character key"}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Provider API keys are encrypted with this key (AES-256-GCM). Store it somewhere safe — if it is lost, stored provider credentials cannot be recovered. Generate one with:"," ",o.jsx("code",{className:"break-all",children:`node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"`})]})]})]}),o.jsxs(jw,{className:"flex-col items-stretch gap-4",children:[o.jsx(me,{disabled:!N,onClick:async()=>{p(!0);try{await Se.post("/api/admin/setup",{username:n,password:l,setupMasterKey:g?c.trim():void 0}),ve.success("Admin account created"),window.location.assign("/login")}catch(M){ve.error(M.message)}finally{p(!1)}},children:"Create admin"}),o.jsxs("div",{className:"border-t pt-4 space-y-2",children:[o.jsx(we,{children:"Import existing database"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Use this to restore the administrator account, password, TOTP settings, providers, models, and master key from a backup without setting up again. Enter the same 6-digit backup passphrase used when the file was created."}),o.jsx(Ae,{type:"file",accept:".json,application/json",onChange:M=>{var T;return y(((T=M.target.files)==null?void 0:T[0])??null)}}),o.jsx(Ae,{inputMode:"numeric",maxLength:6,value:b,onChange:M=>w(M.target.value.replace(/\D/g,"")),placeholder:"Backup passphrase (6 digits)"}),o.jsx(me,{variant:"outline",disabled:!x||b.length!==6||E,onClick:async()=>{var M,T;if(x){j(!0);try{const D=JSON.parse(await x.text()),O=await fetch("/api/admin/backup/restore",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({backup:D,passphrase:b})});if(!O.ok)throw new Error(((T=(M=await O.json())==null?void 0:M.error)==null?void 0:T.message)??"Import failed");ve.success("Database imported"),window.location.assign("/login")}catch(D){ve.error(D.message)}finally{j(!1)}}},children:"Import database"})]})]})]})})}function $a({title:n,description:a,actions:l,className:s}){return o.jsxs("div",{className:Ee("mb-6 flex items-start justify-between gap-4",s),children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:n}),a&&o.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:a})]}),l&&o.jsx("div",{className:"flex items-center gap-2",children:l})]})}const BD=K0("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive text-destructive-foreground",success:"border-transparent bg-emerald-600 text-white",warning:"border-transparent bg-amber-500 text-white",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Qe({className:n,variant:a,...l}){return o.jsx("div",{className:Ee(BD({variant:a}),n),...l})}const Oh=n=>n==="ready"||n==="healthy"?"success":n==="disabled"?"secondary":"destructive";function HD(){const[n,a]=m.useState(null);return m.useEffect(()=>{Se.get("/api/admin/dashboard").then(a).catch(()=>a(null))},[]),n?o.jsxs("div",{children:[o.jsx($a,{title:"Dashboard",description:"Operational summary for today",actions:o.jsxs("div",{className:"flex gap-2",children:[o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/providers",children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," Provider"]})}),o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/combos",children:[o.jsx(T0,{className:"mr-1 h-4 w-4"})," Combo"]})}),o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/api-keys",children:[o.jsx(N0,{className:"mr-1 h-4 w-4"})," API Key"]})})]})}),o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Requests today"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.total)})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Success rate"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:n.today.total?Eu(n.today.success/n.today.total):"—"})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Failed"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.failed)})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Tokens today"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.totalTokens)})]})]}),o.jsxs("div",{className:"mt-6 grid gap-4 lg:grid-cols-2",children:[o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Provider health"}),o.jsxs(gn,{children:[n.providers.length," configured"]})]}),o.jsxs(lt,{className:"space-y-2",children:[n.providers.length===0&&o.jsxs("p",{className:"text-sm text-muted-foreground",children:["No providers yet. ",o.jsx(ra,{to:"/providers",className:"text-primary",children:"Add one"}),"."]}),n.providers.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(M0,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx(ra,{className:"truncate font-medium text-primary hover:underline",to:`/providers?providerId=${encodeURIComponent(l.id)}`,children:l.name}),o.jsx("span",{className:"hidden text-xs text-muted-foreground sm:inline",children:l.slug}),o.jsx(Qe,{variant:"outline",className:"ml-2",children:l.type})]}),o.jsx(Qe,{variant:Oh(l.health),children:l.health})]},l.id))]})]}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Recent failures"}),o.jsx(gn,{children:"Today"})]}),o.jsxs(lt,{className:"space-y-1 text-sm",children:[n.recentFailures.length===0&&o.jsx("p",{className:"text-muted-foreground",children:"No failures today."}),n.recentFailures.map(l=>{var s;return o.jsxs("div",{className:"flex items-center justify-between border-b py-1 last:border-0",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-mono text-xs",children:l.requestedModel}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.errorType??`HTTP ${l.httpStatus}`," — ",(s=l.errorMessage)==null?void 0:s.slice(0,60)]})]}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Lm(l.createdAt)})]},l.id)})]})]})]}),o.jsxs(nt,{className:"mt-6",children:[o.jsxs(at,{children:[o.jsxs(rt,{className:"flex items-center gap-2 text-base",children:[o.jsx(km,{className:"h-4 w-4"})," Health center"]}),o.jsx(gn,{children:"Passive status from recent traffic; no active provider polling."})]}),o.jsxs(lt,{className:"grid gap-4 lg:grid-cols-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Combos"}),o.jsx("div",{className:"space-y-2",children:n.combos.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No combos configured."}):n.combos.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ra,{className:"font-mono text-xs text-primary hover:underline",to:"/combos",children:l.publicModelId}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.readyMembers,"/",l.memberCount," members ready",l.reasons.length>0?` · ${l.reasons.join(", ")}`:""]})]}),o.jsx(Qe,{variant:Oh(l.state),children:l.state})]},l.id))})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Models"}),o.jsx("div",{className:"max-h-64 space-y-2 overflow-auto",children:n.models.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No models imported."}):n.models.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ra,{className:"font-mono text-xs text-primary hover:underline",to:`/models?providerId=${encodeURIComponent(l.providerId)}`,children:l.publicModelId}),o.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[l.providerName??"Unknown provider",l.lastFailureReason?` · last: ${l.lastFailureReason}`:""]})]}),o.jsx(Qe,{variant:Oh(l.state),children:l.state})]},l.id))})]})]})]})]}):o.jsx("div",{className:"text-muted-foreground",children:"Loading…"})}const ca=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{className:"relative w-full overflow-auto",children:o.jsx("table",{ref:l,className:Ee("w-full caption-bottom text-sm",n),...a})}));ca.displayName="Table";const ua=m.forwardRef(({className:n,...a},l)=>o.jsx("thead",{ref:l,className:Ee("[&_tr]:border-b",n),...a}));ua.displayName="TableHeader";const da=m.forwardRef(({className:n,...a},l)=>o.jsx("tbody",{ref:l,className:Ee("[&_tr:last-child]:border-0",n),...a}));da.displayName="TableBody";const We=m.forwardRef(({className:n,...a},l)=>o.jsx("tr",{ref:l,className:Ee("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",n),...a}));We.displayName="TableRow";const ye=m.forwardRef(({className:n,...a},l)=>o.jsx("th",{ref:l,className:Ee("h-10 px-2 text-left align-middle font-medium text-muted-foreground",n),...a}));ye.displayName="TableHead";const pe=m.forwardRef(({className:n,...a},l)=>o.jsx("td",{ref:l,className:Ee("p-2 align-middle",n),...a}));pe.displayName="TableCell";var ID=Object.defineProperty,Yn=(n,a)=>ID(n,"name",{value:a,configurable:!0}),rp="Dialog",[Cw,Ew]=kn(rp),[PD,Na]=Cw(rp),Rw=Yn(n=>{const{__scopeDialog:a,children:l,open:s,defaultOpen:c,onOpenChange:u,modal:f=!0}=n,p=m.useRef(null),g=m.useRef(null),[v,x]=yr({prop:s,defaultProp:c??!1,onChange:u,caller:rp}),[y,b]=m.useState(0),[w,E]=m.useState(0);return o.jsx(PD,{scope:a,triggerRef:p,contentRef:g,contentId:La(),titleId:La(),descriptionId:La(),titlePresent:y>0,descriptionPresent:w>0,setTitleCount:b,setDescriptionCount:E,open:v,onOpenChange:x,onOpenToggle:m.useCallback(()=>x(j=>!j),[x]),modal:f,children:l})},"Dialog"),qD="DialogTrigger",Nw=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(qD,s),f=Xe(l,u.triggerRef);return o.jsx(Ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":u.open,"aria-controls":u.open?u.contentId:void 0,"data-state":Iu(u.open),...c,ref:f,onClick:Ne(a.onClick,u.onOpenToggle)})},"DialogTrigger")),Tw="DialogPortal",[VD,Mw]=Cw(Tw,{forceMount:void 0}),Aw=Yn(n=>{const{__scopeDialog:a,forceMount:l,children:s,container:c}=n,u=Na(Tw,a);return o.jsx(VD,{scope:a,forceMount:l,children:m.Children.map(s,f=>o.jsx(Cr,{present:l||u.open,children:o.jsx(Zm,{asChild:!0,container:c,children:f})}))})},"DialogPortal"),om="DialogOverlay",lp=m.forwardRef(Yn(function(a,l){const s=Mw(om,a.__scopeDialog),{forceMount:c=s.forceMount,...u}=a,f=Na(om,a.__scopeDialog);return f.modal?o.jsx(Cr,{present:c||f.open,children:o.jsx(YD,{...u,ref:l})}):null},"DialogOverlay")),$D=Ha("DialogOverlay.RemoveScroll"),YD=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(om,s),f=o1(),p=Xe(l,f);return o.jsx(Bu,{as:$D,allowPinchZoom:!0,shards:[u.contentRef],children:o.jsx(Ve.div,{"data-state":Iu(u.open),...c,ref:p,style:{pointerEvents:"auto",...c.style}})})},"DialogOverlayImpl")),ei="DialogContent",sp=m.forwardRef(Yn(function(a,l){const s=Mw(ei,a.__scopeDialog),{forceMount:c=s.forceMount,...u}=a,f=Na(ei,a.__scopeDialog);return o.jsx(Cr,{present:c||f.open,children:f.modal?o.jsx(GD,{...u,ref:l}):o.jsx(KD,{...u,ref:l})})},"DialogContent")),GD=m.forwardRef(Yn(function(a,l){const s=Na(ei,a.__scopeDialog),c=m.useRef(null),u=Xe(l,s.contentRef,c);return m.useEffect(()=>{const f=c.current;if(f)return ep(f)},[]),o.jsx(Dw,{...a,ref:u,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Ne(a.onCloseAutoFocus,f=>{var p;f.preventDefault(),(p=s.triggerRef.current)==null||p.focus()}),onPointerDownOutside:Ne(a.onPointerDownOutside,f=>{const p=f.detail.originalEvent,g=p.button===0&&p.ctrlKey===!0;(p.button===2||g)&&f.preventDefault()}),onFocusOutside:Ne(a.onFocusOutside,f=>f.preventDefault())})},"DialogContentModal")),KD=m.forwardRef(Yn(function(a,l){const s=Na(ei,a.__scopeDialog),c=m.useRef(!1),u=m.useRef(!1);return o.jsx(Dw,{...a,ref:l,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:f=>{var p,g;(p=a.onCloseAutoFocus)==null||p.call(a,f),f.defaultPrevented||(c.current||(g=s.triggerRef.current)==null||g.focus(),f.preventDefault()),c.current=!1,u.current=!1},onInteractOutside:f=>{var v,x;(v=a.onInteractOutside)==null||v.call(a,f),f.defaultPrevented||(c.current=!0,f.detail.originalEvent.type==="pointerdown"&&(u.current=!0));const p=f.target;((x=s.triggerRef.current)==null?void 0:x.contains(p))&&f.preventDefault(),f.detail.originalEvent.type==="focusin"&&u.current&&f.preventDefault()}})},"DialogContentNonModal")),Dw=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,trapFocus:c,onOpenAutoFocus:u,onCloseAutoFocus:f,...p}=a,g=Na(ei,s);return fi(),o.jsx(o.Fragment,{children:o.jsx(qm,{asChild:!0,loop:!0,trapped:c,onMountAutoFocus:u,onUnmountAutoFocus:f,children:o.jsx(Nu,{role:"dialog",id:g.contentId,"aria-describedby":g.descriptionPresent?g.descriptionId:void 0,"aria-labelledby":g.titlePresent?g.titleId:void 0,"data-state":Iu(g.open),...p,ref:l,deferPointerDownOutside:!0,onDismiss:()=>g.onOpenChange(!1)})})})},"DialogContentImpl")),XD="DialogTitle",op=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(XD,s),{setTitleCount:f}=u;return Xt(()=>(f(p=>p+1),()=>f(p=>p-1)),[f]),o.jsx(Ve.h2,{id:u.titleId,...c,ref:l})},"DialogTitle")),FD="DialogDescription",ip=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(FD,s),{setDescriptionCount:f}=u;return Xt(()=>(f(p=>p+1),()=>f(p=>p-1)),[f]),o.jsx(Ve.p,{id:u.descriptionId,...c,ref:l})},"DialogDescription")),QD="DialogClose",cp=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(QD,s);return o.jsx(Ve.button,{type:"button",...c,ref:l,onClick:Ne(a.onClick,()=>u.onOpenChange(!1))})},"DialogClose"));function Iu(n){return n?"open":"closed"}Yn(Iu,"getState");const Mn=Rw,mi=Nw,ZD=Aw,Ow=m.forwardRef(({className:n,...a},l)=>o.jsx(lp,{ref:l,className:Ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...a}));Ow.displayName=lp.displayName;const vn=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(ZD,{children:[o.jsx(Ow,{}),o.jsxs(sp,{ref:s,className:Ee("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 sm:rounded-lg",n),...l,children:[a,o.jsxs(cp,{className:"absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100",children:[o.jsx(Cu,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vn.displayName=sp.displayName;const xn=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col space-y-1.5 text-center sm:text-left",n),...a});xn.displayName="DialogHeader";const An=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...a});An.displayName="DialogFooter";const yn=m.forwardRef(({className:n,...a},l)=>o.jsx(op,{ref:l,className:Ee("text-lg font-semibold leading-none tracking-tight",n),...a}));yn.displayName=op.displayName;const uu=m.forwardRef(({className:n,...a},l)=>o.jsx(ip,{ref:l,className:Ee("text-sm text-muted-foreground",n),...a}));uu.displayName=ip.displayName;var JD=Object.defineProperty,Er=(n,a)=>JD(n,"name",{value:a,configurable:!0}),WD="AlertDialog",[eO,Y4]=kn(WD,[Ew]),Rr=Ew(),tO=Er(n=>{const{__scopeAlertDialog:a,...l}=n,s=Rr(a);return o.jsx(Rw,{...s,...l,modal:!0})},"AlertDialog"),nO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(Nw,{...u,...c,ref:l})},"AlertDialogTrigger")),aO=Er(n=>{const{__scopeAlertDialog:a,...l}=n,s=Rr(a);return o.jsx(Aw,{...s,...l})},"AlertDialogPortal"),rO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(lp,{...u,...c,ref:l})},"AlertDialogOverlay")),lO="AlertDialogContent",[sO,oO]=eO(lO),iO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,children:c,...u}=a,f=Rr(s),p=m.useRef(null),g=Xe(l,p),v=m.useRef(null);return o.jsx(sO,{scope:s,cancelRef:v,children:o.jsx(sp,{role:"alertdialog",...f,...u,ref:g,onOpenAutoFocus:Ne(u.onOpenAutoFocus,x=>{var y;x.preventDefault(),(y=v.current)==null||y.focus({preventScroll:!0})}),onPointerDownOutside:x=>x.preventDefault(),onInteractOutside:x=>x.preventDefault(),children:c})})},"AlertDialogContent")),cO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(op,{...u,...c,ref:l})},"AlertDialogTitle")),uO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(ip,{...u,...c,ref:l})},"AlertDialogDescription")),dO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(cp,{...u,...c,ref:l})},"AlertDialogAction")),fO="AlertDialogCancel",hO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,{cancelRef:u}=oO(fO,s),f=Rr(s),p=Xe(l,u);return o.jsx(cp,{...f,...c,ref:p})},"AlertDialogCancel")),mO=tO,pO=nO,gO=aO,_w=rO,kw=iO,zw=dO,Lw=hO,Uw=cO,Bw=uO;const up=mO,vO=pO,xO=gO,Hw=m.forwardRef(({className:n,...a},l)=>o.jsx(_w,{ref:l,className:Ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...a}));Hw.displayName=_w.displayName;const Pu=m.forwardRef(({className:n,...a},l)=>o.jsxs(xO,{children:[o.jsx(Hw,{}),o.jsx(kw,{ref:l,className:Ee("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg sm:max-w-[425px]",n),...a})]}));Pu.displayName=kw.displayName;const dp=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col space-y-2 text-center sm:text-left",n),...a}),fp=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...a}),qu=m.forwardRef(({className:n,...a},l)=>o.jsx(Uw,{ref:l,className:Ee("text-lg font-semibold",n),...a}));qu.displayName=Uw.displayName;const Vu=m.forwardRef(({className:n,...a},l)=>o.jsx(Bw,{ref:l,className:Ee("text-sm text-muted-foreground",n),...a}));Vu.displayName=Bw.displayName;const $u=m.forwardRef(({className:n,...a},l)=>o.jsx(zw,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",n),...a}));$u.displayName=zw.displayName;const Yu=m.forwardRef(({className:n,...a},l)=>o.jsx(Lw,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium hover:bg-accent",n),...a}));Yu.displayName=Lw.displayName;var yO=Object.defineProperty,bO=(n,a)=>yO(n,"name",{value:a,configurable:!0});function im(n,[a,l]){return Math.min(l,Math.max(a,n))}bO(im,"clamp");var wO=Object.defineProperty,SO=(n,a)=>wO(n,"name",{value:a,configurable:!0});function Iw(n){const a=m.useRef({value:n,previous:n});return m.useMemo(()=>(a.current.value!==n&&(a.current.previous=a.current.value,a.current.value=n),a.current.previous),[n])}SO(Iw,"usePrevious");var jO=Object.defineProperty,CO=(n,a)=>jO(n,"name",{value:a,configurable:!0}),Pw=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),EO=m.forwardRef(CO(function(a,l){return o.jsx(Ve.span,{...a,ref:l,style:{...Pw,...a.style}})},"VisuallyHidden")),RO=EO,NO=Object.defineProperty,ht=(n,a)=>NO(n,"name",{value:a,configurable:!0}),TO=[" ","Enter","ArrowUp","ArrowDown"],MO=[" ","Enter"],Bs="Select",[Gu,hp,AO]=Ru(Bs),[Il,G4]=kn(Bs,[AO,Ks]),mp=Ks(),[DO,ul]=Il(Bs),[OO,_O]=Il(Bs);function qw(n){const{__scopeSelect:a,children:l,open:s,defaultOpen:c,onOpenChange:u,value:f,defaultValue:p,onValueChange:g,dir:v,name:x,autoComplete:y,disabled:b,required:w,form:E,internal_do_not_use_render:j}=n,C=mp(a),[N,M]=m.useState(null),[T,D]=m.useState(null),[O,A]=m.useState(!1),U=di(v),[k,$]=yr({prop:s,defaultProp:c??!1,onChange:u,caller:Bs}),[X,te]=yr({prop:f,defaultProp:p,onChange:g,caller:Bs}),G=m.useRef(null),ie=m.useRef(X);m.useEffect(()=>{const I=E?N==null?void 0:N.ownerDocument.getElementById(E):N==null?void 0:N.form;if(I instanceof HTMLFormElement){const F=ht(()=>te(ie.current),"reset");return I.addEventListener("reset",F),()=>I.removeEventListener("reset",F)}},[E,N,te]);const ce=N?!!E||!!N.closest("form"):!0,[se,_]=m.useState(new Set),H=La(),Q=Array.from(se).map(I=>I.props.value).join(";"),J=m.useCallback(I=>{_(F=>new Set(F).add(I))},[]),ee=m.useCallback(I=>{_(F=>{const re=new Set(F);return re.delete(I),re})},[]),z={required:w,trigger:N,onTriggerChange:M,valueNode:T,onValueNodeChange:D,valueNodeHasChildren:O,onValueNodeHasChildrenChange:A,contentId:H,value:X,onValueChange:te,open:k,onOpenChange:$,dir:U,triggerPointerDownPosRef:G,disabled:b,name:x,autoComplete:y,form:E,nativeOptions:se,nativeSelectKey:Q,isFormControl:ce};return o.jsx(O1,{...C,children:o.jsx(DO,{scope:a,...z,children:o.jsx(Gu.Provider,{scope:a,children:o.jsx(OO,{scope:a,onNativeOptionAdd:J,onNativeOptionRemove:ee,children:Xw(j)?j(z):l})})})})}ht(qw,"SelectProvider");var kO=ht(n=>{const{__scopeSelect:a,children:l,...s}=n;return o.jsx(qw,{__scopeSelect:a,...s,internal_do_not_use_render:({isFormControl:c})=>o.jsxs(o.Fragment,{children:[l,c?o.jsx(n_,{__scopeSelect:a}):null]})})},"Select"),zO="SelectTrigger",Vw=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,disabled:c=!1,...u}=a,f=mp(s),p=ul(zO,s),g=p.disabled||c,v=Xe(l,p.onTriggerChange),x=hp(s),y=m.useRef("touch"),[b,w,E]=pp(C=>{const N=x().filter(D=>!D.disabled),M=N.find(D=>D.value===p.value),T=gp(N,C,M);T!==void 0&&p.onValueChange(T.value)}),j=ht(C=>{g||(p.onOpenChange(!0),E()),C&&(p.triggerPointerDownPosRef.current={x:Math.round(C.pageX),y:Math.round(C.pageY)})},"handleOpen");return o.jsx(_1,{asChild:!0,...f,children:o.jsx(Ve.button,{type:"button",role:"combobox","aria-controls":p.open?p.contentId:void 0,"aria-expanded":p.open,"aria-required":p.required,"aria-autocomplete":"none",dir:p.dir,"data-state":p.open?"open":"closed",disabled:g,"data-disabled":g?"":void 0,"data-placeholder":pi(p.value)?"":void 0,...u,ref:v,onClick:Ne(u.onClick,C=>{C.currentTarget.focus(),y.current!=="mouse"&&j(C)}),onPointerDown:Ne(u.onPointerDown,C=>{y.current=C.pointerType;const N=C.target;N.hasPointerCapture(C.pointerId)&&N.releasePointerCapture(C.pointerId),C.button===0&&C.ctrlKey===!1&&C.pointerType==="mouse"&&(j(C),C.preventDefault())}),onKeyDown:Ne(u.onKeyDown,C=>{const N=b.current!=="";!(C.ctrlKey||C.altKey||C.metaKey)&&C.key.length===1&&w(C.key),!(N&&C.key===" ")&&TO.includes(C.key)&&(j(),C.preventDefault())})})})},"SelectTrigger")),LO="SelectValue",UO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,className:c,style:u,children:f,placeholder:p="",...g}=a,v=ul(LO,s),{onValueNodeHasChildrenChange:x}=v,y=f!==void 0,b=Xe(l,v.onValueNodeChange);Xt(()=>{x(y)},[x,y]);const w=pi(v.value);return o.jsx(Ve.span,{...g,asChild:w?!1:g.asChild,ref:b,style:{pointerEvents:"none"},children:o.jsx(m.Fragment,{children:w?p:f},w?"placeholder":"value")})},"SelectValue")),BO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,children:c,...u}=a;return o.jsx(Ve.span,{"aria-hidden":!0,...u,ref:l,children:c||"▼"})},"SelectIcon")),HO="SelectPortal",[IO,PO]=Il(HO,{forceMount:void 0}),qO=ht(n=>{const{__scopeSelect:a,forceMount:l,...s}=n;return o.jsx(IO,{scope:n.__scopeSelect,forceMount:l,children:o.jsx(Zm,{asChild:!0,...s})})},"SelectPortal"),zl="SelectContent",$w=m.forwardRef(ht(function(a,l){const s=PO(zl,a.__scopeSelect),{forceMount:c=s.forceMount,...u}=a,f=ul(zl,a.__scopeSelect),[p,g]=m.useState();return Xt(()=>{g(new DocumentFragment)},[]),o.jsx(Cr,{present:c||f.open,children:({present:v})=>v?o.jsx(YO,{...u,ref:l}):o.jsx(VO,{...u,fragment:p})})},"SelectContent")),VO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,children:c,fragment:u}=a;return u?ba.createPortal(o.jsx(Yw,{scope:s,children:o.jsx(Gu.Slot,{scope:s,children:o.jsx("div",{ref:l,children:c})})}),u):null},"SelectContentFragment")),ya=10,[Yw,Ku]=Il(zl),$O=Ha("SelectContent.RemoveScroll"),YO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s}=a,{position:c="item-aligned",onCloseAutoFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,side:g,sideOffset:v,align:x,alignOffset:y,arrowPadding:b,collisionBoundary:w,collisionPadding:E,sticky:j,hideWhenDetached:C,avoidCollisions:N,...M}=a,T=ul(zl,s),[D,O]=m.useState(null),[A,U]=m.useState(null),k=Xe(l,O),[$,X]=m.useState(null),[te,G]=m.useState(null),ie=hp(s),[ce,se]=m.useState(!1),_=m.useRef(!1);m.useEffect(()=>{if(D)return ep(D)},[D]),fi();const H=m.useCallback(oe=>{const[de,...fe]=ie().map(De=>De.ref.current),[Te]=fe.slice(-1),je=document.activeElement;for(const De of oe)if(De===je||(De==null||De.scrollIntoView({block:"nearest"}),De===de&&A&&(A.scrollTop=0),De===Te&&A&&(A.scrollTop=A.scrollHeight),De==null||De.focus(),document.activeElement!==je))return},[ie,A]),Q=m.useCallback(()=>H([$,D]),[H,$,D]);m.useEffect(()=>{ce&&Q()},[ce,Q]);const{onOpenChange:J,triggerPointerDownPosRef:ee}=T;m.useEffect(()=>{if(D){let oe={x:0,y:0};const de=ht(Te=>{var je,De;oe={x:Math.abs(Math.round(Te.pageX)-(((je=ee.current)==null?void 0:je.x)??0)),y:Math.abs(Math.round(Te.pageY)-(((De=ee.current)==null?void 0:De.y)??0))}},"handlePointerMove"),fe=ht(Te=>{oe.x<=10&&oe.y<=10?Te.preventDefault():Te.composedPath().includes(D)||J(!1),document.removeEventListener("pointermove",de),ee.current=null},"handlePointerUp");return ee.current!==null&&(document.addEventListener("pointermove",de),document.addEventListener("pointerup",fe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",de),document.removeEventListener("pointerup",fe,{capture:!0})}}},[D,J,ee]),m.useEffect(()=>{const oe=ht(()=>J(!1),"close");return window.addEventListener("blur",oe),window.addEventListener("resize",oe),()=>{window.removeEventListener("blur",oe),window.removeEventListener("resize",oe)}},[J]);const[z,I]=pp(oe=>{const de=ie().filter(je=>!je.disabled),fe=de.find(je=>je.ref.current===document.activeElement),Te=gp(de,oe,fe);Te&&setTimeout(()=>{var je;return(je=Te.ref.current)==null?void 0:je.focus()})}),F=m.useCallback((oe,de,fe)=>{const Te=!_.current&&!fe;(T.value!==void 0&&T.value===de||Te)&&(X(oe),Te&&(_.current=!0))},[T.value]),re=m.useCallback(()=>D==null?void 0:D.focus(),[D]),he=m.useCallback((oe,de,fe)=>{const Te=!_.current&&!fe;(T.value!==void 0&&T.value===de||Te)&&G(oe)},[T.value]),ge=c==="popper"?Rb:GO,q=ge===Rb?{side:g,sideOffset:v,align:x,alignOffset:y,arrowPadding:b,collisionBoundary:w,collisionPadding:E,sticky:j,hideWhenDetached:C,avoidCollisions:N}:{};return o.jsx(Yw,{scope:s,content:D,viewport:A,onViewportChange:U,itemRefCallback:F,selectedItem:$,onItemLeave:re,itemTextRefCallback:he,focusSelectedItem:Q,selectedItemText:te,position:c,isPositioned:ce,searchRef:z,children:o.jsx(Bu,{as:$O,allowPinchZoom:!0,children:o.jsx(qm,{asChild:!0,trapped:T.open,onMountAutoFocus:oe=>{oe.preventDefault()},onUnmountAutoFocus:Ne(u,oe=>{var de;(de=T.trigger)==null||de.focus({preventScroll:!0}),oe.preventDefault()}),children:o.jsx(Nu,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:oe=>oe.preventDefault(),onDismiss:()=>T.onOpenChange(!1),children:o.jsx(ge,{role:"listbox",id:T.contentId,"data-state":T.open?"open":"closed",dir:T.dir,onContextMenu:oe=>oe.preventDefault(),...M,...q,onPlaced:()=>se(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...M.style},onKeyDown:Ne(M.onKeyDown,oe=>{const de=oe.ctrlKey||oe.altKey||oe.metaKey;if(oe.key==="Tab"&&oe.preventDefault(),!de&&oe.key.length===1&&I(oe.key),["ArrowUp","ArrowDown","Home","End"].includes(oe.key)){let Te=ie().filter(je=>!je.disabled).map(je=>je.ref.current);if(["ArrowUp","End"].includes(oe.key)&&(Te=Te.slice().reverse()),["ArrowUp","ArrowDown"].includes(oe.key)){const je=oe.target,De=Te.indexOf(je);Te=Te.slice(De+1)}setTimeout(()=>H(Te)),oe.preventDefault()}})})})})})})},"SelectContentImpl")),GO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,onPlaced:c,...u}=a,f=ul(zl,s),p=Ku(zl,s),[g,v]=m.useState(null),[x,y]=m.useState(null),b=Xe(l,y),w=hp(s),E=m.useRef(!1),j=m.useRef(!0),{viewport:C,selectedItem:N,selectedItemText:M,focusSelectedItem:T}=p,D=m.useCallback(()=>{if(f.trigger&&f.valueNode&&g&&x&&C&&N&&M){const k=f.trigger.getBoundingClientRect(),$=x.getBoundingClientRect(),X=f.valueNode.getBoundingClientRect(),te=M.getBoundingClientRect();if(f.dir!=="rtl"){const je=te.left-$.left,De=X.left-je,Fe=k.left-De,et=k.width+Fe,le=Math.max(et,$.width),Le=window.innerWidth-ya,Ie=im(De,[ya,Math.max(ya,Le-le)]);g.style.minWidth=et+"px",g.style.left=Ie+"px"}else{const je=$.right-te.right,De=window.innerWidth-X.right-je,Fe=window.innerWidth-k.right-De,et=k.width+Fe,le=Math.max(et,$.width),Le=window.innerWidth-ya,Ie=im(De,[ya,Math.max(ya,Le-le)]);g.style.minWidth=et+"px",g.style.right=Ie+"px"}const G=w(),ie=window.innerHeight-ya*2,ce=C.scrollHeight,se=window.getComputedStyle(x),_=parseInt(se.borderTopWidth,10),H=parseInt(se.paddingTop,10),Q=parseInt(se.borderBottomWidth,10),J=parseInt(se.paddingBottom,10),ee=_+H+ce+J+Q,z=Math.min(N.offsetHeight*5,ee),I=window.getComputedStyle(C),F=parseInt(I.paddingTop,10),re=parseInt(I.paddingBottom,10),he=k.top+k.height/2-ya,ge=ie-he,q=N.offsetHeight/2,oe=N.offsetTop+q,de=_+H+oe,fe=ee-de;if(de<=he){const je=G.length>0&&N===G[G.length-1].ref.current;g.style.bottom="0px";const De=x.clientHeight-C.offsetTop-C.offsetHeight,Fe=Math.max(ge,q+(je?re:0)+De+Q),et=de+Fe;g.style.height=et+"px"}else{const je=G.length>0&&N===G[0].ref.current;g.style.top="0px";const Fe=Math.max(he,_+C.offsetTop+(je?F:0)+q)+fe;g.style.height=Fe+"px",C.scrollTop=de-he+C.offsetTop}g.style.margin=`${ya}px 0`,g.style.minHeight=z+"px",g.style.maxHeight=ie+"px",c==null||c(),requestAnimationFrame(()=>E.current=!0)}},[w,f.trigger,f.valueNode,g,x,C,N,M,f.dir,c]);Xt(()=>D(),[D]);const[O,A]=m.useState();Xt(()=>{x&&A(window.getComputedStyle(x).zIndex)},[x]);const U=m.useCallback(k=>{k&&j.current===!0&&(D(),T==null||T(),j.current=!1)},[D,T]);return o.jsx(KO,{scope:s,contentWrapper:g,shouldExpandOnScrollRef:E,onScrollButtonChange:U,children:o.jsx("div",{ref:v,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:O},children:o.jsx(Ve.div,{...u,ref:b,style:{boxSizing:"border-box",maxHeight:"100%",...u.style}})})})},"SelectItemAlignedPosition")),Rb=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,align:c="start",collisionPadding:u=ya,...f}=a,p=mp(s);return o.jsx(Qm,{...p,...f,ref:l,align:c,collisionPadding:u,style:{boxSizing:"border-box",...f.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[KO,XO]=Il(zl,{}),Nb="SelectViewport",FO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,nonce:c,...u}=a,f=Ku(Nb,s),p=XO(Nb,s),g=Xe(l,f.onViewportChange),v=m.useRef(0);return o.jsxs(o.Fragment,{children:[o.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:c}),o.jsx(Gu.Slot,{scope:s,children:o.jsx(Ve.div,{"data-radix-select-viewport":"",role:"presentation",...u,ref:g,style:{position:"relative",flex:1,overflow:"hidden auto",...u.style},onScroll:Ne(u.onScroll,x=>{const y=x.currentTarget,{contentWrapper:b,shouldExpandOnScrollRef:w}=p;if(w!=null&&w.current&&b){const E=Math.abs(v.current-y.scrollTop);if(E>0){const j=window.innerHeight-ya*2,C=parseFloat(b.style.minHeight),N=parseFloat(b.style.height),M=Math.max(C,N);if(M<j){const T=M+E,D=Math.min(j,T),O=T-D;b.style.height=D+"px",b.style.bottom==="0px"&&(y.scrollTop=O>0?O:0,b.style.justifyContent="flex-end")}}}v.current=y.scrollTop})})})]})},"SelectViewport")),QO="SelectGroup",[K4,X4]=Il(QO),cm="SelectItem",[ZO,Gw]=Il(cm),Kw=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,value:c,disabled:u=!1,textValue:f,...p}=a,g=ul(cm,s),v=Ku(cm,s),x=g.value===c,[y,b]=m.useState(f??""),[w,E]=m.useState(!1),j=ia(D=>{var O;return(O=v.itemRefCallback)==null?void 0:O.call(v,D,c,u)}),C=Xe(l,j),N=La(),M=m.useRef("touch"),T=ht(()=>{u||(g.onValueChange(c),g.onOpenChange(!1))},"handleSelect");return o.jsx(ZO,{scope:s,value:c,disabled:u,textId:N,isSelected:x,onItemTextChange:m.useCallback(D=>{b(O=>O||((D==null?void 0:D.textContent)??"").trim())},[]),children:o.jsx(Gu.ItemSlot,{scope:s,value:c,disabled:u,textValue:y,children:o.jsx(Ve.div,{role:"option","aria-labelledby":N,"data-highlighted":w?"":void 0,"aria-selected":x&&w,"data-state":x?"checked":"unchecked","aria-disabled":u||void 0,"data-disabled":u?"":void 0,tabIndex:u?void 0:-1,...p,ref:C,onFocus:Ne(p.onFocus,()=>E(!0)),onBlur:Ne(p.onBlur,()=>E(!1)),onClick:Ne(p.onClick,()=>{M.current!=="mouse"&&T()}),onPointerUp:Ne(p.onPointerUp,()=>{M.current==="mouse"&&T()}),onPointerDown:Ne(p.onPointerDown,D=>{M.current=D.pointerType}),onPointerMove:Ne(p.onPointerMove,D=>{var O;M.current=D.pointerType,u?(O=v.onItemLeave)==null||O.call(v):M.current==="mouse"&&D.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ne(p.onPointerLeave,D=>{var O;D.currentTarget===document.activeElement&&((O=v.onItemLeave)==null||O.call(v))}),onKeyDown:Ne(p.onKeyDown,D=>{var A;u||D.target!==D.currentTarget||((A=v.searchRef)==null?void 0:A.current)!==""&&D.key===" "||(MO.includes(D.key)&&T(),D.key===" "&&D.preventDefault())})})})})},"SelectItem")),Ic="SelectItemText",JO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,className:c,style:u,...f}=a,p=ul(Ic,s),g=Ku(Ic,s),v=Gw(Ic,s),x=_O(Ic,s),[y,b]=m.useState(null),w=ia(T=>{var D;return(D=g.itemTextRefCallback)==null?void 0:D.call(g,T,v.value,v.disabled)}),E=Xe(l,b,v.onItemTextChange,w),j=y==null?void 0:y.textContent,C=m.useMemo(()=>o.jsx("option",{value:v.value,disabled:v.disabled,children:j},v.value),[v.disabled,v.value,j]),{onNativeOptionAdd:N,onNativeOptionRemove:M}=x;return Xt(()=>(N(C),()=>M(C)),[N,M,C]),o.jsxs(o.Fragment,{children:[o.jsx(Ve.span,{id:v.textId,...f,ref:E}),v.isSelected&&p.valueNode&&!p.valueNodeHasChildren&&!pi(p.value)?ba.createPortal(f.children,p.valueNode):null]})},"SelectItemText")),WO="SelectItemIndicator",e_=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,...c}=a;return Gw(WO,s).isSelected?o.jsx(Ve.span,{"aria-hidden":!0,...c,ref:l}):null},"SelectItemIndicator")),t_="SelectBubbleInput",n_=m.forwardRef(ht(function({__scopeSelect:a,...l},s){const c=ul(t_,a),{value:u,onValueChange:f,required:p,disabled:g,name:v,autoComplete:x,form:y}=c,{nativeOptions:b,nativeSelectKey:w}=c,E=m.useRef(null),j=Xe(s,E),C=u??"",N=Iw(C),M=Array.from(b).some(T=>(T.props.value??"")==="");return m.useEffect(()=>{const T=E.current;if(!T)return;const D=window.HTMLSelectElement.prototype,A=Object.getOwnPropertyDescriptor(D,"value").set;if(N!==C&&A){const U=new Event("change",{bubbles:!0});A.call(T,C),T.dispatchEvent(U)}},[N,C]),o.jsxs(Ve.select,{"aria-hidden":!0,required:p,tabIndex:-1,name:v,autoComplete:x,disabled:g,form:y,onChange:T=>f(T.target.value),...l,style:{...Pw,...l.style},ref:j,defaultValue:C,children:[pi(u)&&!M?o.jsx("option",{value:""}):null,Array.from(b)]},w)},"SelectBubbleInput"));function Xw(n){return typeof n=="function"}ht(Xw,"isFunction");function pi(n){return n===""||n===void 0}ht(pi,"shouldShowPlaceholder");function pp(n){const a=ia(n),l=m.useRef(""),s=m.useRef(0),c=m.useCallback(f=>{const p=l.current+f;a(p),ht((function g(v){l.current=v,window.clearTimeout(s.current),v!==""&&(s.current=window.setTimeout(()=>g(""),1e3))}),"updateSearch")(p)},[a]),u=m.useCallback(()=>{l.current="",window.clearTimeout(s.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(s.current),[]),[l,c,u]}ht(pp,"useTypeaheadSearch");function gp(n,a,l){const c=a.length>1&&Array.from(a).every(v=>v===a[0])?a[0]:a,u=l?n.indexOf(l):-1;let f=Fw(n,Math.max(u,0));c.length===1&&(f=f.filter(v=>v!==l));const g=f.find(v=>v.textValue.toLowerCase().startsWith(c.toLowerCase()));return g!==l?g:void 0}ht(gp,"findNextItem");function Fw(n,a){return n.map((l,s)=>n[(a+s)%n.length])}ht(Fw,"wrapArray");const Ua=kO,Ba=UO,Sa=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(Vw,{ref:s,className:Ee("flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",n),...l,children:[a,o.jsx(BO,{asChild:!0,children:o.jsx(JE,{className:"h-4 w-4 opacity-50"})})]}));Sa.displayName=Vw.displayName;const ja=m.forwardRef(({className:n,children:a,position:l="popper",...s},c)=>o.jsx(qO,{children:o.jsx($w,{ref:c,className:Ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md",n),position:l,...s,children:o.jsx(FO,{className:Ee("p-1",l==="popper"&&"w-full min-w-[var(--radix-select-trigger-width)]"),children:a})})}));ja.displayName=$w.displayName;const Rt=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(Kw,{ref:s,className:Ee("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n),...l,children:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(e_,{children:o.jsx(C0,{className:"h-4 w-4"})})}),o.jsx(JO,{children:a})]}));Rt.displayName=Kw.displayName;var a_=Object.defineProperty,il=(n,a)=>a_(n,"name",{value:a,configurable:!0}),vp="Switch",[r_,F4]=kn(vp),[l_,xp]=r_(vp);function Qw(n){const{__scopeSwitch:a,checked:l,children:s,defaultChecked:c,disabled:u,form:f,name:p,onCheckedChange:g,required:v,value:x="on",internal_do_not_use_render:y}=n,[b,w]=yr({prop:l,defaultProp:c??!1,onChange:g,caller:vp}),[E,j]=m.useState(null),[C,N]=m.useState(null),M=m.useRef(!1),[T,D]=m.useReducer(U=>U+1,0),O=E?!!f||!!E.closest("form"):!0,A={checked:b,setChecked:w,disabled:u,control:E,setControl:j,name:p,form:f,value:x,hasConsumerStoppedPropagationRef:M,userInteractionCount:T,onUserInteraction:D,required:v,defaultChecked:c,isFormControl:O,bubbleInput:C,setBubbleInput:N};return o.jsx(l_,{scope:a,...A,children:Jw(y)?y(A):s})}il(Qw,"SwitchProvider");var s_="SwitchTrigger",o_=m.forwardRef(il(function({__scopeSwitch:a,onClick:l,...s},c){const{control:u,form:f,value:p,disabled:g,checked:v,required:x,setControl:y,setChecked:b,hasConsumerStoppedPropagationRef:w,onUserInteraction:E,isFormControl:j,bubbleInput:C}=xp(s_,a),N=Xe(c,y),M=m.useRef(v);return m.useEffect(()=>{const T=f?u==null?void 0:u.ownerDocument.getElementById(f):u==null?void 0:u.form;if(T instanceof HTMLFormElement){const D=il(()=>b(M.current),"reset");return T.addEventListener("reset",D),()=>T.removeEventListener("reset",D)}},[u,f,b]),o.jsx(Ve.button,{type:"button",role:"switch","aria-checked":v,"aria-required":x,"data-state":yp(v),"data-disabled":g?"":void 0,disabled:g,value:p,...s,ref:N,onClick:Ne(l,T=>{E(),b(D=>!D),C&&j&&(w.current=T.isPropagationStopped(),w.current||T.stopPropagation())})})},"SwitchTrigger")),Zw=m.forwardRef(il(function(a,l){const{__scopeSwitch:s,name:c,checked:u,defaultChecked:f,required:p,disabled:g,value:v,onCheckedChange:x,form:y,...b}=a;return o.jsx(Qw,{__scopeSwitch:s,checked:u,defaultChecked:f,disabled:g,required:p,onCheckedChange:x,name:c,form:y,value:v,internal_do_not_use_render:({isFormControl:w})=>o.jsxs(o.Fragment,{children:[o.jsx(o_,{...b,ref:l,__scopeSwitch:s}),w&&o.jsx(d_,{__scopeSwitch:s})]})})},"Switch")),i_="SwitchThumb",c_=m.forwardRef(il(function(a,l){const{__scopeSwitch:s,...c}=a,u=xp(i_,s);return o.jsx(Ve.span,{"data-state":yp(u.checked),"data-disabled":u.disabled?"":void 0,...c,ref:l})},"SwitchThumb")),u_="SwitchBubbleInput",d_=m.forwardRef(il(function({__scopeSwitch:a,onClick:l,...s},c){const{control:u,hasConsumerStoppedPropagationRef:f,userInteractionCount:p,checked:g,defaultChecked:v,required:x,disabled:y,name:b,value:w,form:E,bubbleInput:j,setBubbleInput:C}=xp(u_,a),N=Xe(c,C),M=_u(u),T=m.useRef(!1),D=m.useRef(g),O=m.useRef(p);m.useEffect(()=>{const U=j;if(!U)return;const k=window.HTMLInputElement.prototype,X=Object.getOwnPropertyDescriptor(k,"checked").set,te=p!==O.current;O.current=p;const G=D.current!==g;D.current=g;const ie=!(te&&f.current);if(G&&X){T.current=!te;const ce=new Event("click",{bubbles:ie});X.call(U,g),U.dispatchEvent(ce),T.current=!1}},[j,g,f,p]);const A=m.useRef(g);return o.jsx(Ve.input,{type:"checkbox","aria-hidden":!0,defaultChecked:v??A.current,required:x,disabled:y,name:b,value:w,form:E,...s,tabIndex:-1,ref:N,onClick:Ne(l,U=>{T.current&&U.stopPropagation()}),style:{...s.style,...M,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Jw(n){return typeof n=="function"}il(Jw,"isFunction");function yp(n){return n?"checked":"unchecked"}il(yp,"getState");const Ca=m.forwardRef(({className:n,...a},l)=>o.jsx(Zw,{className:Ee("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",n),...a,ref:l,children:o.jsx(c_,{className:Ee("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Ca.displayName=Zw.displayName;const Al={name:"",slug:"",type:"openai",baseUrl:"https://api.openai.com",apiKey:"",customHeaders:"",enabled:!0},f_={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function h_(){const[n,a]=m.useState([]),[l,s]=m.useState(!1),[c,u]=m.useState(Al),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(Al),[E,j]=m.useState(null),[C,N]=m.useState(!1),M=async()=>{try{const k=await Se.get("/api/admin/providers");a(k.providers)}catch(k){ve.error(k.message||"Unable to load providers")}};m.useEffect(()=>{M()},[]);const T=async()=>{p(!0);try{let k;if(c.customHeaders.trim())try{k=JSON.parse(c.customHeaders)}catch{throw new Error("Custom headers must be valid JSON object")}await Se.post("/api/admin/providers",{name:c.name,slug:c.slug||void 0,type:c.type,baseUrl:c.baseUrl,apiKey:c.apiKey,customHeaders:k,enabled:c.enabled}),ve.success("Provider created"),s(!1),u(Al),M()}catch(k){ve.error(k.message)}finally{p(!1)}},D=async k=>{v(k);try{const $=await Se.post(`/api/admin/providers/${k}/test`);ve.success($.ok?`Connection OK: ${$.detail}`:`Failed: ${$.detail}`),M()}catch($){ve.error($.message)}finally{v(null)}},O=k=>{y(k.id),w({...Al,name:k.name,slug:k.slug||"",type:k.type,baseUrl:k.baseUrl,apiKey:"",customHeaders:"",enabled:k.enabled})},A=async()=>{if(x){p(!0);try{let k;if(b.customHeaders.trim())try{k=JSON.parse(b.customHeaders)}catch{throw new Error("Custom headers must be valid JSON object")}await Se.patch("/api/admin/providers",{id:x,name:b.name,slug:b.slug||void 0,type:b.type,baseUrl:b.baseUrl,apiKey:b.apiKey||void 0,customHeaders:k,enabled:b.enabled}),ve.success("Provider updated"),y(null),w(Al),M()}catch(k){ve.error(k.message)}finally{p(!1)}}},U=async k=>{N(!0);try{await Se.del(`/api/admin/providers/${k}`),ve.success("Provider removed"),M()}catch($){ve.error($.message)}finally{N(!1),j(null)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Providers",description:"Upstream LLM providers and their credentials",actions:o.jsx("div",{className:"flex gap-2",children:o.jsxs(Mn,{open:l,onOpenChange:s,children:[o.jsx(mi,{asChild:!0,children:o.jsx(me,{children:"Add compatible provider"})}),o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"New provider"}),o.jsx(uu,{children:"API-key or compatible endpoint."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-name",children:"Name"}),o.jsx(Ae,{id:"provider-name",value:c.name,onChange:k=>u({...c,name:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-slug",children:"Slug (optional)"}),o.jsx(Ae,{id:"provider-slug",value:c.slug,onChange:k=>u({...c,slug:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Type"}),o.jsxs(Ua,{value:c.type,onValueChange:k=>u($=>({...$,type:k,baseUrl:f_[k]})),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"openai",children:"OpenAI-compatible"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic-compatible"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-base-url",children:"Base URL"}),o.jsx(Ae,{id:"provider-base-url",value:c.baseUrl,onChange:k=>u({...c,baseUrl:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-api-key",children:"API key"}),o.jsx(Ae,{id:"provider-api-key",type:"password",value:c.apiKey,onChange:k=>u({...c,apiKey:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-headers",children:"Custom headers (JSON)"}),o.jsx(Ae,{id:"provider-headers",value:c.customHeaders,onChange:k=>u({...c,customHeaders:k.target.value}),placeholder:'{"X-Org":"acme"}'})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:c.enabled,onCheckedChange:k=>u({...c,enabled:k})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),o.jsx(me,{disabled:f||!c.name||!c.apiKey,onClick:T,children:f?"Creating…":"Create"})]})]})]})})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All providers"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Name"}),o.jsx(ye,{children:"Type"}),o.jsx(ye,{children:"Base URL"}),o.jsx(ye,{children:"Models"}),o.jsx(ye,{children:"Health"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{className:"text-right",children:"Actions"})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:7,className:"text-center text-muted-foreground",children:"No providers yet."})}),n.map(k=>o.jsxs(We,{children:[o.jsxs(pe,{className:"font-medium",children:[k.name," ",o.jsx("span",{className:"text-xs text-muted-foreground",children:k.slug})]}),o.jsx(pe,{children:o.jsx(Qe,{variant:"outline",children:k.type})}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:k.baseUrl}),o.jsx(pe,{children:k.modelCount}),o.jsx(pe,{children:o.jsx(Qe,{variant:k.health==="healthy"?"success":k.health==="down"?"destructive":"secondary",children:k.health})}),o.jsx(pe,{children:k.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex justify-end gap-1",children:[o.jsx(me,{size:"sm",variant:"outline",disabled:g===k.id,onClick:()=>D(k.id),children:o.jsx(A0,{className:"h-3 w-3"})}),o.jsx(me,{size:"sm",variant:"outline",onClick:()=>O(k),children:"✎"}),o.jsx(me,{size:"sm",variant:"outline",onClick:()=>j(k.id),children:o.jsx(ju,{className:"h-3 w-3"})})]})})]},k.id))]})]})})]}),o.jsx(Mn,{open:!!x,onOpenChange:k=>{k||(y(null),w(Al))},children:o.jsxs(vn,{children:[o.jsx(xn,{children:o.jsx(yn,{children:"Edit provider"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:b.name,onChange:k=>w({...b,name:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional)"}),o.jsx(Ae,{value:b.slug,onChange:k=>w({...b,slug:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Type"}),o.jsxs(Ua,{value:b.type,onValueChange:k=>w({...b,type:k}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"openai",children:"OpenAI-compatible"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic-compatible"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Base URL"}),o.jsx(Ae,{value:b.baseUrl,onChange:k=>w({...b,baseUrl:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"API key (leave empty to keep current)"}),o.jsx(Ae,{type:"password",value:b.apiKey,onChange:k=>w({...b,apiKey:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Custom headers (JSON)"}),o.jsx(Ae,{value:b.customHeaders,onChange:k=>w({...b,customHeaders:k.target.value}),placeholder:'{"X-Org":"acme"}'})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:b.enabled,onCheckedChange:k=>w({...b,enabled:k})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>{y(null),w(Al)},children:"Cancel"}),o.jsx(me,{disabled:f||!b.name,onClick:A,children:"Save changes"})]})]})}),o.jsx(up,{open:!!E,onOpenChange:k=>{k||j(null)},children:o.jsxs(Pu,{children:[o.jsxs(dp,{children:[o.jsx(qu,{children:"Delete provider?"}),o.jsx(Vu,{children:"This will soft-disable the provider if models depend on it."})]}),o.jsxs(fp,{children:[o.jsx(Yu,{children:"Cancel"}),o.jsx($u,{disabled:C,onClick:k=>{E&&(k.preventDefault(),U(E))},children:C?"Deleting…":"Delete"})]})]})})]})}var m_=Object.defineProperty,Sr=(n,a)=>m_(n,"name",{value:a,configurable:!0}),bp="Checkbox",[p_,Q4]=kn(bp),[g_,wp]=p_(bp);function Ww(n){const{__scopeCheckbox:a,checked:l,children:s,defaultChecked:c,disabled:u,form:f,name:p,onCheckedChange:g,required:v,value:x="on",internal_do_not_use_render:y}=n,[b,w]=yr({prop:l,defaultProp:c??!1,onChange:g,caller:bp}),[E,j]=m.useState(null),[C,N]=m.useState(null),M=m.useRef(!1),[T,D]=m.useReducer(U=>U+1,0),O=E?!!f||!!E.closest("form"):!0,A={checked:b,disabled:u,setChecked:w,control:E,setControl:j,name:p,form:f,value:x,hasConsumerStoppedPropagationRef:M,userInteractionCount:T,onUserInteraction:D,required:v,defaultChecked:vr(c)?!1:c,isFormControl:O,bubbleInput:C,setBubbleInput:N};return o.jsx(g_,{scope:a,...A,children:tS(y)?y(A):s})}Sr(Ww,"CheckboxProvider");var v_="CheckboxTrigger",x_=m.forwardRef(Sr(function({__scopeCheckbox:a,onKeyDown:l,onClick:s,...c},u){const{control:f,value:p,disabled:g,checked:v,required:x,setControl:y,setChecked:b,hasConsumerStoppedPropagationRef:w,onUserInteraction:E,isFormControl:j,bubbleInput:C}=wp(v_,a),N=Xe(u,y),M=m.useRef(v);return m.useEffect(()=>{const T=f==null?void 0:f.form;if(T){const D=Sr(()=>b(M.current),"reset");return T.addEventListener("reset",D),()=>T.removeEventListener("reset",D)}},[f,b]),o.jsx(Ve.button,{type:"button",role:"checkbox","aria-checked":vr(v)?"mixed":v,"aria-required":x,"data-state":Sp(v),"data-disabled":g?"":void 0,disabled:g,value:p,...c,ref:N,onKeyDown:Ne(l,T=>{T.key==="Enter"&&T.preventDefault()}),onClick:Ne(s,T=>{E(),b(D=>vr(D)?!0:!D),C&&j&&(w.current=T.isPropagationStopped(),w.current||T.stopPropagation())})})},"CheckboxTrigger")),eS=m.forwardRef(Sr(function(a,l){const{__scopeCheckbox:s,name:c,checked:u,defaultChecked:f,required:p,disabled:g,value:v,onCheckedChange:x,form:y,...b}=a;return o.jsx(Ww,{__scopeCheckbox:s,checked:u,defaultChecked:f,disabled:g,required:p,onCheckedChange:x,name:c,form:y,value:v,internal_do_not_use_render:({isFormControl:w})=>o.jsxs(o.Fragment,{children:[o.jsx(x_,{...b,ref:l,__scopeCheckbox:s}),w&&o.jsx(S_,{__scopeCheckbox:s})]})})},"Checkbox")),y_="CheckboxIndicator",b_=m.forwardRef(Sr(function(a,l){const{__scopeCheckbox:s,forceMount:c,...u}=a,f=wp(y_,s);return o.jsx(Cr,{present:c||vr(f.checked)||f.checked===!0,children:o.jsx(Ve.span,{"data-state":Sp(f.checked),"data-disabled":f.disabled?"":void 0,...u,ref:l,style:{pointerEvents:"none",...a.style}})})},"CheckboxIndicator")),w_="CheckboxBubbleInput",S_=m.forwardRef(Sr(function({__scopeCheckbox:a,onClick:l,...s},c){const{control:u,hasConsumerStoppedPropagationRef:f,userInteractionCount:p,checked:g,defaultChecked:v,required:x,disabled:y,name:b,value:w,form:E,bubbleInput:j,setBubbleInput:C}=wp(w_,a),N=Xe(c,C),M=_u(u),T=m.useRef(!1),D=m.useRef(g),O=m.useRef(p);m.useEffect(()=>{const U=j;if(!U)return;const k=window.HTMLInputElement.prototype,X=Object.getOwnPropertyDescriptor(k,"checked").set,te=p!==O.current;O.current=p;const G=D.current!==g;D.current=g;const ie=!(te&&f.current);if(G&&X){T.current=!te;const ce=new Event("click",{bubbles:ie});U.indeterminate=vr(g),X.call(U,vr(g)?!1:g),U.dispatchEvent(ce),T.current=!1}},[j,g,f,p]);const A=m.useRef(vr(g)?!1:g);return o.jsx(Ve.input,{type:"checkbox","aria-hidden":!0,defaultChecked:v??A.current,required:x,disabled:y,name:b,value:w,form:E,...s,tabIndex:-1,ref:N,onClick:Ne(l,U=>{T.current&&U.stopPropagation()}),style:{...s.style,...M,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function tS(n){return typeof n=="function"}Sr(tS,"isFunction");function vr(n){return n==="indeterminate"}Sr(vr,"isIndeterminate");function Sp(n){return vr(n)?"indeterminate":n?"checked":"unchecked"}Sr(Sp,"getState");const jp=m.forwardRef(({className:n,...a},l)=>o.jsx(eS,{ref:l,className:Ee("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",n),...a,children:o.jsx(b_,{className:Ee("flex items-center justify-center text-current"),children:o.jsx(C0,{className:"h-3.5 w-3.5"})})}));jp.displayName=eS.displayName;const um=["image_input","audio_input","tools","structured_output","reasoning","chat","streaming"],j_=["unknown","yes","no"];function C_(n,a){return n[a]===!0?"yes":n[a]===!1?"no":"unknown"}function E_(n){const a={};for(const l of um)a[l]=n[l]==="yes"?!0:n[l]==="no"?!1:null;return a}function R_(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState("all"),[f,p]=m.useState(!1),[g,v]=m.useState(""),[x,y]=m.useState([]),[b,w]=m.useState(new Set),[E,j]=m.useState(!1),[C,N]=m.useState(""),[M,T]=m.useState(""),[D,O]=m.useState(null),[A,U]=m.useState(!1),[k,$]=m.useState(null),[X,te]=m.useState(null),[G,ie]=m.useState(null),[ce,se]=m.useState({}),[_,H]=m.useState(!1),Q=q=>{const oe={};for(const de of um)oe[de]=C_(q.capabilities,de);se(oe),ie(q)},J=async()=>{if(G){H(!0);try{await Se.patch("/api/admin/models",{id:G.id,capabilities:E_(ce)}),ve.success("Capabilities updated"),ie(null),ee()}catch(q){ve.error(q.message)}finally{H(!1)}}},ee=async()=>{const[q,oe]=await Promise.all([Se.get("/api/admin/models"),Se.get("/api/admin/providers")]);a(q.models),s(oe.providers)};m.useEffect(()=>{ee()},[]);const z=n.filter(q=>!(c!=="all"&&q.providerId!==c||C&&!q.publicModelId.toLowerCase().includes(C.toLowerCase()))),I=x.filter(q=>{if(!M)return!0;const oe=M.toLowerCase();return q.upstreamId.toLowerCase().includes(oe)||q.displayName.toLowerCase().includes(oe)}),F=async()=>{if(g){j(!0);try{const q=await Se.post(`/api/admin/providers/${g}/discover`);y(q.models),w(new Set)}catch(q){ve.error(q.message)}finally{j(!1)}}},re=async()=>{if(b.size!==0)try{const q=await Se.post("/api/admin/models/import",{providerId:g,modelIds:Array.from(b)});ve.success(`Imported ${q.imported} of ${q.requested}`),p(!1),y([]),w(new Set),ee()}catch(q){ve.error(q.message)}},he=async()=>{if(X)try{await Se.del(`/api/admin/models/${X.id}`),ve.success("Model deleted"),te(null),ee()}catch(q){ve.error(q.message)}},ge=async q=>{var de,fe,Te;O(q),U(!0);const oe=Date.now();$({phase:"streaming",startedAt:oe,text:"",progress:{}});try{const je=await ru(`/api/admin/models/${q}/test-stream`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});if(!je.ok){const Ie=await je.text().catch(()=>"");$({phase:"error",model:q,error:`HTTP ${je.status}: ${Ie}`});return}const De=(de=je.body)==null?void 0:de.getReader();if(!De){$({phase:"error",model:q,error:"No response body"});return}const Fe=new TextDecoder;let et="",le="",Le=!1;for(;!Le;){const{value:Ie,done:kt}=await De.read();Le=kt,Ie&&(et+=Fe.decode(Ie,{stream:!0}));let St;for(;(St=et.indexOf(`
|
|
341
|
+
`);function Hc(n){return n.label!==void 0}var ED=3,RD="32px",ND="16px",Cb=4e3,TD=356,MD=14,AD=20,DD=200;function xa(...n){return n.filter(Boolean).join(" ")}function OD(n){let[a,l]=n.split("-"),s=[];return a&&s.push(a),l&&s.push(l),s}var _D=n=>{var a,l,s,c,u,f,p,g,v,x,y;let{invert:b,toast:w,unstyled:E,interacting:j,setHeights:C,visibleToasts:N,heights:M,index:T,toasts:D,expanded:O,removeToast:A,defaultRichColors:U,closeButton:k,style:$,cancelButtonStyle:X,actionButtonStyle:te,className:G="",descriptionClassName:ie="",duration:ce,position:se,gap:_,loadingIcon:H,expandByDefault:Q,classNames:J,icons:ee,closeButtonAriaLabel:z="Close toast",pauseWhenPageIsHidden:I}=n,[F,re]=ue.useState(null),[he,ge]=ue.useState(null),[q,oe]=ue.useState(!1),[de,fe]=ue.useState(!1),[Te,je]=ue.useState(!1),[De,Fe]=ue.useState(!1),[et,le]=ue.useState(!1),[Le,Ie]=ue.useState(0),[kt,St]=ue.useState(0),Ft=ue.useRef(w.duration||ce||Cb),on=ue.useRef(null),Qt=ue.useRef(null),jt=T===0,fn=T+1<=N,Mt=w.type,At=w.dismissible!==!1,cn=w.className||"",fa=w.descriptionClassName||"",Ta=ue.useMemo(()=>M.findIndex(Ce=>Ce.toastId===w.id)||0,[M,w.id]),Gn=ue.useMemo(()=>{var Ce;return(Ce=w.closeButton)!=null?Ce:k},[w.closeButton,k]),dl=ue.useMemo(()=>w.duration||ce||Cb,[w.duration,ce]),ha=ue.useRef(0),Dt=ue.useRef(0),hn=ue.useRef(0),Tt=ue.useRef(null),[Js,Pl]=se.split("-"),ql=ue.useMemo(()=>M.reduce((Ce,ke,Ue)=>Ue>=Ta?Ce:Ce+ke.height,0),[M,Ta]),Ya=vD(),Nr=w.invert||b,vt=Mt==="loading";Dt.current=ue.useMemo(()=>Ta*_+ql,[Ta,ql]),ue.useEffect(()=>{Ft.current=dl},[dl]),ue.useEffect(()=>{oe(!0)},[]),ue.useEffect(()=>{let Ce=Qt.current;if(Ce){let ke=Ce.getBoundingClientRect().height;return St(ke),C(Ue=>[{toastId:w.id,height:ke,position:w.position},...Ue]),()=>C(Ue=>Ue.filter(gt=>gt.toastId!==w.id))}},[C,w.id]),ue.useLayoutEffect(()=>{if(!q)return;let Ce=Qt.current,ke=Ce.style.height;Ce.style.height="auto";let Ue=Ce.getBoundingClientRect().height;Ce.style.height=ke,St(Ue),C(gt=>gt.find(Ct=>Ct.toastId===w.id)?gt.map(Ct=>Ct.toastId===w.id?{...Ct,height:Ue}:Ct):[{toastId:w.id,height:Ue,position:w.position},...gt])},[q,w.title,w.description,C,w.id]);let st=ue.useCallback(()=>{fe(!0),Ie(Dt.current),C(Ce=>Ce.filter(ke=>ke.toastId!==w.id)),setTimeout(()=>{A(w)},DD)},[w,A,C,Dt]);ue.useEffect(()=>{if(w.promise&&Mt==="loading"||w.duration===1/0||w.type==="loading")return;let Ce;return O||j||I&&Ya?(()=>{if(hn.current<ha.current){let ke=new Date().getTime()-ha.current;Ft.current=Ft.current-ke}hn.current=new Date().getTime()})():Ft.current!==1/0&&(ha.current=new Date().getTime(),Ce=setTimeout(()=>{var ke;(ke=w.onAutoClose)==null||ke.call(w,w),st()},Ft.current)),()=>clearTimeout(Ce)},[O,j,w,Mt,I,Ya,st]),ue.useEffect(()=>{w.delete&&st()},[st,w.delete]);function Bt(){var Ce,ke,Ue;return ee!=null&&ee.loading?ue.createElement("div",{className:xa(J==null?void 0:J.loader,(Ce=w==null?void 0:w.classNames)==null?void 0:Ce.loader,"sonner-loader"),"data-visible":Mt==="loading"},ee.loading):H?ue.createElement("div",{className:xa(J==null?void 0:J.loader,(ke=w==null?void 0:w.classNames)==null?void 0:ke.loader,"sonner-loader"),"data-visible":Mt==="loading"},H):ue.createElement(dD,{className:xa(J==null?void 0:J.loader,(Ue=w==null?void 0:w.classNames)==null?void 0:Ue.loader),visible:Mt==="loading"})}return ue.createElement("li",{tabIndex:0,ref:Qt,className:xa(G,cn,J==null?void 0:J.toast,(a=w==null?void 0:w.classNames)==null?void 0:a.toast,J==null?void 0:J.default,J==null?void 0:J[Mt],(l=w==null?void 0:w.classNames)==null?void 0:l[Mt]),"data-sonner-toast":"","data-rich-colors":(s=w.richColors)!=null?s:U,"data-styled":!(w.jsx||w.unstyled||E),"data-mounted":q,"data-promise":!!w.promise,"data-swiped":et,"data-removed":de,"data-visible":fn,"data-y-position":Js,"data-x-position":Pl,"data-index":T,"data-front":jt,"data-swiping":Te,"data-dismissible":At,"data-type":Mt,"data-invert":Nr,"data-swipe-out":De,"data-swipe-direction":he,"data-expanded":!!(O||Q&&q),style:{"--index":T,"--toasts-before":T,"--z-index":D.length-T,"--offset":`${de?Le:Dt.current}px`,"--initial-height":Q?"auto":`${kt}px`,...$,...w.style},onDragEnd:()=>{je(!1),re(null),Tt.current=null},onPointerDown:Ce=>{vt||!At||(on.current=new Date,Ie(Dt.current),Ce.target.setPointerCapture(Ce.pointerId),Ce.target.tagName!=="BUTTON"&&(je(!0),Tt.current={x:Ce.clientX,y:Ce.clientY}))},onPointerUp:()=>{var Ce,ke,Ue,gt;if(De||!At)return;Tt.current=null;let Ct=Number(((Ce=Qt.current)==null?void 0:Ce.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ct=Number(((ke=Qt.current)==null?void 0:ke.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),$t=new Date().getTime()-((Ue=on.current)==null?void 0:Ue.getTime()),xt=F==="x"?Ct:ct,zt=Math.abs(xt)/$t;if(Math.abs(xt)>=AD||zt>.11){Ie(Dt.current),(gt=w.onDismiss)==null||gt.call(w,w),ge(F==="x"?Ct>0?"right":"left":ct>0?"down":"up"),st(),Fe(!0),le(!1);return}je(!1),re(null)},onPointerMove:Ce=>{var ke,Ue,gt,Ct;if(!Tt.current||!At||((ke=window.getSelection())==null?void 0:ke.toString().length)>0)return;let ct=Ce.clientY-Tt.current.y,$t=Ce.clientX-Tt.current.x,xt=(Ue=n.swipeDirections)!=null?Ue:OD(se);!F&&(Math.abs($t)>1||Math.abs(ct)>1)&&re(Math.abs($t)>Math.abs(ct)?"x":"y");let zt={x:0,y:0};F==="y"?(xt.includes("top")||xt.includes("bottom"))&&(xt.includes("top")&&ct<0||xt.includes("bottom")&&ct>0)&&(zt.y=ct):F==="x"&&(xt.includes("left")||xt.includes("right"))&&(xt.includes("left")&&$t<0||xt.includes("right")&&$t>0)&&(zt.x=$t),(Math.abs(zt.x)>0||Math.abs(zt.y)>0)&&le(!0),(gt=Qt.current)==null||gt.style.setProperty("--swipe-amount-x",`${zt.x}px`),(Ct=Qt.current)==null||Ct.style.setProperty("--swipe-amount-y",`${zt.y}px`)}},Gn&&!w.jsx?ue.createElement("button",{"aria-label":z,"data-disabled":vt,"data-close-button":!0,onClick:vt||!At?()=>{}:()=>{var Ce;st(),(Ce=w.onDismiss)==null||Ce.call(w,w)},className:xa(J==null?void 0:J.closeButton,(c=w==null?void 0:w.classNames)==null?void 0:c.closeButton)},(u=ee==null?void 0:ee.close)!=null?u:gD):null,w.jsx||m.isValidElement(w.title)?w.jsx?w.jsx:typeof w.title=="function"?w.title():w.title:ue.createElement(ue.Fragment,null,Mt||w.icon||w.promise?ue.createElement("div",{"data-icon":"",className:xa(J==null?void 0:J.icon,(f=w==null?void 0:w.classNames)==null?void 0:f.icon)},w.promise||w.type==="loading"&&!w.icon?w.icon||Bt():null,w.type!=="loading"?w.icon||(ee==null?void 0:ee[Mt])||cD(Mt):null):null,ue.createElement("div",{"data-content":"",className:xa(J==null?void 0:J.content,(p=w==null?void 0:w.classNames)==null?void 0:p.content)},ue.createElement("div",{"data-title":"",className:xa(J==null?void 0:J.title,(g=w==null?void 0:w.classNames)==null?void 0:g.title)},typeof w.title=="function"?w.title():w.title),w.description?ue.createElement("div",{"data-description":"",className:xa(ie,fa,J==null?void 0:J.description,(v=w==null?void 0:w.classNames)==null?void 0:v.description)},typeof w.description=="function"?w.description():w.description):null),m.isValidElement(w.cancel)?w.cancel:w.cancel&&Hc(w.cancel)?ue.createElement("button",{"data-button":!0,"data-cancel":!0,style:w.cancelButtonStyle||X,onClick:Ce=>{var ke,Ue;Hc(w.cancel)&&At&&((Ue=(ke=w.cancel).onClick)==null||Ue.call(ke,Ce),st())},className:xa(J==null?void 0:J.cancelButton,(x=w==null?void 0:w.classNames)==null?void 0:x.cancelButton)},w.cancel.label):null,m.isValidElement(w.action)?w.action:w.action&&Hc(w.action)?ue.createElement("button",{"data-button":!0,"data-action":!0,style:w.actionButtonStyle||te,onClick:Ce=>{var ke,Ue;Hc(w.action)&&((Ue=(ke=w.action).onClick)==null||Ue.call(ke,Ce),!Ce.defaultPrevented&&st())},className:xa(J==null?void 0:J.actionButton,(y=w==null?void 0:w.classNames)==null?void 0:y.actionButton)},w.action.label):null))};function Eb(){if(typeof window>"u"||typeof document>"u")return"ltr";let n=document.documentElement.getAttribute("dir");return n==="auto"||!n?window.getComputedStyle(document.documentElement).direction:n}function kD(n,a){let l={};return[n,a].forEach((s,c)=>{let u=c===1,f=u?"--mobile-offset":"--offset",p=u?ND:RD;function g(v){["top","right","bottom","left"].forEach(x=>{l[`${f}-${x}`]=typeof v=="number"?`${v}px`:v})}typeof s=="number"||typeof s=="string"?g(s):typeof s=="object"?["top","right","bottom","left"].forEach(v=>{s[v]===void 0?l[`${f}-${v}`]=p:l[`${f}-${v}`]=typeof s[v]=="number"?`${s[v]}px`:s[v]}):g(p)}),l}var zD=m.forwardRef(function(n,a){let{invert:l,position:s="bottom-right",hotkey:c=["altKey","KeyT"],expand:u,closeButton:f,className:p,offset:g,mobileOffset:v,theme:x="light",richColors:y,duration:b,style:w,visibleToasts:E=ED,toastOptions:j,dir:C=Eb(),gap:N=MD,loadingIcon:M,icons:T,containerAriaLabel:D="Notifications",pauseWhenPageIsHidden:O}=n,[A,U]=ue.useState([]),k=ue.useMemo(()=>Array.from(new Set([s].concat(A.filter(I=>I.position).map(I=>I.position)))),[A,s]),[$,X]=ue.useState([]),[te,G]=ue.useState(!1),[ie,ce]=ue.useState(!1),[se,_]=ue.useState(x!=="system"?x:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),H=ue.useRef(null),Q=c.join("+").replace(/Key/g,"").replace(/Digit/g,""),J=ue.useRef(null),ee=ue.useRef(!1),z=ue.useCallback(I=>{U(F=>{var re;return(re=F.find(he=>he.id===I.id))!=null&&re.delete||Tn.dismiss(I.id),F.filter(({id:he})=>he!==I.id)})},[]);return ue.useEffect(()=>Tn.subscribe(I=>{if(I.dismiss){U(F=>F.map(re=>re.id===I.id?{...re,delete:!0}:re));return}setTimeout(()=>{$E.flushSync(()=>{U(F=>{let re=F.findIndex(he=>he.id===I.id);return re!==-1?[...F.slice(0,re),{...F[re],...I},...F.slice(re+1)]:[I,...F]})})})}),[]),ue.useEffect(()=>{if(x!=="system"){_(x);return}if(x==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?_("dark"):_("light")),typeof window>"u")return;let I=window.matchMedia("(prefers-color-scheme: dark)");try{I.addEventListener("change",({matches:F})=>{_(F?"dark":"light")})}catch{I.addListener(({matches:re})=>{try{_(re?"dark":"light")}catch(he){console.error(he)}})}},[x]),ue.useEffect(()=>{A.length<=1&&G(!1)},[A]),ue.useEffect(()=>{let I=F=>{var re,he;c.every(ge=>F[ge]||F.code===ge)&&(G(!0),(re=H.current)==null||re.focus()),F.code==="Escape"&&(document.activeElement===H.current||(he=H.current)!=null&&he.contains(document.activeElement))&&G(!1)};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[c]),ue.useEffect(()=>{if(H.current)return()=>{J.current&&(J.current.focus({preventScroll:!0}),J.current=null,ee.current=!1)}},[H.current]),ue.createElement("section",{ref:a,"aria-label":`${D} ${Q}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},k.map((I,F)=>{var re;let[he,ge]=I.split("-");return A.length?ue.createElement("ol",{key:I,dir:C==="auto"?Eb():C,tabIndex:-1,ref:H,className:p,"data-sonner-toaster":!0,"data-theme":se,"data-y-position":he,"data-lifted":te&&A.length>1&&!u,"data-x-position":ge,style:{"--front-toast-height":`${((re=$[0])==null?void 0:re.height)||0}px`,"--width":`${TD}px`,"--gap":`${N}px`,...w,...kD(g,v)},onBlur:q=>{ee.current&&!q.currentTarget.contains(q.relatedTarget)&&(ee.current=!1,J.current&&(J.current.focus({preventScroll:!0}),J.current=null))},onFocus:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||ee.current||(ee.current=!0,J.current=q.relatedTarget)},onMouseEnter:()=>G(!0),onMouseMove:()=>G(!0),onMouseLeave:()=>{ie||G(!1)},onDragEnd:()=>G(!1),onPointerDown:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||ce(!0)},onPointerUp:()=>ce(!1)},A.filter(q=>!q.position&&F===0||q.position===I).map((q,oe)=>{var de,fe;return ue.createElement(_D,{key:q.id,icons:T,index:oe,toast:q,defaultRichColors:y,duration:(de=j==null?void 0:j.duration)!=null?de:b,className:j==null?void 0:j.className,descriptionClassName:j==null?void 0:j.descriptionClassName,invert:l,visibleToasts:E,closeButton:(fe=j==null?void 0:j.closeButton)!=null?fe:f,interacting:ie,position:I,style:j==null?void 0:j.style,unstyled:j==null?void 0:j.unstyled,classNames:j==null?void 0:j.classNames,cancelButtonStyle:j==null?void 0:j.cancelButtonStyle,actionButtonStyle:j==null?void 0:j.actionButtonStyle,removeToast:z,toasts:A.filter(Te=>Te.position==q.position),heights:$.filter(Te=>Te.position==q.position),setHeights:X,expandByDefault:u,gap:N,loadingIcon:M,expanded:te,pauseWhenPageIsHidden:O,swipeDirections:n.swipeDirections})})):null}))});function LD(){const{login:n}=_m(),[a,l]=m.useState("admin"),[s,c]=m.useState(""),[u,f]=m.useState(""),[p,g]=m.useState(""),[v,x]=m.useState(!1),[y,b]=m.useState(!1),w=oi(),E=_n();return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:o.jsxs(nt,{className:"w-full max-w-sm",children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("img",{src:"/logo.png",alt:"LateDev Router",className:"h-8 w-8 object-contain"}),o.jsx(rt,{children:"Sign in"})]}),o.jsx(gn,{children:"Enter your admin credentials."})]}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Username"}),o.jsx(Ae,{value:a,onChange:j=>l(j.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Password"}),o.jsx(Ae,{type:"password",value:s,onChange:j=>c(j.target.value)})]}),v&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"2FA code (or recovery code)"}),o.jsx(Ae,{value:u,onChange:j=>f(j.target.value),placeholder:"123456",maxLength:6})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Recovery code (alternative)"}),o.jsx(Ae,{value:p,onChange:j=>g(j.target.value),placeholder:"ABCD12-EF3456"})]})]})]}),o.jsx("div",{className:"px-6 pb-6",children:o.jsx(me,{className:"w-full",disabled:y,onClick:async()=>{var j,C;b(!0);try{if((await n(a,s,u||void 0,p||void 0)).totpRequired){x(!0);return}const M=((C=(j=E.state)==null?void 0:j.from)==null?void 0:C.pathname)??"/";w(M,{replace:!0})}catch(N){ve.error(N.message)}finally{b(!1)}},children:"Sign in"})})]})})}function UD(){const[n,a]=m.useState("admin"),[l,s]=m.useState(""),[c,u]=m.useState(""),[f,p]=m.useState(!1),[g,v]=m.useState(!0),[x,y]=m.useState(null),[b,w]=m.useState(""),[E,j]=m.useState(!1);m.useEffect(()=>{Se.get("/api/admin/setup/status").then(M=>v(!M.masterKeyConfigured)).catch(()=>v(!0))},[]);const C=!g||c.trim().length>=32,N=!f&&l.length>=12&&C;return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:o.jsxs(nt,{className:"w-full max-w-md",children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("img",{src:"/logo.png",alt:"LateDev Router",className:"h-8 w-8 object-contain rounded"}),o.jsx(rt,{children:"Welcome to LateDev Router"})]}),o.jsx(gn,{children:"Set up the administrator account to get started."})]}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Username"}),o.jsx(Ae,{value:n,onChange:M=>a(M.target.value)})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Password (12+ chars)"}),o.jsx(Ae,{type:"password",value:l,onChange:M=>s(M.target.value)})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs(we,{children:["Master encryption key ",g?"(required, 32+ chars)":"(already configured)"]}),o.jsx(Ae,{type:"password",value:c,onChange:M=>u(M.target.value),placeholder:"Paste or generate a 32+ character key"}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Provider API keys are encrypted with this key (AES-256-GCM). Store it somewhere safe — if it is lost, stored provider credentials cannot be recovered. Generate one with:"," ",o.jsx("code",{className:"break-all",children:`node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"`})]})]})]}),o.jsxs(jw,{className:"flex-col items-stretch gap-4",children:[o.jsx(me,{disabled:!N,onClick:async()=>{p(!0);try{await Se.post("/api/admin/setup",{username:n,password:l,setupMasterKey:c.trim()||void 0}),ve.success("Admin account created"),window.location.assign("/login")}catch(M){ve.error(M.message)}finally{p(!1)}},children:"Create admin"}),o.jsxs("div",{className:"border-t pt-4 space-y-2",children:[o.jsx(we,{children:"Import existing database"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Use this to restore the administrator account, password, TOTP settings, providers, models, and master key from a backup without setting up again. Enter the same 6-digit backup passphrase used when the file was created."}),o.jsx(Ae,{type:"file",accept:".json,application/json",onChange:M=>{var T;return y(((T=M.target.files)==null?void 0:T[0])??null)}}),o.jsx(Ae,{inputMode:"numeric",maxLength:6,value:b,onChange:M=>w(M.target.value.replace(/\D/g,"")),placeholder:"Backup passphrase (6 digits)"}),o.jsx(me,{variant:"outline",disabled:!x||b.length!==6||E,onClick:async()=>{var M,T;if(x){j(!0);try{const D=JSON.parse(await x.text()),O=await fetch("/api/admin/backup/restore",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({backup:D,passphrase:b})});if(!O.ok)throw new Error(((T=(M=await O.json())==null?void 0:M.error)==null?void 0:T.message)??"Import failed");ve.success("Database imported"),window.location.assign("/login")}catch(D){ve.error(D.message)}finally{j(!1)}}},children:"Import database"})]})]})]})})}function $a({title:n,description:a,actions:l,className:s}){return o.jsxs("div",{className:Ee("mb-6 flex items-start justify-between gap-4",s),children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:n}),a&&o.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:a})]}),l&&o.jsx("div",{className:"flex items-center gap-2",children:l})]})}const BD=K0("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive text-destructive-foreground",success:"border-transparent bg-emerald-600 text-white",warning:"border-transparent bg-amber-500 text-white",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Qe({className:n,variant:a,...l}){return o.jsx("div",{className:Ee(BD({variant:a}),n),...l})}const Oh=n=>n==="ready"||n==="healthy"?"success":n==="disabled"?"secondary":"destructive";function HD(){const[n,a]=m.useState(null);return m.useEffect(()=>{Se.get("/api/admin/dashboard").then(a).catch(()=>a(null))},[]),n?o.jsxs("div",{children:[o.jsx($a,{title:"Dashboard",description:"Operational summary for today",actions:o.jsxs("div",{className:"flex gap-2",children:[o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/providers",children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," Provider"]})}),o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/combos",children:[o.jsx(T0,{className:"mr-1 h-4 w-4"})," Combo"]})}),o.jsx(me,{asChild:!0,variant:"outline",size:"sm",children:o.jsxs(ra,{to:"/api-keys",children:[o.jsx(N0,{className:"mr-1 h-4 w-4"})," API Key"]})})]})}),o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Requests today"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.total)})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Success rate"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:n.today.total?Eu(n.today.success/n.today.total):"—"})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Failed"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.failed)})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-1",children:o.jsx(rt,{className:"text-sm text-muted-foreground",children:"Tokens today"})}),o.jsx(lt,{className:"text-2xl font-semibold",children:Kt(n.today.totalTokens)})]})]}),o.jsxs("div",{className:"mt-6 grid gap-4 lg:grid-cols-2",children:[o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Provider health"}),o.jsxs(gn,{children:[n.providers.length," configured"]})]}),o.jsxs(lt,{className:"space-y-2",children:[n.providers.length===0&&o.jsxs("p",{className:"text-sm text-muted-foreground",children:["No providers yet. ",o.jsx(ra,{to:"/providers",className:"text-primary",children:"Add one"}),"."]}),n.providers.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(M0,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx(ra,{className:"truncate font-medium text-primary hover:underline",to:`/providers?providerId=${encodeURIComponent(l.id)}`,children:l.name}),o.jsx("span",{className:"hidden text-xs text-muted-foreground sm:inline",children:l.slug}),o.jsx(Qe,{variant:"outline",className:"ml-2",children:l.type})]}),o.jsx(Qe,{variant:Oh(l.health),children:l.health})]},l.id))]})]}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Recent failures"}),o.jsx(gn,{children:"Today"})]}),o.jsxs(lt,{className:"space-y-1 text-sm",children:[n.recentFailures.length===0&&o.jsx("p",{className:"text-muted-foreground",children:"No failures today."}),n.recentFailures.map(l=>{var s;return o.jsxs("div",{className:"flex items-center justify-between border-b py-1 last:border-0",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-mono text-xs",children:l.requestedModel}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.errorType??`HTTP ${l.httpStatus}`," — ",(s=l.errorMessage)==null?void 0:s.slice(0,60)]})]}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Lm(l.createdAt)})]},l.id)})]})]})]}),o.jsxs(nt,{className:"mt-6",children:[o.jsxs(at,{children:[o.jsxs(rt,{className:"flex items-center gap-2 text-base",children:[o.jsx(km,{className:"h-4 w-4"})," Health center"]}),o.jsx(gn,{children:"Passive status from recent traffic; no active provider polling."})]}),o.jsxs(lt,{className:"grid gap-4 lg:grid-cols-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Combos"}),o.jsx("div",{className:"space-y-2",children:n.combos.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No combos configured."}):n.combos.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ra,{className:"font-mono text-xs text-primary hover:underline",to:"/combos",children:l.publicModelId}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.readyMembers,"/",l.memberCount," members ready",l.reasons.length>0?` · ${l.reasons.join(", ")}`:""]})]}),o.jsx(Qe,{variant:Oh(l.state),children:l.state})]},l.id))})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Models"}),o.jsx("div",{className:"max-h-64 space-y-2 overflow-auto",children:n.models.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No models imported."}):n.models.map(l=>o.jsxs("div",{className:"flex items-center justify-between rounded border p-2 text-sm",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ra,{className:"font-mono text-xs text-primary hover:underline",to:`/models?providerId=${encodeURIComponent(l.providerId)}`,children:l.publicModelId}),o.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[l.providerName??"Unknown provider",l.lastFailureReason?` · last: ${l.lastFailureReason}`:""]})]}),o.jsx(Qe,{variant:Oh(l.state),children:l.state})]},l.id))})]})]})]})]}):o.jsx("div",{className:"text-muted-foreground",children:"Loading…"})}const ca=m.forwardRef(({className:n,...a},l)=>o.jsx("div",{className:"relative w-full overflow-auto",children:o.jsx("table",{ref:l,className:Ee("w-full caption-bottom text-sm",n),...a})}));ca.displayName="Table";const ua=m.forwardRef(({className:n,...a},l)=>o.jsx("thead",{ref:l,className:Ee("[&_tr]:border-b",n),...a}));ua.displayName="TableHeader";const da=m.forwardRef(({className:n,...a},l)=>o.jsx("tbody",{ref:l,className:Ee("[&_tr:last-child]:border-0",n),...a}));da.displayName="TableBody";const We=m.forwardRef(({className:n,...a},l)=>o.jsx("tr",{ref:l,className:Ee("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",n),...a}));We.displayName="TableRow";const ye=m.forwardRef(({className:n,...a},l)=>o.jsx("th",{ref:l,className:Ee("h-10 px-2 text-left align-middle font-medium text-muted-foreground",n),...a}));ye.displayName="TableHead";const pe=m.forwardRef(({className:n,...a},l)=>o.jsx("td",{ref:l,className:Ee("p-2 align-middle",n),...a}));pe.displayName="TableCell";var ID=Object.defineProperty,Yn=(n,a)=>ID(n,"name",{value:a,configurable:!0}),rp="Dialog",[Cw,Ew]=kn(rp),[PD,Na]=Cw(rp),Rw=Yn(n=>{const{__scopeDialog:a,children:l,open:s,defaultOpen:c,onOpenChange:u,modal:f=!0}=n,p=m.useRef(null),g=m.useRef(null),[v,x]=yr({prop:s,defaultProp:c??!1,onChange:u,caller:rp}),[y,b]=m.useState(0),[w,E]=m.useState(0);return o.jsx(PD,{scope:a,triggerRef:p,contentRef:g,contentId:La(),titleId:La(),descriptionId:La(),titlePresent:y>0,descriptionPresent:w>0,setTitleCount:b,setDescriptionCount:E,open:v,onOpenChange:x,onOpenToggle:m.useCallback(()=>x(j=>!j),[x]),modal:f,children:l})},"Dialog"),qD="DialogTrigger",Nw=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(qD,s),f=Xe(l,u.triggerRef);return o.jsx(Ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":u.open,"aria-controls":u.open?u.contentId:void 0,"data-state":Iu(u.open),...c,ref:f,onClick:Ne(a.onClick,u.onOpenToggle)})},"DialogTrigger")),Tw="DialogPortal",[VD,Mw]=Cw(Tw,{forceMount:void 0}),Aw=Yn(n=>{const{__scopeDialog:a,forceMount:l,children:s,container:c}=n,u=Na(Tw,a);return o.jsx(VD,{scope:a,forceMount:l,children:m.Children.map(s,f=>o.jsx(Cr,{present:l||u.open,children:o.jsx(Zm,{asChild:!0,container:c,children:f})}))})},"DialogPortal"),om="DialogOverlay",lp=m.forwardRef(Yn(function(a,l){const s=Mw(om,a.__scopeDialog),{forceMount:c=s.forceMount,...u}=a,f=Na(om,a.__scopeDialog);return f.modal?o.jsx(Cr,{present:c||f.open,children:o.jsx(YD,{...u,ref:l})}):null},"DialogOverlay")),$D=Ha("DialogOverlay.RemoveScroll"),YD=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(om,s),f=o1(),p=Xe(l,f);return o.jsx(Bu,{as:$D,allowPinchZoom:!0,shards:[u.contentRef],children:o.jsx(Ve.div,{"data-state":Iu(u.open),...c,ref:p,style:{pointerEvents:"auto",...c.style}})})},"DialogOverlayImpl")),ei="DialogContent",sp=m.forwardRef(Yn(function(a,l){const s=Mw(ei,a.__scopeDialog),{forceMount:c=s.forceMount,...u}=a,f=Na(ei,a.__scopeDialog);return o.jsx(Cr,{present:c||f.open,children:f.modal?o.jsx(GD,{...u,ref:l}):o.jsx(KD,{...u,ref:l})})},"DialogContent")),GD=m.forwardRef(Yn(function(a,l){const s=Na(ei,a.__scopeDialog),c=m.useRef(null),u=Xe(l,s.contentRef,c);return m.useEffect(()=>{const f=c.current;if(f)return ep(f)},[]),o.jsx(Dw,{...a,ref:u,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Ne(a.onCloseAutoFocus,f=>{var p;f.preventDefault(),(p=s.triggerRef.current)==null||p.focus()}),onPointerDownOutside:Ne(a.onPointerDownOutside,f=>{const p=f.detail.originalEvent,g=p.button===0&&p.ctrlKey===!0;(p.button===2||g)&&f.preventDefault()}),onFocusOutside:Ne(a.onFocusOutside,f=>f.preventDefault())})},"DialogContentModal")),KD=m.forwardRef(Yn(function(a,l){const s=Na(ei,a.__scopeDialog),c=m.useRef(!1),u=m.useRef(!1);return o.jsx(Dw,{...a,ref:l,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:f=>{var p,g;(p=a.onCloseAutoFocus)==null||p.call(a,f),f.defaultPrevented||(c.current||(g=s.triggerRef.current)==null||g.focus(),f.preventDefault()),c.current=!1,u.current=!1},onInteractOutside:f=>{var v,x;(v=a.onInteractOutside)==null||v.call(a,f),f.defaultPrevented||(c.current=!0,f.detail.originalEvent.type==="pointerdown"&&(u.current=!0));const p=f.target;((x=s.triggerRef.current)==null?void 0:x.contains(p))&&f.preventDefault(),f.detail.originalEvent.type==="focusin"&&u.current&&f.preventDefault()}})},"DialogContentNonModal")),Dw=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,trapFocus:c,onOpenAutoFocus:u,onCloseAutoFocus:f,...p}=a,g=Na(ei,s);return fi(),o.jsx(o.Fragment,{children:o.jsx(qm,{asChild:!0,loop:!0,trapped:c,onMountAutoFocus:u,onUnmountAutoFocus:f,children:o.jsx(Nu,{role:"dialog",id:g.contentId,"aria-describedby":g.descriptionPresent?g.descriptionId:void 0,"aria-labelledby":g.titlePresent?g.titleId:void 0,"data-state":Iu(g.open),...p,ref:l,deferPointerDownOutside:!0,onDismiss:()=>g.onOpenChange(!1)})})})},"DialogContentImpl")),XD="DialogTitle",op=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(XD,s),{setTitleCount:f}=u;return Xt(()=>(f(p=>p+1),()=>f(p=>p-1)),[f]),o.jsx(Ve.h2,{id:u.titleId,...c,ref:l})},"DialogTitle")),FD="DialogDescription",ip=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(FD,s),{setDescriptionCount:f}=u;return Xt(()=>(f(p=>p+1),()=>f(p=>p-1)),[f]),o.jsx(Ve.p,{id:u.descriptionId,...c,ref:l})},"DialogDescription")),QD="DialogClose",cp=m.forwardRef(Yn(function(a,l){const{__scopeDialog:s,...c}=a,u=Na(QD,s);return o.jsx(Ve.button,{type:"button",...c,ref:l,onClick:Ne(a.onClick,()=>u.onOpenChange(!1))})},"DialogClose"));function Iu(n){return n?"open":"closed"}Yn(Iu,"getState");const Mn=Rw,mi=Nw,ZD=Aw,Ow=m.forwardRef(({className:n,...a},l)=>o.jsx(lp,{ref:l,className:Ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...a}));Ow.displayName=lp.displayName;const vn=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(ZD,{children:[o.jsx(Ow,{}),o.jsxs(sp,{ref:s,className:Ee("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 sm:rounded-lg",n),...l,children:[a,o.jsxs(cp,{className:"absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100",children:[o.jsx(Cu,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vn.displayName=sp.displayName;const xn=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col space-y-1.5 text-center sm:text-left",n),...a});xn.displayName="DialogHeader";const An=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...a});An.displayName="DialogFooter";const yn=m.forwardRef(({className:n,...a},l)=>o.jsx(op,{ref:l,className:Ee("text-lg font-semibold leading-none tracking-tight",n),...a}));yn.displayName=op.displayName;const uu=m.forwardRef(({className:n,...a},l)=>o.jsx(ip,{ref:l,className:Ee("text-sm text-muted-foreground",n),...a}));uu.displayName=ip.displayName;var JD=Object.defineProperty,Er=(n,a)=>JD(n,"name",{value:a,configurable:!0}),WD="AlertDialog",[eO,Y4]=kn(WD,[Ew]),Rr=Ew(),tO=Er(n=>{const{__scopeAlertDialog:a,...l}=n,s=Rr(a);return o.jsx(Rw,{...s,...l,modal:!0})},"AlertDialog"),nO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(Nw,{...u,...c,ref:l})},"AlertDialogTrigger")),aO=Er(n=>{const{__scopeAlertDialog:a,...l}=n,s=Rr(a);return o.jsx(Aw,{...s,...l})},"AlertDialogPortal"),rO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(lp,{...u,...c,ref:l})},"AlertDialogOverlay")),lO="AlertDialogContent",[sO,oO]=eO(lO),iO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,children:c,...u}=a,f=Rr(s),p=m.useRef(null),g=Xe(l,p),v=m.useRef(null);return o.jsx(sO,{scope:s,cancelRef:v,children:o.jsx(sp,{role:"alertdialog",...f,...u,ref:g,onOpenAutoFocus:Ne(u.onOpenAutoFocus,x=>{var y;x.preventDefault(),(y=v.current)==null||y.focus({preventScroll:!0})}),onPointerDownOutside:x=>x.preventDefault(),onInteractOutside:x=>x.preventDefault(),children:c})})},"AlertDialogContent")),cO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(op,{...u,...c,ref:l})},"AlertDialogTitle")),uO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(ip,{...u,...c,ref:l})},"AlertDialogDescription")),dO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,u=Rr(s);return o.jsx(cp,{...u,...c,ref:l})},"AlertDialogAction")),fO="AlertDialogCancel",hO=m.forwardRef(Er(function(a,l){const{__scopeAlertDialog:s,...c}=a,{cancelRef:u}=oO(fO,s),f=Rr(s),p=Xe(l,u);return o.jsx(cp,{...f,...c,ref:p})},"AlertDialogCancel")),mO=tO,pO=nO,gO=aO,_w=rO,kw=iO,zw=dO,Lw=hO,Uw=cO,Bw=uO;const up=mO,vO=pO,xO=gO,Hw=m.forwardRef(({className:n,...a},l)=>o.jsx(_w,{ref:l,className:Ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...a}));Hw.displayName=_w.displayName;const Pu=m.forwardRef(({className:n,...a},l)=>o.jsxs(xO,{children:[o.jsx(Hw,{}),o.jsx(kw,{ref:l,className:Ee("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg sm:max-w-[425px]",n),...a})]}));Pu.displayName=kw.displayName;const dp=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col space-y-2 text-center sm:text-left",n),...a}),fp=({className:n,...a})=>o.jsx("div",{className:Ee("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...a}),qu=m.forwardRef(({className:n,...a},l)=>o.jsx(Uw,{ref:l,className:Ee("text-lg font-semibold",n),...a}));qu.displayName=Uw.displayName;const Vu=m.forwardRef(({className:n,...a},l)=>o.jsx(Bw,{ref:l,className:Ee("text-sm text-muted-foreground",n),...a}));Vu.displayName=Bw.displayName;const $u=m.forwardRef(({className:n,...a},l)=>o.jsx(zw,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",n),...a}));$u.displayName=zw.displayName;const Yu=m.forwardRef(({className:n,...a},l)=>o.jsx(Lw,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium hover:bg-accent",n),...a}));Yu.displayName=Lw.displayName;var yO=Object.defineProperty,bO=(n,a)=>yO(n,"name",{value:a,configurable:!0});function im(n,[a,l]){return Math.min(l,Math.max(a,n))}bO(im,"clamp");var wO=Object.defineProperty,SO=(n,a)=>wO(n,"name",{value:a,configurable:!0});function Iw(n){const a=m.useRef({value:n,previous:n});return m.useMemo(()=>(a.current.value!==n&&(a.current.previous=a.current.value,a.current.value=n),a.current.previous),[n])}SO(Iw,"usePrevious");var jO=Object.defineProperty,CO=(n,a)=>jO(n,"name",{value:a,configurable:!0}),Pw=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),EO=m.forwardRef(CO(function(a,l){return o.jsx(Ve.span,{...a,ref:l,style:{...Pw,...a.style}})},"VisuallyHidden")),RO=EO,NO=Object.defineProperty,ht=(n,a)=>NO(n,"name",{value:a,configurable:!0}),TO=[" ","Enter","ArrowUp","ArrowDown"],MO=[" ","Enter"],Bs="Select",[Gu,hp,AO]=Ru(Bs),[Il,G4]=kn(Bs,[AO,Ks]),mp=Ks(),[DO,ul]=Il(Bs),[OO,_O]=Il(Bs);function qw(n){const{__scopeSelect:a,children:l,open:s,defaultOpen:c,onOpenChange:u,value:f,defaultValue:p,onValueChange:g,dir:v,name:x,autoComplete:y,disabled:b,required:w,form:E,internal_do_not_use_render:j}=n,C=mp(a),[N,M]=m.useState(null),[T,D]=m.useState(null),[O,A]=m.useState(!1),U=di(v),[k,$]=yr({prop:s,defaultProp:c??!1,onChange:u,caller:Bs}),[X,te]=yr({prop:f,defaultProp:p,onChange:g,caller:Bs}),G=m.useRef(null),ie=m.useRef(X);m.useEffect(()=>{const I=E?N==null?void 0:N.ownerDocument.getElementById(E):N==null?void 0:N.form;if(I instanceof HTMLFormElement){const F=ht(()=>te(ie.current),"reset");return I.addEventListener("reset",F),()=>I.removeEventListener("reset",F)}},[E,N,te]);const ce=N?!!E||!!N.closest("form"):!0,[se,_]=m.useState(new Set),H=La(),Q=Array.from(se).map(I=>I.props.value).join(";"),J=m.useCallback(I=>{_(F=>new Set(F).add(I))},[]),ee=m.useCallback(I=>{_(F=>{const re=new Set(F);return re.delete(I),re})},[]),z={required:w,trigger:N,onTriggerChange:M,valueNode:T,onValueNodeChange:D,valueNodeHasChildren:O,onValueNodeHasChildrenChange:A,contentId:H,value:X,onValueChange:te,open:k,onOpenChange:$,dir:U,triggerPointerDownPosRef:G,disabled:b,name:x,autoComplete:y,form:E,nativeOptions:se,nativeSelectKey:Q,isFormControl:ce};return o.jsx(O1,{...C,children:o.jsx(DO,{scope:a,...z,children:o.jsx(Gu.Provider,{scope:a,children:o.jsx(OO,{scope:a,onNativeOptionAdd:J,onNativeOptionRemove:ee,children:Xw(j)?j(z):l})})})})}ht(qw,"SelectProvider");var kO=ht(n=>{const{__scopeSelect:a,children:l,...s}=n;return o.jsx(qw,{__scopeSelect:a,...s,internal_do_not_use_render:({isFormControl:c})=>o.jsxs(o.Fragment,{children:[l,c?o.jsx(n_,{__scopeSelect:a}):null]})})},"Select"),zO="SelectTrigger",Vw=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,disabled:c=!1,...u}=a,f=mp(s),p=ul(zO,s),g=p.disabled||c,v=Xe(l,p.onTriggerChange),x=hp(s),y=m.useRef("touch"),[b,w,E]=pp(C=>{const N=x().filter(D=>!D.disabled),M=N.find(D=>D.value===p.value),T=gp(N,C,M);T!==void 0&&p.onValueChange(T.value)}),j=ht(C=>{g||(p.onOpenChange(!0),E()),C&&(p.triggerPointerDownPosRef.current={x:Math.round(C.pageX),y:Math.round(C.pageY)})},"handleOpen");return o.jsx(_1,{asChild:!0,...f,children:o.jsx(Ve.button,{type:"button",role:"combobox","aria-controls":p.open?p.contentId:void 0,"aria-expanded":p.open,"aria-required":p.required,"aria-autocomplete":"none",dir:p.dir,"data-state":p.open?"open":"closed",disabled:g,"data-disabled":g?"":void 0,"data-placeholder":pi(p.value)?"":void 0,...u,ref:v,onClick:Ne(u.onClick,C=>{C.currentTarget.focus(),y.current!=="mouse"&&j(C)}),onPointerDown:Ne(u.onPointerDown,C=>{y.current=C.pointerType;const N=C.target;N.hasPointerCapture(C.pointerId)&&N.releasePointerCapture(C.pointerId),C.button===0&&C.ctrlKey===!1&&C.pointerType==="mouse"&&(j(C),C.preventDefault())}),onKeyDown:Ne(u.onKeyDown,C=>{const N=b.current!=="";!(C.ctrlKey||C.altKey||C.metaKey)&&C.key.length===1&&w(C.key),!(N&&C.key===" ")&&TO.includes(C.key)&&(j(),C.preventDefault())})})})},"SelectTrigger")),LO="SelectValue",UO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,className:c,style:u,children:f,placeholder:p="",...g}=a,v=ul(LO,s),{onValueNodeHasChildrenChange:x}=v,y=f!==void 0,b=Xe(l,v.onValueNodeChange);Xt(()=>{x(y)},[x,y]);const w=pi(v.value);return o.jsx(Ve.span,{...g,asChild:w?!1:g.asChild,ref:b,style:{pointerEvents:"none"},children:o.jsx(m.Fragment,{children:w?p:f},w?"placeholder":"value")})},"SelectValue")),BO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,children:c,...u}=a;return o.jsx(Ve.span,{"aria-hidden":!0,...u,ref:l,children:c||"▼"})},"SelectIcon")),HO="SelectPortal",[IO,PO]=Il(HO,{forceMount:void 0}),qO=ht(n=>{const{__scopeSelect:a,forceMount:l,...s}=n;return o.jsx(IO,{scope:n.__scopeSelect,forceMount:l,children:o.jsx(Zm,{asChild:!0,...s})})},"SelectPortal"),zl="SelectContent",$w=m.forwardRef(ht(function(a,l){const s=PO(zl,a.__scopeSelect),{forceMount:c=s.forceMount,...u}=a,f=ul(zl,a.__scopeSelect),[p,g]=m.useState();return Xt(()=>{g(new DocumentFragment)},[]),o.jsx(Cr,{present:c||f.open,children:({present:v})=>v?o.jsx(YO,{...u,ref:l}):o.jsx(VO,{...u,fragment:p})})},"SelectContent")),VO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,children:c,fragment:u}=a;return u?ba.createPortal(o.jsx(Yw,{scope:s,children:o.jsx(Gu.Slot,{scope:s,children:o.jsx("div",{ref:l,children:c})})}),u):null},"SelectContentFragment")),ya=10,[Yw,Ku]=Il(zl),$O=Ha("SelectContent.RemoveScroll"),YO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s}=a,{position:c="item-aligned",onCloseAutoFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,side:g,sideOffset:v,align:x,alignOffset:y,arrowPadding:b,collisionBoundary:w,collisionPadding:E,sticky:j,hideWhenDetached:C,avoidCollisions:N,...M}=a,T=ul(zl,s),[D,O]=m.useState(null),[A,U]=m.useState(null),k=Xe(l,O),[$,X]=m.useState(null),[te,G]=m.useState(null),ie=hp(s),[ce,se]=m.useState(!1),_=m.useRef(!1);m.useEffect(()=>{if(D)return ep(D)},[D]),fi();const H=m.useCallback(oe=>{const[de,...fe]=ie().map(De=>De.ref.current),[Te]=fe.slice(-1),je=document.activeElement;for(const De of oe)if(De===je||(De==null||De.scrollIntoView({block:"nearest"}),De===de&&A&&(A.scrollTop=0),De===Te&&A&&(A.scrollTop=A.scrollHeight),De==null||De.focus(),document.activeElement!==je))return},[ie,A]),Q=m.useCallback(()=>H([$,D]),[H,$,D]);m.useEffect(()=>{ce&&Q()},[ce,Q]);const{onOpenChange:J,triggerPointerDownPosRef:ee}=T;m.useEffect(()=>{if(D){let oe={x:0,y:0};const de=ht(Te=>{var je,De;oe={x:Math.abs(Math.round(Te.pageX)-(((je=ee.current)==null?void 0:je.x)??0)),y:Math.abs(Math.round(Te.pageY)-(((De=ee.current)==null?void 0:De.y)??0))}},"handlePointerMove"),fe=ht(Te=>{oe.x<=10&&oe.y<=10?Te.preventDefault():Te.composedPath().includes(D)||J(!1),document.removeEventListener("pointermove",de),ee.current=null},"handlePointerUp");return ee.current!==null&&(document.addEventListener("pointermove",de),document.addEventListener("pointerup",fe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",de),document.removeEventListener("pointerup",fe,{capture:!0})}}},[D,J,ee]),m.useEffect(()=>{const oe=ht(()=>J(!1),"close");return window.addEventListener("blur",oe),window.addEventListener("resize",oe),()=>{window.removeEventListener("blur",oe),window.removeEventListener("resize",oe)}},[J]);const[z,I]=pp(oe=>{const de=ie().filter(je=>!je.disabled),fe=de.find(je=>je.ref.current===document.activeElement),Te=gp(de,oe,fe);Te&&setTimeout(()=>{var je;return(je=Te.ref.current)==null?void 0:je.focus()})}),F=m.useCallback((oe,de,fe)=>{const Te=!_.current&&!fe;(T.value!==void 0&&T.value===de||Te)&&(X(oe),Te&&(_.current=!0))},[T.value]),re=m.useCallback(()=>D==null?void 0:D.focus(),[D]),he=m.useCallback((oe,de,fe)=>{const Te=!_.current&&!fe;(T.value!==void 0&&T.value===de||Te)&&G(oe)},[T.value]),ge=c==="popper"?Rb:GO,q=ge===Rb?{side:g,sideOffset:v,align:x,alignOffset:y,arrowPadding:b,collisionBoundary:w,collisionPadding:E,sticky:j,hideWhenDetached:C,avoidCollisions:N}:{};return o.jsx(Yw,{scope:s,content:D,viewport:A,onViewportChange:U,itemRefCallback:F,selectedItem:$,onItemLeave:re,itemTextRefCallback:he,focusSelectedItem:Q,selectedItemText:te,position:c,isPositioned:ce,searchRef:z,children:o.jsx(Bu,{as:$O,allowPinchZoom:!0,children:o.jsx(qm,{asChild:!0,trapped:T.open,onMountAutoFocus:oe=>{oe.preventDefault()},onUnmountAutoFocus:Ne(u,oe=>{var de;(de=T.trigger)==null||de.focus({preventScroll:!0}),oe.preventDefault()}),children:o.jsx(Nu,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:oe=>oe.preventDefault(),onDismiss:()=>T.onOpenChange(!1),children:o.jsx(ge,{role:"listbox",id:T.contentId,"data-state":T.open?"open":"closed",dir:T.dir,onContextMenu:oe=>oe.preventDefault(),...M,...q,onPlaced:()=>se(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...M.style},onKeyDown:Ne(M.onKeyDown,oe=>{const de=oe.ctrlKey||oe.altKey||oe.metaKey;if(oe.key==="Tab"&&oe.preventDefault(),!de&&oe.key.length===1&&I(oe.key),["ArrowUp","ArrowDown","Home","End"].includes(oe.key)){let Te=ie().filter(je=>!je.disabled).map(je=>je.ref.current);if(["ArrowUp","End"].includes(oe.key)&&(Te=Te.slice().reverse()),["ArrowUp","ArrowDown"].includes(oe.key)){const je=oe.target,De=Te.indexOf(je);Te=Te.slice(De+1)}setTimeout(()=>H(Te)),oe.preventDefault()}})})})})})})},"SelectContentImpl")),GO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,onPlaced:c,...u}=a,f=ul(zl,s),p=Ku(zl,s),[g,v]=m.useState(null),[x,y]=m.useState(null),b=Xe(l,y),w=hp(s),E=m.useRef(!1),j=m.useRef(!0),{viewport:C,selectedItem:N,selectedItemText:M,focusSelectedItem:T}=p,D=m.useCallback(()=>{if(f.trigger&&f.valueNode&&g&&x&&C&&N&&M){const k=f.trigger.getBoundingClientRect(),$=x.getBoundingClientRect(),X=f.valueNode.getBoundingClientRect(),te=M.getBoundingClientRect();if(f.dir!=="rtl"){const je=te.left-$.left,De=X.left-je,Fe=k.left-De,et=k.width+Fe,le=Math.max(et,$.width),Le=window.innerWidth-ya,Ie=im(De,[ya,Math.max(ya,Le-le)]);g.style.minWidth=et+"px",g.style.left=Ie+"px"}else{const je=$.right-te.right,De=window.innerWidth-X.right-je,Fe=window.innerWidth-k.right-De,et=k.width+Fe,le=Math.max(et,$.width),Le=window.innerWidth-ya,Ie=im(De,[ya,Math.max(ya,Le-le)]);g.style.minWidth=et+"px",g.style.right=Ie+"px"}const G=w(),ie=window.innerHeight-ya*2,ce=C.scrollHeight,se=window.getComputedStyle(x),_=parseInt(se.borderTopWidth,10),H=parseInt(se.paddingTop,10),Q=parseInt(se.borderBottomWidth,10),J=parseInt(se.paddingBottom,10),ee=_+H+ce+J+Q,z=Math.min(N.offsetHeight*5,ee),I=window.getComputedStyle(C),F=parseInt(I.paddingTop,10),re=parseInt(I.paddingBottom,10),he=k.top+k.height/2-ya,ge=ie-he,q=N.offsetHeight/2,oe=N.offsetTop+q,de=_+H+oe,fe=ee-de;if(de<=he){const je=G.length>0&&N===G[G.length-1].ref.current;g.style.bottom="0px";const De=x.clientHeight-C.offsetTop-C.offsetHeight,Fe=Math.max(ge,q+(je?re:0)+De+Q),et=de+Fe;g.style.height=et+"px"}else{const je=G.length>0&&N===G[0].ref.current;g.style.top="0px";const Fe=Math.max(he,_+C.offsetTop+(je?F:0)+q)+fe;g.style.height=Fe+"px",C.scrollTop=de-he+C.offsetTop}g.style.margin=`${ya}px 0`,g.style.minHeight=z+"px",g.style.maxHeight=ie+"px",c==null||c(),requestAnimationFrame(()=>E.current=!0)}},[w,f.trigger,f.valueNode,g,x,C,N,M,f.dir,c]);Xt(()=>D(),[D]);const[O,A]=m.useState();Xt(()=>{x&&A(window.getComputedStyle(x).zIndex)},[x]);const U=m.useCallback(k=>{k&&j.current===!0&&(D(),T==null||T(),j.current=!1)},[D,T]);return o.jsx(KO,{scope:s,contentWrapper:g,shouldExpandOnScrollRef:E,onScrollButtonChange:U,children:o.jsx("div",{ref:v,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:O},children:o.jsx(Ve.div,{...u,ref:b,style:{boxSizing:"border-box",maxHeight:"100%",...u.style}})})})},"SelectItemAlignedPosition")),Rb=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,align:c="start",collisionPadding:u=ya,...f}=a,p=mp(s);return o.jsx(Qm,{...p,...f,ref:l,align:c,collisionPadding:u,style:{boxSizing:"border-box",...f.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[KO,XO]=Il(zl,{}),Nb="SelectViewport",FO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,nonce:c,...u}=a,f=Ku(Nb,s),p=XO(Nb,s),g=Xe(l,f.onViewportChange),v=m.useRef(0);return o.jsxs(o.Fragment,{children:[o.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:c}),o.jsx(Gu.Slot,{scope:s,children:o.jsx(Ve.div,{"data-radix-select-viewport":"",role:"presentation",...u,ref:g,style:{position:"relative",flex:1,overflow:"hidden auto",...u.style},onScroll:Ne(u.onScroll,x=>{const y=x.currentTarget,{contentWrapper:b,shouldExpandOnScrollRef:w}=p;if(w!=null&&w.current&&b){const E=Math.abs(v.current-y.scrollTop);if(E>0){const j=window.innerHeight-ya*2,C=parseFloat(b.style.minHeight),N=parseFloat(b.style.height),M=Math.max(C,N);if(M<j){const T=M+E,D=Math.min(j,T),O=T-D;b.style.height=D+"px",b.style.bottom==="0px"&&(y.scrollTop=O>0?O:0,b.style.justifyContent="flex-end")}}}v.current=y.scrollTop})})})]})},"SelectViewport")),QO="SelectGroup",[K4,X4]=Il(QO),cm="SelectItem",[ZO,Gw]=Il(cm),Kw=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,value:c,disabled:u=!1,textValue:f,...p}=a,g=ul(cm,s),v=Ku(cm,s),x=g.value===c,[y,b]=m.useState(f??""),[w,E]=m.useState(!1),j=ia(D=>{var O;return(O=v.itemRefCallback)==null?void 0:O.call(v,D,c,u)}),C=Xe(l,j),N=La(),M=m.useRef("touch"),T=ht(()=>{u||(g.onValueChange(c),g.onOpenChange(!1))},"handleSelect");return o.jsx(ZO,{scope:s,value:c,disabled:u,textId:N,isSelected:x,onItemTextChange:m.useCallback(D=>{b(O=>O||((D==null?void 0:D.textContent)??"").trim())},[]),children:o.jsx(Gu.ItemSlot,{scope:s,value:c,disabled:u,textValue:y,children:o.jsx(Ve.div,{role:"option","aria-labelledby":N,"data-highlighted":w?"":void 0,"aria-selected":x&&w,"data-state":x?"checked":"unchecked","aria-disabled":u||void 0,"data-disabled":u?"":void 0,tabIndex:u?void 0:-1,...p,ref:C,onFocus:Ne(p.onFocus,()=>E(!0)),onBlur:Ne(p.onBlur,()=>E(!1)),onClick:Ne(p.onClick,()=>{M.current!=="mouse"&&T()}),onPointerUp:Ne(p.onPointerUp,()=>{M.current==="mouse"&&T()}),onPointerDown:Ne(p.onPointerDown,D=>{M.current=D.pointerType}),onPointerMove:Ne(p.onPointerMove,D=>{var O;M.current=D.pointerType,u?(O=v.onItemLeave)==null||O.call(v):M.current==="mouse"&&D.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ne(p.onPointerLeave,D=>{var O;D.currentTarget===document.activeElement&&((O=v.onItemLeave)==null||O.call(v))}),onKeyDown:Ne(p.onKeyDown,D=>{var A;u||D.target!==D.currentTarget||((A=v.searchRef)==null?void 0:A.current)!==""&&D.key===" "||(MO.includes(D.key)&&T(),D.key===" "&&D.preventDefault())})})})})},"SelectItem")),Ic="SelectItemText",JO=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,className:c,style:u,...f}=a,p=ul(Ic,s),g=Ku(Ic,s),v=Gw(Ic,s),x=_O(Ic,s),[y,b]=m.useState(null),w=ia(T=>{var D;return(D=g.itemTextRefCallback)==null?void 0:D.call(g,T,v.value,v.disabled)}),E=Xe(l,b,v.onItemTextChange,w),j=y==null?void 0:y.textContent,C=m.useMemo(()=>o.jsx("option",{value:v.value,disabled:v.disabled,children:j},v.value),[v.disabled,v.value,j]),{onNativeOptionAdd:N,onNativeOptionRemove:M}=x;return Xt(()=>(N(C),()=>M(C)),[N,M,C]),o.jsxs(o.Fragment,{children:[o.jsx(Ve.span,{id:v.textId,...f,ref:E}),v.isSelected&&p.valueNode&&!p.valueNodeHasChildren&&!pi(p.value)?ba.createPortal(f.children,p.valueNode):null]})},"SelectItemText")),WO="SelectItemIndicator",e_=m.forwardRef(ht(function(a,l){const{__scopeSelect:s,...c}=a;return Gw(WO,s).isSelected?o.jsx(Ve.span,{"aria-hidden":!0,...c,ref:l}):null},"SelectItemIndicator")),t_="SelectBubbleInput",n_=m.forwardRef(ht(function({__scopeSelect:a,...l},s){const c=ul(t_,a),{value:u,onValueChange:f,required:p,disabled:g,name:v,autoComplete:x,form:y}=c,{nativeOptions:b,nativeSelectKey:w}=c,E=m.useRef(null),j=Xe(s,E),C=u??"",N=Iw(C),M=Array.from(b).some(T=>(T.props.value??"")==="");return m.useEffect(()=>{const T=E.current;if(!T)return;const D=window.HTMLSelectElement.prototype,A=Object.getOwnPropertyDescriptor(D,"value").set;if(N!==C&&A){const U=new Event("change",{bubbles:!0});A.call(T,C),T.dispatchEvent(U)}},[N,C]),o.jsxs(Ve.select,{"aria-hidden":!0,required:p,tabIndex:-1,name:v,autoComplete:x,disabled:g,form:y,onChange:T=>f(T.target.value),...l,style:{...Pw,...l.style},ref:j,defaultValue:C,children:[pi(u)&&!M?o.jsx("option",{value:""}):null,Array.from(b)]},w)},"SelectBubbleInput"));function Xw(n){return typeof n=="function"}ht(Xw,"isFunction");function pi(n){return n===""||n===void 0}ht(pi,"shouldShowPlaceholder");function pp(n){const a=ia(n),l=m.useRef(""),s=m.useRef(0),c=m.useCallback(f=>{const p=l.current+f;a(p),ht((function g(v){l.current=v,window.clearTimeout(s.current),v!==""&&(s.current=window.setTimeout(()=>g(""),1e3))}),"updateSearch")(p)},[a]),u=m.useCallback(()=>{l.current="",window.clearTimeout(s.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(s.current),[]),[l,c,u]}ht(pp,"useTypeaheadSearch");function gp(n,a,l){const c=a.length>1&&Array.from(a).every(v=>v===a[0])?a[0]:a,u=l?n.indexOf(l):-1;let f=Fw(n,Math.max(u,0));c.length===1&&(f=f.filter(v=>v!==l));const g=f.find(v=>v.textValue.toLowerCase().startsWith(c.toLowerCase()));return g!==l?g:void 0}ht(gp,"findNextItem");function Fw(n,a){return n.map((l,s)=>n[(a+s)%n.length])}ht(Fw,"wrapArray");const Ua=kO,Ba=UO,Sa=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(Vw,{ref:s,className:Ee("flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",n),...l,children:[a,o.jsx(BO,{asChild:!0,children:o.jsx(JE,{className:"h-4 w-4 opacity-50"})})]}));Sa.displayName=Vw.displayName;const ja=m.forwardRef(({className:n,children:a,position:l="popper",...s},c)=>o.jsx(qO,{children:o.jsx($w,{ref:c,className:Ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md",n),position:l,...s,children:o.jsx(FO,{className:Ee("p-1",l==="popper"&&"w-full min-w-[var(--radix-select-trigger-width)]"),children:a})})}));ja.displayName=$w.displayName;const Rt=m.forwardRef(({className:n,children:a,...l},s)=>o.jsxs(Kw,{ref:s,className:Ee("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n),...l,children:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(e_,{children:o.jsx(C0,{className:"h-4 w-4"})})}),o.jsx(JO,{children:a})]}));Rt.displayName=Kw.displayName;var a_=Object.defineProperty,il=(n,a)=>a_(n,"name",{value:a,configurable:!0}),vp="Switch",[r_,F4]=kn(vp),[l_,xp]=r_(vp);function Qw(n){const{__scopeSwitch:a,checked:l,children:s,defaultChecked:c,disabled:u,form:f,name:p,onCheckedChange:g,required:v,value:x="on",internal_do_not_use_render:y}=n,[b,w]=yr({prop:l,defaultProp:c??!1,onChange:g,caller:vp}),[E,j]=m.useState(null),[C,N]=m.useState(null),M=m.useRef(!1),[T,D]=m.useReducer(U=>U+1,0),O=E?!!f||!!E.closest("form"):!0,A={checked:b,setChecked:w,disabled:u,control:E,setControl:j,name:p,form:f,value:x,hasConsumerStoppedPropagationRef:M,userInteractionCount:T,onUserInteraction:D,required:v,defaultChecked:c,isFormControl:O,bubbleInput:C,setBubbleInput:N};return o.jsx(l_,{scope:a,...A,children:Jw(y)?y(A):s})}il(Qw,"SwitchProvider");var s_="SwitchTrigger",o_=m.forwardRef(il(function({__scopeSwitch:a,onClick:l,...s},c){const{control:u,form:f,value:p,disabled:g,checked:v,required:x,setControl:y,setChecked:b,hasConsumerStoppedPropagationRef:w,onUserInteraction:E,isFormControl:j,bubbleInput:C}=xp(s_,a),N=Xe(c,y),M=m.useRef(v);return m.useEffect(()=>{const T=f?u==null?void 0:u.ownerDocument.getElementById(f):u==null?void 0:u.form;if(T instanceof HTMLFormElement){const D=il(()=>b(M.current),"reset");return T.addEventListener("reset",D),()=>T.removeEventListener("reset",D)}},[u,f,b]),o.jsx(Ve.button,{type:"button",role:"switch","aria-checked":v,"aria-required":x,"data-state":yp(v),"data-disabled":g?"":void 0,disabled:g,value:p,...s,ref:N,onClick:Ne(l,T=>{E(),b(D=>!D),C&&j&&(w.current=T.isPropagationStopped(),w.current||T.stopPropagation())})})},"SwitchTrigger")),Zw=m.forwardRef(il(function(a,l){const{__scopeSwitch:s,name:c,checked:u,defaultChecked:f,required:p,disabled:g,value:v,onCheckedChange:x,form:y,...b}=a;return o.jsx(Qw,{__scopeSwitch:s,checked:u,defaultChecked:f,disabled:g,required:p,onCheckedChange:x,name:c,form:y,value:v,internal_do_not_use_render:({isFormControl:w})=>o.jsxs(o.Fragment,{children:[o.jsx(o_,{...b,ref:l,__scopeSwitch:s}),w&&o.jsx(d_,{__scopeSwitch:s})]})})},"Switch")),i_="SwitchThumb",c_=m.forwardRef(il(function(a,l){const{__scopeSwitch:s,...c}=a,u=xp(i_,s);return o.jsx(Ve.span,{"data-state":yp(u.checked),"data-disabled":u.disabled?"":void 0,...c,ref:l})},"SwitchThumb")),u_="SwitchBubbleInput",d_=m.forwardRef(il(function({__scopeSwitch:a,onClick:l,...s},c){const{control:u,hasConsumerStoppedPropagationRef:f,userInteractionCount:p,checked:g,defaultChecked:v,required:x,disabled:y,name:b,value:w,form:E,bubbleInput:j,setBubbleInput:C}=xp(u_,a),N=Xe(c,C),M=_u(u),T=m.useRef(!1),D=m.useRef(g),O=m.useRef(p);m.useEffect(()=>{const U=j;if(!U)return;const k=window.HTMLInputElement.prototype,X=Object.getOwnPropertyDescriptor(k,"checked").set,te=p!==O.current;O.current=p;const G=D.current!==g;D.current=g;const ie=!(te&&f.current);if(G&&X){T.current=!te;const ce=new Event("click",{bubbles:ie});X.call(U,g),U.dispatchEvent(ce),T.current=!1}},[j,g,f,p]);const A=m.useRef(g);return o.jsx(Ve.input,{type:"checkbox","aria-hidden":!0,defaultChecked:v??A.current,required:x,disabled:y,name:b,value:w,form:E,...s,tabIndex:-1,ref:N,onClick:Ne(l,U=>{T.current&&U.stopPropagation()}),style:{...s.style,...M,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Jw(n){return typeof n=="function"}il(Jw,"isFunction");function yp(n){return n?"checked":"unchecked"}il(yp,"getState");const Ca=m.forwardRef(({className:n,...a},l)=>o.jsx(Zw,{className:Ee("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",n),...a,ref:l,children:o.jsx(c_,{className:Ee("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Ca.displayName=Zw.displayName;const Al={name:"",slug:"",type:"openai",baseUrl:"https://api.openai.com",apiKey:"",customHeaders:"",enabled:!0},f_={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function h_(){const[n,a]=m.useState([]),[l,s]=m.useState(!1),[c,u]=m.useState(Al),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(Al),[E,j]=m.useState(null),[C,N]=m.useState(!1),M=async()=>{try{const k=await Se.get("/api/admin/providers");a(k.providers)}catch(k){ve.error(k.message||"Unable to load providers")}};m.useEffect(()=>{M()},[]);const T=async()=>{p(!0);try{let k;if(c.customHeaders.trim())try{k=JSON.parse(c.customHeaders)}catch{throw new Error("Custom headers must be valid JSON object")}await Se.post("/api/admin/providers",{name:c.name,slug:c.slug||void 0,type:c.type,baseUrl:c.baseUrl,apiKey:c.apiKey,customHeaders:k,enabled:c.enabled}),ve.success("Provider created"),s(!1),u(Al),M()}catch(k){ve.error(k.message)}finally{p(!1)}},D=async k=>{v(k);try{const $=await Se.post(`/api/admin/providers/${k}/test`);ve.success($.ok?`Connection OK: ${$.detail}`:`Failed: ${$.detail}`),M()}catch($){ve.error($.message)}finally{v(null)}},O=k=>{y(k.id),w({...Al,name:k.name,slug:k.slug||"",type:k.type,baseUrl:k.baseUrl,apiKey:"",customHeaders:"",enabled:k.enabled})},A=async()=>{if(x){p(!0);try{let k;if(b.customHeaders.trim())try{k=JSON.parse(b.customHeaders)}catch{throw new Error("Custom headers must be valid JSON object")}await Se.patch("/api/admin/providers",{id:x,name:b.name,slug:b.slug||void 0,type:b.type,baseUrl:b.baseUrl,apiKey:b.apiKey||void 0,customHeaders:k,enabled:b.enabled}),ve.success("Provider updated"),y(null),w(Al),M()}catch(k){ve.error(k.message)}finally{p(!1)}}},U=async k=>{N(!0);try{await Se.del(`/api/admin/providers/${k}`),ve.success("Provider removed"),M()}catch($){ve.error($.message)}finally{N(!1),j(null)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Providers",description:"Upstream LLM providers and their credentials",actions:o.jsx("div",{className:"flex gap-2",children:o.jsxs(Mn,{open:l,onOpenChange:s,children:[o.jsx(mi,{asChild:!0,children:o.jsx(me,{children:"Add compatible provider"})}),o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"New provider"}),o.jsx(uu,{children:"API-key or compatible endpoint."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-name",children:"Name"}),o.jsx(Ae,{id:"provider-name",value:c.name,onChange:k=>u({...c,name:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-slug",children:"Slug (optional)"}),o.jsx(Ae,{id:"provider-slug",value:c.slug,onChange:k=>u({...c,slug:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Type"}),o.jsxs(Ua,{value:c.type,onValueChange:k=>u($=>({...$,type:k,baseUrl:f_[k]})),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"openai",children:"OpenAI-compatible"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic-compatible"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-base-url",children:"Base URL"}),o.jsx(Ae,{id:"provider-base-url",value:c.baseUrl,onChange:k=>u({...c,baseUrl:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-api-key",children:"API key"}),o.jsx(Ae,{id:"provider-api-key",type:"password",value:c.apiKey,onChange:k=>u({...c,apiKey:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{htmlFor:"provider-headers",children:"Custom headers (JSON)"}),o.jsx(Ae,{id:"provider-headers",value:c.customHeaders,onChange:k=>u({...c,customHeaders:k.target.value}),placeholder:'{"X-Org":"acme"}'})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:c.enabled,onCheckedChange:k=>u({...c,enabled:k})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),o.jsx(me,{disabled:f||!c.name||!c.apiKey,onClick:T,children:f?"Creating…":"Create"})]})]})]})})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All providers"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Name"}),o.jsx(ye,{children:"Type"}),o.jsx(ye,{children:"Base URL"}),o.jsx(ye,{children:"Models"}),o.jsx(ye,{children:"Health"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{className:"text-right",children:"Actions"})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:7,className:"text-center text-muted-foreground",children:"No providers yet."})}),n.map(k=>o.jsxs(We,{children:[o.jsxs(pe,{className:"font-medium",children:[k.name," ",o.jsx("span",{className:"text-xs text-muted-foreground",children:k.slug})]}),o.jsx(pe,{children:o.jsx(Qe,{variant:"outline",children:k.type})}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:k.baseUrl}),o.jsx(pe,{children:k.modelCount}),o.jsx(pe,{children:o.jsx(Qe,{variant:k.health==="healthy"?"success":k.health==="down"?"destructive":"secondary",children:k.health})}),o.jsx(pe,{children:k.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex justify-end gap-1",children:[o.jsx(me,{size:"sm",variant:"outline",disabled:g===k.id,onClick:()=>D(k.id),children:o.jsx(A0,{className:"h-3 w-3"})}),o.jsx(me,{size:"sm",variant:"outline",onClick:()=>O(k),children:"✎"}),o.jsx(me,{size:"sm",variant:"outline",onClick:()=>j(k.id),children:o.jsx(ju,{className:"h-3 w-3"})})]})})]},k.id))]})]})})]}),o.jsx(Mn,{open:!!x,onOpenChange:k=>{k||(y(null),w(Al))},children:o.jsxs(vn,{children:[o.jsx(xn,{children:o.jsx(yn,{children:"Edit provider"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:b.name,onChange:k=>w({...b,name:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional)"}),o.jsx(Ae,{value:b.slug,onChange:k=>w({...b,slug:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Type"}),o.jsxs(Ua,{value:b.type,onValueChange:k=>w({...b,type:k}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"openai",children:"OpenAI-compatible"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic-compatible"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Base URL"}),o.jsx(Ae,{value:b.baseUrl,onChange:k=>w({...b,baseUrl:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"API key (leave empty to keep current)"}),o.jsx(Ae,{type:"password",value:b.apiKey,onChange:k=>w({...b,apiKey:k.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Custom headers (JSON)"}),o.jsx(Ae,{value:b.customHeaders,onChange:k=>w({...b,customHeaders:k.target.value}),placeholder:'{"X-Org":"acme"}'})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:b.enabled,onCheckedChange:k=>w({...b,enabled:k})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>{y(null),w(Al)},children:"Cancel"}),o.jsx(me,{disabled:f||!b.name,onClick:A,children:"Save changes"})]})]})}),o.jsx(up,{open:!!E,onOpenChange:k=>{k||j(null)},children:o.jsxs(Pu,{children:[o.jsxs(dp,{children:[o.jsx(qu,{children:"Delete provider?"}),o.jsx(Vu,{children:"This permanently removes the provider, its models, and dependent routing configuration."})]}),o.jsxs(fp,{children:[o.jsx(Yu,{children:"Cancel"}),o.jsx($u,{disabled:C,onClick:k=>{E&&(k.preventDefault(),U(E))},children:C?"Deleting…":"Delete"})]})]})})]})}var m_=Object.defineProperty,Sr=(n,a)=>m_(n,"name",{value:a,configurable:!0}),bp="Checkbox",[p_,Q4]=kn(bp),[g_,wp]=p_(bp);function Ww(n){const{__scopeCheckbox:a,checked:l,children:s,defaultChecked:c,disabled:u,form:f,name:p,onCheckedChange:g,required:v,value:x="on",internal_do_not_use_render:y}=n,[b,w]=yr({prop:l,defaultProp:c??!1,onChange:g,caller:bp}),[E,j]=m.useState(null),[C,N]=m.useState(null),M=m.useRef(!1),[T,D]=m.useReducer(U=>U+1,0),O=E?!!f||!!E.closest("form"):!0,A={checked:b,disabled:u,setChecked:w,control:E,setControl:j,name:p,form:f,value:x,hasConsumerStoppedPropagationRef:M,userInteractionCount:T,onUserInteraction:D,required:v,defaultChecked:vr(c)?!1:c,isFormControl:O,bubbleInput:C,setBubbleInput:N};return o.jsx(g_,{scope:a,...A,children:tS(y)?y(A):s})}Sr(Ww,"CheckboxProvider");var v_="CheckboxTrigger",x_=m.forwardRef(Sr(function({__scopeCheckbox:a,onKeyDown:l,onClick:s,...c},u){const{control:f,value:p,disabled:g,checked:v,required:x,setControl:y,setChecked:b,hasConsumerStoppedPropagationRef:w,onUserInteraction:E,isFormControl:j,bubbleInput:C}=wp(v_,a),N=Xe(u,y),M=m.useRef(v);return m.useEffect(()=>{const T=f==null?void 0:f.form;if(T){const D=Sr(()=>b(M.current),"reset");return T.addEventListener("reset",D),()=>T.removeEventListener("reset",D)}},[f,b]),o.jsx(Ve.button,{type:"button",role:"checkbox","aria-checked":vr(v)?"mixed":v,"aria-required":x,"data-state":Sp(v),"data-disabled":g?"":void 0,disabled:g,value:p,...c,ref:N,onKeyDown:Ne(l,T=>{T.key==="Enter"&&T.preventDefault()}),onClick:Ne(s,T=>{E(),b(D=>vr(D)?!0:!D),C&&j&&(w.current=T.isPropagationStopped(),w.current||T.stopPropagation())})})},"CheckboxTrigger")),eS=m.forwardRef(Sr(function(a,l){const{__scopeCheckbox:s,name:c,checked:u,defaultChecked:f,required:p,disabled:g,value:v,onCheckedChange:x,form:y,...b}=a;return o.jsx(Ww,{__scopeCheckbox:s,checked:u,defaultChecked:f,disabled:g,required:p,onCheckedChange:x,name:c,form:y,value:v,internal_do_not_use_render:({isFormControl:w})=>o.jsxs(o.Fragment,{children:[o.jsx(x_,{...b,ref:l,__scopeCheckbox:s}),w&&o.jsx(S_,{__scopeCheckbox:s})]})})},"Checkbox")),y_="CheckboxIndicator",b_=m.forwardRef(Sr(function(a,l){const{__scopeCheckbox:s,forceMount:c,...u}=a,f=wp(y_,s);return o.jsx(Cr,{present:c||vr(f.checked)||f.checked===!0,children:o.jsx(Ve.span,{"data-state":Sp(f.checked),"data-disabled":f.disabled?"":void 0,...u,ref:l,style:{pointerEvents:"none",...a.style}})})},"CheckboxIndicator")),w_="CheckboxBubbleInput",S_=m.forwardRef(Sr(function({__scopeCheckbox:a,onClick:l,...s},c){const{control:u,hasConsumerStoppedPropagationRef:f,userInteractionCount:p,checked:g,defaultChecked:v,required:x,disabled:y,name:b,value:w,form:E,bubbleInput:j,setBubbleInput:C}=wp(w_,a),N=Xe(c,C),M=_u(u),T=m.useRef(!1),D=m.useRef(g),O=m.useRef(p);m.useEffect(()=>{const U=j;if(!U)return;const k=window.HTMLInputElement.prototype,X=Object.getOwnPropertyDescriptor(k,"checked").set,te=p!==O.current;O.current=p;const G=D.current!==g;D.current=g;const ie=!(te&&f.current);if(G&&X){T.current=!te;const ce=new Event("click",{bubbles:ie});U.indeterminate=vr(g),X.call(U,vr(g)?!1:g),U.dispatchEvent(ce),T.current=!1}},[j,g,f,p]);const A=m.useRef(vr(g)?!1:g);return o.jsx(Ve.input,{type:"checkbox","aria-hidden":!0,defaultChecked:v??A.current,required:x,disabled:y,name:b,value:w,form:E,...s,tabIndex:-1,ref:N,onClick:Ne(l,U=>{T.current&&U.stopPropagation()}),style:{...s.style,...M,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function tS(n){return typeof n=="function"}Sr(tS,"isFunction");function vr(n){return n==="indeterminate"}Sr(vr,"isIndeterminate");function Sp(n){return vr(n)?"indeterminate":n?"checked":"unchecked"}Sr(Sp,"getState");const jp=m.forwardRef(({className:n,...a},l)=>o.jsx(eS,{ref:l,className:Ee("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",n),...a,children:o.jsx(b_,{className:Ee("flex items-center justify-center text-current"),children:o.jsx(C0,{className:"h-3.5 w-3.5"})})}));jp.displayName=eS.displayName;const um=["image_input","audio_input","tools","structured_output","reasoning","chat","streaming"],j_=["unknown","yes","no"];function C_(n,a){return n[a]===!0?"yes":n[a]===!1?"no":"unknown"}function E_(n){const a={};for(const l of um)a[l]=n[l]==="yes"?!0:n[l]==="no"?!1:null;return a}function R_(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState("all"),[f,p]=m.useState(!1),[g,v]=m.useState(""),[x,y]=m.useState([]),[b,w]=m.useState(new Set),[E,j]=m.useState(!1),[C,N]=m.useState(""),[M,T]=m.useState(""),[D,O]=m.useState(null),[A,U]=m.useState(!1),[k,$]=m.useState(null),[X,te]=m.useState(null),[G,ie]=m.useState(null),[ce,se]=m.useState({}),[_,H]=m.useState(!1),Q=q=>{const oe={};for(const de of um)oe[de]=C_(q.capabilities,de);se(oe),ie(q)},J=async()=>{if(G){H(!0);try{await Se.patch("/api/admin/models",{id:G.id,capabilities:E_(ce)}),ve.success("Capabilities updated"),ie(null),ee()}catch(q){ve.error(q.message)}finally{H(!1)}}},ee=async()=>{const[q,oe]=await Promise.all([Se.get("/api/admin/models"),Se.get("/api/admin/providers")]);a(q.models),s(oe.providers)};m.useEffect(()=>{ee()},[]);const z=n.filter(q=>!(c!=="all"&&q.providerId!==c||C&&!q.publicModelId.toLowerCase().includes(C.toLowerCase()))),I=x.filter(q=>{if(!M)return!0;const oe=M.toLowerCase();return q.upstreamId.toLowerCase().includes(oe)||q.displayName.toLowerCase().includes(oe)}),F=async()=>{if(g){j(!0);try{const q=await Se.post(`/api/admin/providers/${g}/discover`);y(q.models),w(new Set)}catch(q){ve.error(q.message)}finally{j(!1)}}},re=async()=>{if(b.size!==0)try{const q=await Se.post("/api/admin/models/import",{providerId:g,modelIds:Array.from(b)});ve.success(`Imported ${q.imported} of ${q.requested}`),p(!1),y([]),w(new Set),ee()}catch(q){ve.error(q.message)}},he=async()=>{if(X)try{await Se.del(`/api/admin/models/${X.id}`),ve.success("Model deleted"),te(null),ee()}catch(q){ve.error(q.message)}},ge=async q=>{var de,fe,Te;O(q),U(!0);const oe=Date.now();$({phase:"streaming",startedAt:oe,text:"",progress:{}});try{const je=await ru(`/api/admin/models/${q}/test-stream`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});if(!je.ok){const Ie=await je.text().catch(()=>"");$({phase:"error",model:q,error:`HTTP ${je.status}: ${Ie}`});return}const De=(de=je.body)==null?void 0:de.getReader();if(!De){$({phase:"error",model:q,error:"No response body"});return}const Fe=new TextDecoder;let et="",le="",Le=!1;for(;!Le;){const{value:Ie,done:kt}=await De.read();Le=kt,Ie&&(et+=Fe.decode(Ie,{stream:!0}));let St;for(;(St=et.indexOf(`
|
|
342
342
|
|
|
343
343
|
`))>=0;){const Ft=et.slice(0,St);et=et.slice(St+2);const on=Ft.split(`
|
|
344
|
-
`);let Qt="",jt="";for(const fn of on)fn.startsWith("event: ")?Qt=fn.slice(7):fn.startsWith("data: ")&&(jt=fn.slice(6));if(jt){if(Qt===""||Qt==="message")try{const Mt=(fe=JSON.parse(jt).choices)==null?void 0:fe[0];(Te=Mt==null?void 0:Mt.delta)!=null&&Te.content&&(le+=Mt.delta.content),$(At=>{if(!At||At.phase!=="streaming")return At;const cn=Date.now()-oe,fa=At.progress.ttftMs??cn;return{...At,text:le,progress:{ttftMs:fa,elapsedMs:cn}}})}catch{}if(Qt==="test_meta")try{const fn=JSON.parse(jt);$({phase:"done",model:q,result:fn,text:le})}catch{}if(Qt==="test_error")try{const fn=JSON.parse(jt);$({phase:"error",model:q,error:fn.message})}catch{}}}}$(Ie=>!Ie||Ie.phase==="streaming"?{phase:"error",model:q,error:"Stream ended unexpectedly"}:Ie)}catch(je){$({phase:"error",model:q,error:je.message})}finally{O(null)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Models",description:"Physical models imported from providers",actions:o.jsxs(Mn,{open:f,onOpenChange:p,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{variant:"outline",children:[o.jsx(E0,{className:"mr-1 h-4 w-4"})," Fetch models"]})}),o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Discover models"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("div",{className:"flex-1",children:o.jsxs(Ua,{value:g,onValueChange:v,children:[o.jsx(Sa,{children:o.jsx(Ba,{placeholder:"Choose provider"})}),o.jsx(ja,{children:l.map(q=>o.jsx(Rt,{value:q.id,children:q.name},q.id))})]})}),o.jsx(me,{onClick:F,disabled:!g||E,children:E?"Fetching…":"Fetch"})]}),x.length>0&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"flex items-center gap-2 flex-1",children:o.jsxs("div",{className:"relative flex-1",children:[o.jsx(D0,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(Ae,{className:"pl-8",placeholder:"Search models…",value:M,onChange:q=>T(q.target.value)}),M&&o.jsx("button",{className:"absolute right-2 top-2.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:o.jsx(Cu,{className:"h-4 w-4"})})]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:[I.length," / ",x.length," · ",b.size," selected"]}),o.jsx(me,{variant:"outline",size:"sm",onClick:()=>w(new Set(I.filter(q=>!q.alreadyImported).map(q=>q.upstreamId))),children:"Select All (new)"}),o.jsx(me,{variant:"outline",size:"sm",onClick:()=>w(new Set),children:"Clear"})]})]}),o.jsx("div",{className:"max-h-80 space-y-1 overflow-auto rounded border p-2",children:I.length===0&&x.length>0?o.jsx("div",{className:"text-center text-sm text-muted-foreground py-4",children:"No models match your search."}):I.map(q=>o.jsxs("label",{className:"flex items-center gap-2 rounded p-1 text-sm hover:bg-accent",children:[o.jsx(jp,{checked:b.has(q.upstreamId),onCheckedChange:oe=>{const de=new Set(b);oe?de.add(q.upstreamId):de.delete(q.upstreamId),w(de)}}),o.jsx("span",{className:"font-mono text-xs",children:q.upstreamId}),q.alreadyImported&&o.jsx(Qe,{variant:"secondary",children:"imported"})]},q.upstreamId))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsxs(me,{disabled:b.size===0,onClick:re,children:["Import ",b.size||""]})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All models"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsxs(lt,{children:[o.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[o.jsxs(Ua,{value:c,onValueChange:u,children:[o.jsx(Sa,{className:"w-56",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"All providers"}),l.map(q=>o.jsx(Rt,{value:q.id,children:q.name},q.id))]})]}),o.jsx(Ae,{className:"max-w-xs",placeholder:"Search public ID",value:C,onChange:q=>N(q.target.value)})]}),o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Public ID"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Upstream ID"}),o.jsx(ye,{children:"Capabilities"}),o.jsx(ye,{children:"Available"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[z.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:7,className:"text-center text-muted-foreground",children:"No models"})}),z.map(q=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:q.publicModelId}),o.jsx(pe,{children:q.providerSlug}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:q.upstreamModelId}),o.jsx(pe,{className:"space-x-1",children:Object.entries(q.capabilities).filter(([,oe])=>oe===!0).slice(0,4).map(([oe])=>o.jsx(Qe,{variant:"outline",className:"mr-1",children:oe},oe))}),o.jsx(pe,{children:q.upstreamAvailable?o.jsx(Qe,{variant:"success",children:"up"}):o.jsx(Qe,{variant:"destructive",children:"down"})}),o.jsx(pe,{children:q.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>Q(q),disabled:D!==null,children:[o.jsx(vR,{className:"h-3.5 w-3.5"})," Capabilities"]}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>void ge(q.id),disabled:D!==null,children:[D===q.id?o.jsx(_s,{className:"h-3.5 w-3.5 animate-spin"}):o.jsx(iR,{className:"h-3.5 w-3.5"})," Test"]}),o.jsxs(me,{size:"sm",variant:"destructive",onClick:()=>te(q),disabled:D!==null,children:[o.jsx(ju,{className:"h-3.5 w-3.5"})," Xoá"]})]})})]},q.id))]})]})]})]}),o.jsx(Mn,{open:!!X,onOpenChange:q=>{q||te(null)},children:o.jsxs(vn,{className:"max-w-md",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Xoá model"})}),o.jsxs("div",{className:"space-y-2 text-sm",children:[o.jsxs("p",{children:["Bạn có chắc muốn xoá model ",o.jsx("span",{className:"font-mono",children:X==null?void 0:X.publicModelId}),"?"]}),o.jsx("p",{className:"text-muted-foreground",children:"Model đang được dùng trong combo sẽ bị soft-disable (vô hiệu hoá) thay vì xoá hẳn, để giữ lịch sử và tham chiếu combo."})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>te(null),children:"Huỷ"}),o.jsx(me,{variant:"destructive",onClick:he,children:"Xoá"})]})]})}),o.jsx(Mn,{open:G!==null,onOpenChange:q=>{q||ie(null)},children:o.jsxs(vn,{className:"max-w-lg",children:[o.jsx(xn,{children:o.jsxs(yn,{children:["Capabilities — ",G==null?void 0:G.publicModelId]})}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.jsx("strong",{children:"Unknown"})," means the router has no verified answer and will attempt the request."," ",o.jsx("strong",{children:"No"})," blocks requests needing that capability (HTTP 400/502 before any upstream call)."]}),um.map(q=>{var de;const oe=(de=G==null?void 0:G.discoveredCapabilities)==null?void 0:de[q];return o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded px-1 py-1 text-sm hover:bg-accent",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("code",{className:"text-xs",children:q}),o.jsx("span",{className:"text-xs text-muted-foreground",children:oe===void 0?"discovered: unknown":`discovered: ${String(oe)}`})]}),o.jsx("div",{className:"flex gap-1",children:j_.map(fe=>o.jsx(me,{size:"sm",variant:ce[q]===fe?"default":"outline",onClick:()=>se(Te=>({...Te,[q]:fe})),children:fe==="unknown"?"Unknown":fe==="yes"?"Yes":"No"},fe))})]},q)})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>ie(null),children:"Huỷ"}),o.jsx(me,{onClick:J,disabled:_,children:_?"Saving…":"Lưu"})]})]})}),o.jsx(Mn,{open:A,onOpenChange:U,children:o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Kết quả test model"})}),k&&k.phase==="streaming"&&o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx(_s,{className:"h-4 w-4 animate-spin"})," Đang stream…",o.jsxs("span",{className:"font-mono text-xs text-muted-foreground/60",children:["TTFT ",k.progress.ttftMs!=null?`${k.progress.ttftMs} ms`:"…"]}),o.jsxs("span",{className:"font-mono text-xs text-muted-foreground/60",children:["· ",k.progress.elapsedMs!=null?`${k.progress.elapsedMs} ms`:"…"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Phản hồi (streaming)"}),o.jsxs("div",{className:"max-h-60 overflow-auto whitespace-pre-wrap rounded border bg-muted p-3 font-mono text-xs",children:[k.text||o.jsx("span",{className:"text-muted-foreground/60 animate-pulse",children:"waiting for first token…"}),k.phase==="streaming"&&o.jsx("span",{className:"ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-primary/70"})]})]})]}),k&&k.phase==="done"&&o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsx(Qe,{variant:k.result.success?"success":"destructive",children:k.result.success?"Thành công":"Thất bại"}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Thời gian phản hồi"}),o.jsxs("div",{className:"font-mono",children:[k.result.latencyMs," ms"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"TTFT"}),o.jsx("div",{className:"font-mono",children:k.result.ttftMs!=null?`${k.result.ttftMs} ms`:"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Tokens (in / out)"}),o.jsxs("div",{className:"font-mono",children:[k.result.usage.input," / ",k.result.usage.output]})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Phản hồi của model"}),o.jsx("div",{className:"max-h-60 overflow-auto whitespace-pre-wrap rounded border bg-muted p-3 font-mono text-xs",children:k.text||k.result.text||"(trống)"})]}),k.result.attempts.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Attempts"}),o.jsx("div",{className:"space-y-1",children:k.result.attempts.map((q,oe)=>o.jsxs("div",{className:"flex items-center gap-2 rounded border p-2 text-xs",children:[o.jsx(Qe,{variant:q.success?"success":"destructive",children:q.success?"OK":"FAIL"}),o.jsxs("span",{className:"font-mono",children:[q.providerName," / ",q.modelId]}),o.jsxs("span",{className:"text-muted-foreground",children:[q.latencyMs," ms"]}),q.failureReason&&o.jsx("span",{className:"text-destructive",children:q.failureReason})]},oe))})]})]}),k&&k.phase==="error"&&o.jsxs("div",{className:"space-y-2 text-sm",children:[o.jsx(Qe,{variant:"destructive",children:"Thất bại"}),o.jsx("p",{className:"text-destructive",children:k.error})]}),o.jsx(An,{children:o.jsx(me,{variant:"outline",onClick:()=>U(!1),children:"Đóng"})})]})})]})}function N_(){for(var n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];return m.useMemo(()=>s=>{a.forEach(c=>c(s))},a)}const Xu=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Xs(n){const a=Object.prototype.toString.call(n);return a==="[object Window]"||a==="[object global]"}function Cp(n){return"nodeType"in n}function zn(n){var a,l;return n?Xs(n)?n:Cp(n)&&(a=(l=n.ownerDocument)==null?void 0:l.defaultView)!=null?a:window:window}function Ep(n){const{Document:a}=zn(n);return n instanceof a}function gi(n){return Xs(n)?!1:n instanceof zn(n).HTMLElement}function nS(n){return n instanceof zn(n).SVGElement}function Fs(n){return n?Xs(n)?n.document:Cp(n)?Ep(n)?n:gi(n)||nS(n)?n.ownerDocument:document:document:document}const qa=Xu?m.useLayoutEffect:m.useEffect;function Rp(n){const a=m.useRef(n);return qa(()=>{a.current=n}),m.useCallback(function(){for(var l=arguments.length,s=new Array(l),c=0;c<l;c++)s[c]=arguments[c];return a.current==null?void 0:a.current(...s)},[])}function T_(){const n=m.useRef(null),a=m.useCallback((s,c)=>{n.current=setInterval(s,c)},[]),l=m.useCallback(()=>{n.current!==null&&(clearInterval(n.current),n.current=null)},[]);return[a,l]}function ti(n,a){a===void 0&&(a=[n]);const l=m.useRef(n);return qa(()=>{l.current!==n&&(l.current=n)},a),l}function vi(n,a){const l=m.useRef();return m.useMemo(()=>{const s=n(l.current);return l.current=s,s},[...a])}function du(n){const a=Rp(n),l=m.useRef(null),s=m.useCallback(c=>{c!==l.current&&(a==null||a(c,l.current)),l.current=c},[]);return[l,s]}function dm(n){const a=m.useRef();return m.useEffect(()=>{a.current=n},[n]),a.current}let _h={};function xi(n,a){return m.useMemo(()=>{if(a)return a;const l=_h[n]==null?0:_h[n]+1;return _h[n]=l,n+"-"+l},[n,a])}function aS(n){return function(a){for(var l=arguments.length,s=new Array(l>1?l-1:0),c=1;c<l;c++)s[c-1]=arguments[c];return s.reduce((u,f)=>{const p=Object.entries(f);for(const[g,v]of p){const x=u[g];x!=null&&(u[g]=x+n*v)}return u},{...a})}}const Us=aS(1),ni=aS(-1);function M_(n){return"clientX"in n&&"clientY"in n}function Np(n){if(!n)return!1;const{KeyboardEvent:a}=zn(n.target);return a&&n instanceof a}function A_(n){if(!n)return!1;const{TouchEvent:a}=zn(n.target);return a&&n instanceof a}function fm(n){if(A_(n)){if(n.touches&&n.touches.length){const{clientX:a,clientY:l}=n.touches[0];return{x:a,y:l}}else if(n.changedTouches&&n.changedTouches.length){const{clientX:a,clientY:l}=n.changedTouches[0];return{x:a,y:l}}}return M_(n)?{x:n.clientX,y:n.clientY}:null}const fu=Object.freeze({Translate:{toString(n){if(!n)return;const{x:a,y:l}=n;return"translate3d("+(a?Math.round(a):0)+"px, "+(l?Math.round(l):0)+"px, 0)"}},Scale:{toString(n){if(!n)return;const{scaleX:a,scaleY:l}=n;return"scaleX("+a+") scaleY("+l+")"}},Transform:{toString(n){if(n)return[fu.Translate.toString(n),fu.Scale.toString(n)].join(" ")}},Transition:{toString(n){let{property:a,duration:l,easing:s}=n;return a+" "+l+"ms "+s}}}),Tb="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function D_(n){return n.matches(Tb)?n:n.querySelector(Tb)}const O_={display:"none"};function __(n){let{id:a,value:l}=n;return ue.createElement("div",{id:a,style:O_},l)}function k_(n){let{id:a,announcement:l,ariaLiveType:s="assertive"}=n;const c={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ue.createElement("div",{id:a,style:c,role:"status","aria-live":s,"aria-atomic":!0},l)}function z_(){const[n,a]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&a(s)},[]),announcement:n}}const rS=m.createContext(null);function L_(n){const a=m.useContext(rS);m.useEffect(()=>{if(!a)throw new Error("useDndMonitor must be used within a children of <DndContext>");return a(n)},[n,a])}function U_(){const[n]=m.useState(()=>new Set),a=m.useCallback(s=>(n.add(s),()=>n.delete(s)),[n]);return[m.useCallback(s=>{let{type:c,event:u}=s;n.forEach(f=>{var p;return(p=f[c])==null?void 0:p.call(f,u)})},[n]),a]}const B_={draggable:`
|
|
344
|
+
`);let Qt="",jt="";for(const fn of on)fn.startsWith("event: ")?Qt=fn.slice(7):fn.startsWith("data: ")&&(jt=fn.slice(6));if(jt){if(Qt===""||Qt==="message")try{const Mt=(fe=JSON.parse(jt).choices)==null?void 0:fe[0];(Te=Mt==null?void 0:Mt.delta)!=null&&Te.content&&(le+=Mt.delta.content),$(At=>{if(!At||At.phase!=="streaming")return At;const cn=Date.now()-oe,fa=At.progress.ttftMs??cn;return{...At,text:le,progress:{ttftMs:fa,elapsedMs:cn}}})}catch{}if(Qt==="test_meta")try{const fn=JSON.parse(jt);$({phase:"done",model:q,result:fn,text:le})}catch{}if(Qt==="test_error")try{const fn=JSON.parse(jt);$({phase:"error",model:q,error:fn.message})}catch{}}}}$(Ie=>!Ie||Ie.phase==="streaming"?{phase:"error",model:q,error:"Stream ended unexpectedly"}:Ie)}catch(je){$({phase:"error",model:q,error:je.message})}finally{O(null)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Models",description:"Physical models imported from providers",actions:o.jsxs(Mn,{open:f,onOpenChange:p,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{variant:"outline",children:[o.jsx(E0,{className:"mr-1 h-4 w-4"})," Fetch models"]})}),o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Discover models"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("div",{className:"flex-1",children:o.jsxs(Ua,{value:g,onValueChange:v,children:[o.jsx(Sa,{children:o.jsx(Ba,{placeholder:"Choose provider"})}),o.jsx(ja,{children:l.map(q=>o.jsx(Rt,{value:q.id,children:q.name},q.id))})]})}),o.jsx(me,{onClick:F,disabled:!g||E,children:E?"Fetching…":"Fetch"})]}),x.length>0&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"flex items-center gap-2 flex-1",children:o.jsxs("div",{className:"relative flex-1",children:[o.jsx(D0,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(Ae,{className:"pl-8",placeholder:"Search models…",value:M,onChange:q=>T(q.target.value)}),M&&o.jsx("button",{className:"absolute right-2 top-2.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:o.jsx(Cu,{className:"h-4 w-4"})})]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:[I.length," / ",x.length," · ",b.size," selected"]}),o.jsx(me,{variant:"outline",size:"sm",onClick:()=>w(new Set(I.filter(q=>!q.alreadyImported).map(q=>q.upstreamId))),children:"Select All (new)"}),o.jsx(me,{variant:"outline",size:"sm",onClick:()=>w(new Set),children:"Clear"})]})]}),o.jsx("div",{className:"max-h-80 space-y-1 overflow-auto rounded border p-2",children:I.length===0&&x.length>0?o.jsx("div",{className:"text-center text-sm text-muted-foreground py-4",children:"No models match your search."}):I.map(q=>o.jsxs("label",{className:"flex items-center gap-2 rounded p-1 text-sm hover:bg-accent",children:[o.jsx(jp,{checked:b.has(q.upstreamId),onCheckedChange:oe=>{const de=new Set(b);oe?de.add(q.upstreamId):de.delete(q.upstreamId),w(de)}}),o.jsx("span",{className:"font-mono text-xs",children:q.upstreamId}),q.alreadyImported&&o.jsx(Qe,{variant:"secondary",children:"imported"})]},q.upstreamId))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsxs(me,{disabled:b.size===0,onClick:re,children:["Import ",b.size||""]})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All models"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsxs(lt,{children:[o.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[o.jsxs(Ua,{value:c,onValueChange:u,children:[o.jsx(Sa,{className:"w-56",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"All providers"}),l.map(q=>o.jsx(Rt,{value:q.id,children:q.name},q.id))]})]}),o.jsx(Ae,{className:"max-w-xs",placeholder:"Search public ID",value:C,onChange:q=>N(q.target.value)})]}),o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Public ID"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Upstream ID"}),o.jsx(ye,{children:"Capabilities"}),o.jsx(ye,{children:"Available"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[z.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:7,className:"text-center text-muted-foreground",children:"No models"})}),z.map(q=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:q.publicModelId}),o.jsx(pe,{children:q.providerSlug}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:q.upstreamModelId}),o.jsx(pe,{className:"space-x-1",children:Object.entries(q.capabilities).filter(([,oe])=>oe===!0).slice(0,4).map(([oe])=>o.jsx(Qe,{variant:"outline",className:"mr-1",children:oe},oe))}),o.jsx(pe,{children:q.upstreamAvailable?o.jsx(Qe,{variant:"success",children:"up"}):o.jsx(Qe,{variant:"destructive",children:"down"})}),o.jsx(pe,{children:q.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>Q(q),disabled:D!==null,children:[o.jsx(vR,{className:"h-3.5 w-3.5"})," Capabilities"]}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>void ge(q.id),disabled:D!==null,children:[D===q.id?o.jsx(_s,{className:"h-3.5 w-3.5 animate-spin"}):o.jsx(iR,{className:"h-3.5 w-3.5"})," Test"]}),o.jsxs(me,{size:"sm",variant:"destructive",onClick:()=>te(q),disabled:D!==null,children:[o.jsx(ju,{className:"h-3.5 w-3.5"})," Xoá"]})]})})]},q.id))]})]})]})]}),o.jsx(Mn,{open:!!X,onOpenChange:q=>{q||te(null)},children:o.jsxs(vn,{className:"max-w-md",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Xoá model"})}),o.jsxs("div",{className:"space-y-2 text-sm",children:[o.jsxs("p",{children:["Bạn có chắc muốn xoá model ",o.jsx("span",{className:"font-mono",children:X==null?void 0:X.publicModelId}),"?"]}),o.jsx("p",{className:"text-muted-foreground",children:"Model sẽ bị xoá khỏi combo, alias, permission và cache trước khi xoá hẳn."})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>te(null),children:"Huỷ"}),o.jsx(me,{variant:"destructive",onClick:he,children:"Xoá"})]})]})}),o.jsx(Mn,{open:G!==null,onOpenChange:q=>{q||ie(null)},children:o.jsxs(vn,{className:"max-w-lg",children:[o.jsx(xn,{children:o.jsxs(yn,{children:["Capabilities — ",G==null?void 0:G.publicModelId]})}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.jsx("strong",{children:"Unknown"})," means the router has no verified answer and will attempt the request."," ",o.jsx("strong",{children:"No"})," blocks requests needing that capability (HTTP 400/502 before any upstream call)."]}),um.map(q=>{var de;const oe=(de=G==null?void 0:G.discoveredCapabilities)==null?void 0:de[q];return o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded px-1 py-1 text-sm hover:bg-accent",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("code",{className:"text-xs",children:q}),o.jsx("span",{className:"text-xs text-muted-foreground",children:oe===void 0?"discovered: unknown":`discovered: ${String(oe)}`})]}),o.jsx("div",{className:"flex gap-1",children:j_.map(fe=>o.jsx(me,{size:"sm",variant:ce[q]===fe?"default":"outline",onClick:()=>se(Te=>({...Te,[q]:fe})),children:fe==="unknown"?"Unknown":fe==="yes"?"Yes":"No"},fe))})]},q)})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>ie(null),children:"Huỷ"}),o.jsx(me,{onClick:J,disabled:_,children:_?"Saving…":"Lưu"})]})]})}),o.jsx(Mn,{open:A,onOpenChange:U,children:o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Kết quả test model"})}),k&&k.phase==="streaming"&&o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx(_s,{className:"h-4 w-4 animate-spin"})," Đang stream…",o.jsxs("span",{className:"font-mono text-xs text-muted-foreground/60",children:["TTFT ",k.progress.ttftMs!=null?`${k.progress.ttftMs} ms`:"…"]}),o.jsxs("span",{className:"font-mono text-xs text-muted-foreground/60",children:["· ",k.progress.elapsedMs!=null?`${k.progress.elapsedMs} ms`:"…"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Phản hồi (streaming)"}),o.jsxs("div",{className:"max-h-60 overflow-auto whitespace-pre-wrap rounded border bg-muted p-3 font-mono text-xs",children:[k.text||o.jsx("span",{className:"text-muted-foreground/60 animate-pulse",children:"waiting for first token…"}),k.phase==="streaming"&&o.jsx("span",{className:"ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-primary/70"})]})]})]}),k&&k.phase==="done"&&o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsx(Qe,{variant:k.result.success?"success":"destructive",children:k.result.success?"Thành công":"Thất bại"}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Thời gian phản hồi"}),o.jsxs("div",{className:"font-mono",children:[k.result.latencyMs," ms"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"TTFT"}),o.jsx("div",{className:"font-mono",children:k.result.ttftMs!=null?`${k.result.ttftMs} ms`:"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Tokens (in / out)"}),o.jsxs("div",{className:"font-mono",children:[k.result.usage.input," / ",k.result.usage.output]})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Phản hồi của model"}),o.jsx("div",{className:"max-h-60 overflow-auto whitespace-pre-wrap rounded border bg-muted p-3 font-mono text-xs",children:k.text||k.result.text||"(trống)"})]}),k.result.attempts.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Attempts"}),o.jsx("div",{className:"space-y-1",children:k.result.attempts.map((q,oe)=>o.jsxs("div",{className:"flex items-center gap-2 rounded border p-2 text-xs",children:[o.jsx(Qe,{variant:q.success?"success":"destructive",children:q.success?"OK":"FAIL"}),o.jsxs("span",{className:"font-mono",children:[q.providerName," / ",q.modelId]}),o.jsxs("span",{className:"text-muted-foreground",children:[q.latencyMs," ms"]}),q.failureReason&&o.jsx("span",{className:"text-destructive",children:q.failureReason})]},oe))})]})]}),k&&k.phase==="error"&&o.jsxs("div",{className:"space-y-2 text-sm",children:[o.jsx(Qe,{variant:"destructive",children:"Thất bại"}),o.jsx("p",{className:"text-destructive",children:k.error})]}),o.jsx(An,{children:o.jsx(me,{variant:"outline",onClick:()=>U(!1),children:"Đóng"})})]})})]})}function N_(){for(var n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];return m.useMemo(()=>s=>{a.forEach(c=>c(s))},a)}const Xu=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Xs(n){const a=Object.prototype.toString.call(n);return a==="[object Window]"||a==="[object global]"}function Cp(n){return"nodeType"in n}function zn(n){var a,l;return n?Xs(n)?n:Cp(n)&&(a=(l=n.ownerDocument)==null?void 0:l.defaultView)!=null?a:window:window}function Ep(n){const{Document:a}=zn(n);return n instanceof a}function gi(n){return Xs(n)?!1:n instanceof zn(n).HTMLElement}function nS(n){return n instanceof zn(n).SVGElement}function Fs(n){return n?Xs(n)?n.document:Cp(n)?Ep(n)?n:gi(n)||nS(n)?n.ownerDocument:document:document:document}const qa=Xu?m.useLayoutEffect:m.useEffect;function Rp(n){const a=m.useRef(n);return qa(()=>{a.current=n}),m.useCallback(function(){for(var l=arguments.length,s=new Array(l),c=0;c<l;c++)s[c]=arguments[c];return a.current==null?void 0:a.current(...s)},[])}function T_(){const n=m.useRef(null),a=m.useCallback((s,c)=>{n.current=setInterval(s,c)},[]),l=m.useCallback(()=>{n.current!==null&&(clearInterval(n.current),n.current=null)},[]);return[a,l]}function ti(n,a){a===void 0&&(a=[n]);const l=m.useRef(n);return qa(()=>{l.current!==n&&(l.current=n)},a),l}function vi(n,a){const l=m.useRef();return m.useMemo(()=>{const s=n(l.current);return l.current=s,s},[...a])}function du(n){const a=Rp(n),l=m.useRef(null),s=m.useCallback(c=>{c!==l.current&&(a==null||a(c,l.current)),l.current=c},[]);return[l,s]}function dm(n){const a=m.useRef();return m.useEffect(()=>{a.current=n},[n]),a.current}let _h={};function xi(n,a){return m.useMemo(()=>{if(a)return a;const l=_h[n]==null?0:_h[n]+1;return _h[n]=l,n+"-"+l},[n,a])}function aS(n){return function(a){for(var l=arguments.length,s=new Array(l>1?l-1:0),c=1;c<l;c++)s[c-1]=arguments[c];return s.reduce((u,f)=>{const p=Object.entries(f);for(const[g,v]of p){const x=u[g];x!=null&&(u[g]=x+n*v)}return u},{...a})}}const Us=aS(1),ni=aS(-1);function M_(n){return"clientX"in n&&"clientY"in n}function Np(n){if(!n)return!1;const{KeyboardEvent:a}=zn(n.target);return a&&n instanceof a}function A_(n){if(!n)return!1;const{TouchEvent:a}=zn(n.target);return a&&n instanceof a}function fm(n){if(A_(n)){if(n.touches&&n.touches.length){const{clientX:a,clientY:l}=n.touches[0];return{x:a,y:l}}else if(n.changedTouches&&n.changedTouches.length){const{clientX:a,clientY:l}=n.changedTouches[0];return{x:a,y:l}}}return M_(n)?{x:n.clientX,y:n.clientY}:null}const fu=Object.freeze({Translate:{toString(n){if(!n)return;const{x:a,y:l}=n;return"translate3d("+(a?Math.round(a):0)+"px, "+(l?Math.round(l):0)+"px, 0)"}},Scale:{toString(n){if(!n)return;const{scaleX:a,scaleY:l}=n;return"scaleX("+a+") scaleY("+l+")"}},Transform:{toString(n){if(n)return[fu.Translate.toString(n),fu.Scale.toString(n)].join(" ")}},Transition:{toString(n){let{property:a,duration:l,easing:s}=n;return a+" "+l+"ms "+s}}}),Tb="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function D_(n){return n.matches(Tb)?n:n.querySelector(Tb)}const O_={display:"none"};function __(n){let{id:a,value:l}=n;return ue.createElement("div",{id:a,style:O_},l)}function k_(n){let{id:a,announcement:l,ariaLiveType:s="assertive"}=n;const c={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ue.createElement("div",{id:a,style:c,role:"status","aria-live":s,"aria-atomic":!0},l)}function z_(){const[n,a]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&a(s)},[]),announcement:n}}const rS=m.createContext(null);function L_(n){const a=m.useContext(rS);m.useEffect(()=>{if(!a)throw new Error("useDndMonitor must be used within a children of <DndContext>");return a(n)},[n,a])}function U_(){const[n]=m.useState(()=>new Set),a=m.useCallback(s=>(n.add(s),()=>n.delete(s)),[n]);return[m.useCallback(s=>{let{type:c,event:u}=s;n.forEach(f=>{var p;return(p=f[c])==null?void 0:p.call(f,u)})},[n]),a]}const B_={draggable:`
|
|
345
345
|
To pick up a draggable item, press the space bar.
|
|
346
346
|
While dragging, use the arrow keys to move the item.
|
|
347
347
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
348
|
-
`},H_={onDragStart(n){let{active:a}=n;return"Picked up draggable item "+a.id+"."},onDragOver(n){let{active:a,over:l}=n;return l?"Draggable item "+a.id+" was moved over droppable area "+l.id+".":"Draggable item "+a.id+" is no longer over a droppable area."},onDragEnd(n){let{active:a,over:l}=n;return l?"Draggable item "+a.id+" was dropped over droppable area "+l.id:"Draggable item "+a.id+" was dropped."},onDragCancel(n){let{active:a}=n;return"Dragging was cancelled. Draggable item "+a.id+" was dropped."}};function I_(n){let{announcements:a=H_,container:l,hiddenTextDescribedById:s,screenReaderInstructions:c=B_}=n;const{announce:u,announcement:f}=z_(),p=xi("DndLiveRegion"),[g,v]=m.useState(!1);if(m.useEffect(()=>{v(!0)},[]),L_(m.useMemo(()=>({onDragStart(y){let{active:b}=y;u(a.onDragStart({active:b}))},onDragMove(y){let{active:b,over:w}=y;a.onDragMove&&u(a.onDragMove({active:b,over:w}))},onDragOver(y){let{active:b,over:w}=y;u(a.onDragOver({active:b,over:w}))},onDragEnd(y){let{active:b,over:w}=y;u(a.onDragEnd({active:b,over:w}))},onDragCancel(y){let{active:b,over:w}=y;u(a.onDragCancel({active:b,over:w}))}}),[u,a])),!g)return null;const x=ue.createElement(ue.Fragment,null,ue.createElement(__,{id:s,value:c.draggable}),ue.createElement(k_,{id:p,announcement:f}));return l?ba.createPortal(x,l):x}var Gt;(function(n){n.DragStart="dragStart",n.DragMove="dragMove",n.DragEnd="dragEnd",n.DragCancel="dragCancel",n.DragOver="dragOver",n.RegisterDroppable="registerDroppable",n.SetDroppableDisabled="setDroppableDisabled",n.UnregisterDroppable="unregisterDroppable"})(Gt||(Gt={}));function hu(){}function Mb(n,a){return m.useMemo(()=>({sensor:n,options:a??{}}),[n,a])}function P_(){for(var n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];return m.useMemo(()=>[...a].filter(s=>s!=null),[...a])}const Ea=Object.freeze({x:0,y:0});function lS(n,a){return Math.sqrt(Math.pow(n.x-a.x,2)+Math.pow(n.y-a.y,2))}function sS(n,a){let{data:{value:l}}=n,{data:{value:s}}=a;return l-s}function q_(n,a){let{data:{value:l}}=n,{data:{value:s}}=a;return s-l}function Ab(n){let{left:a,top:l,height:s,width:c}=n;return[{x:a,y:l},{x:a+c,y:l},{x:a,y:l+s},{x:a+c,y:l+s}]}function oS(n,a){if(!n||n.length===0)return null;const[l]=n;return l[a]}function Db(n,a,l){return a===void 0&&(a=n.left),l===void 0&&(l=n.top),{x:a+n.width*.5,y:l+n.height*.5}}const V_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=Db(a,a.left,a.top),u=[];for(const f of s){const{id:p}=f,g=l.get(p);if(g){const v=lS(Db(g),c);u.push({id:p,data:{droppableContainer:f,value:v}})}}return u.sort(sS)},$_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=Ab(a),u=[];for(const f of s){const{id:p}=f,g=l.get(p);if(g){const v=Ab(g),x=c.reduce((b,w,E)=>b+lS(v[E],w),0),y=Number((x/4).toFixed(4));u.push({id:p,data:{droppableContainer:f,value:y}})}}return u.sort(sS)};function Y_(n,a){const l=Math.max(a.top,n.top),s=Math.max(a.left,n.left),c=Math.min(a.left+a.width,n.left+n.width),u=Math.min(a.top+a.height,n.top+n.height),f=c-s,p=u-l;if(s<c&&l<u){const g=a.width*a.height,v=n.width*n.height,x=f*p,y=x/(g+v-x);return Number(y.toFixed(4))}return 0}const G_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=[];for(const u of s){const{id:f}=u,p=l.get(f);if(p){const g=Y_(p,a);g>0&&c.push({id:f,data:{droppableContainer:u,value:g}})}}return c.sort(q_)};function K_(n,a,l){return{...n,scaleX:a&&l?a.width/l.width:1,scaleY:a&&l?a.height/l.height:1}}function iS(n,a){return n&&a?{x:n.left-a.left,y:n.top-a.top}:Ea}function X_(n){return function(l){for(var s=arguments.length,c=new Array(s>1?s-1:0),u=1;u<s;u++)c[u-1]=arguments[u];return c.reduce((f,p)=>({...f,top:f.top+n*p.y,bottom:f.bottom+n*p.y,left:f.left+n*p.x,right:f.right+n*p.x}),{...l})}}const F_=X_(1);function Q_(n){if(n.startsWith("matrix3d(")){const a=n.slice(9,-1).split(/, /);return{x:+a[12],y:+a[13],scaleX:+a[0],scaleY:+a[5]}}else if(n.startsWith("matrix(")){const a=n.slice(7,-1).split(/, /);return{x:+a[4],y:+a[5],scaleX:+a[0],scaleY:+a[3]}}return null}function Z_(n,a,l){const s=Q_(a);if(!s)return n;const{scaleX:c,scaleY:u,x:f,y:p}=s,g=n.left-f-(1-c)*parseFloat(l),v=n.top-p-(1-u)*parseFloat(l.slice(l.indexOf(" ")+1)),x=c?n.width/c:n.width,y=u?n.height/u:n.height;return{width:x,height:y,top:v,right:g+x,bottom:v+y,left:g}}const J_={ignoreTransform:!1};function Qs(n,a){a===void 0&&(a=J_);let l=n.getBoundingClientRect();if(a.ignoreTransform){const{transform:v,transformOrigin:x}=zn(n).getComputedStyle(n);v&&(l=Z_(l,v,x))}const{top:s,left:c,width:u,height:f,bottom:p,right:g}=l;return{top:s,left:c,width:u,height:f,bottom:p,right:g}}function Ob(n){return Qs(n,{ignoreTransform:!0})}function W_(n){const a=n.innerWidth,l=n.innerHeight;return{top:0,left:0,right:a,bottom:l,width:a,height:l}}function e3(n,a){return a===void 0&&(a=zn(n).getComputedStyle(n)),a.position==="fixed"}function t3(n,a){a===void 0&&(a=zn(n).getComputedStyle(n));const l=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(c=>{const u=a[c];return typeof u=="string"?l.test(u):!1})}function Fu(n,a){const l=[];function s(c){if(a!=null&&l.length>=a||!c)return l;if(Ep(c)&&c.scrollingElement!=null&&!l.includes(c.scrollingElement))return l.push(c.scrollingElement),l;if(!gi(c)||nS(c)||l.includes(c))return l;const u=zn(n).getComputedStyle(c);return c!==n&&t3(c,u)&&l.push(c),e3(c,u)?l:s(c.parentNode)}return n?s(n):l}function cS(n){const[a]=Fu(n,1);return a??null}function kh(n){return!Xu||!n?null:Xs(n)?n:Cp(n)?Ep(n)||n===Fs(n).scrollingElement?window:gi(n)?n:null:null}function uS(n){return Xs(n)?n.scrollX:n.scrollLeft}function dS(n){return Xs(n)?n.scrollY:n.scrollTop}function hm(n){return{x:uS(n),y:dS(n)}}var Wt;(function(n){n[n.Forward=1]="Forward",n[n.Backward=-1]="Backward"})(Wt||(Wt={}));function fS(n){return!Xu||!n?!1:n===document.scrollingElement}function hS(n){const a={x:0,y:0},l=fS(n)?{height:window.innerHeight,width:window.innerWidth}:{height:n.clientHeight,width:n.clientWidth},s={x:n.scrollWidth-l.width,y:n.scrollHeight-l.height},c=n.scrollTop<=a.y,u=n.scrollLeft<=a.x,f=n.scrollTop>=s.y,p=n.scrollLeft>=s.x;return{isTop:c,isLeft:u,isBottom:f,isRight:p,maxScroll:s,minScroll:a}}const n3={x:.2,y:.2};function a3(n,a,l,s,c){let{top:u,left:f,right:p,bottom:g}=l;s===void 0&&(s=10),c===void 0&&(c=n3);const{isTop:v,isBottom:x,isLeft:y,isRight:b}=hS(n),w={x:0,y:0},E={x:0,y:0},j={height:a.height*c.y,width:a.width*c.x};return!v&&u<=a.top+j.height?(w.y=Wt.Backward,E.y=s*Math.abs((a.top+j.height-u)/j.height)):!x&&g>=a.bottom-j.height&&(w.y=Wt.Forward,E.y=s*Math.abs((a.bottom-j.height-g)/j.height)),!b&&p>=a.right-j.width?(w.x=Wt.Forward,E.x=s*Math.abs((a.right-j.width-p)/j.width)):!y&&f<=a.left+j.width&&(w.x=Wt.Backward,E.x=s*Math.abs((a.left+j.width-f)/j.width)),{direction:w,speed:E}}function r3(n){if(n===document.scrollingElement){const{innerWidth:u,innerHeight:f}=window;return{top:0,left:0,right:u,bottom:f,width:u,height:f}}const{top:a,left:l,right:s,bottom:c}=n.getBoundingClientRect();return{top:a,left:l,right:s,bottom:c,width:n.clientWidth,height:n.clientHeight}}function mS(n){return n.reduce((a,l)=>Us(a,hm(l)),Ea)}function l3(n){return n.reduce((a,l)=>a+uS(l),0)}function s3(n){return n.reduce((a,l)=>a+dS(l),0)}function o3(n,a){if(a===void 0&&(a=Qs),!n)return;const{top:l,left:s,bottom:c,right:u}=a(n);cS(n)&&(c<=0||u<=0||l>=window.innerHeight||s>=window.innerWidth)&&n.scrollIntoView({block:"center",inline:"center"})}const i3=[["x",["left","right"],l3],["y",["top","bottom"],s3]];class Tp{constructor(a,l){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=Fu(l),c=mS(s);this.rect={...a},this.width=a.width,this.height=a.height;for(const[u,f,p]of i3)for(const g of f)Object.defineProperty(this,g,{get:()=>{const v=p(s),x=c[u]-v;return this.rect[g]+x},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Xo{constructor(a){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(l=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...l)})},this.target=a}add(a,l,s){var c;(c=this.target)==null||c.addEventListener(a,l,s),this.listeners.push([a,l,s])}}function c3(n){const{EventTarget:a}=zn(n);return n instanceof a?n:Fs(n)}function zh(n,a){const l=Math.abs(n.x),s=Math.abs(n.y);return typeof a=="number"?Math.sqrt(l**2+s**2)>a:"x"in a&&"y"in a?l>a.x&&s>a.y:"x"in a?l>a.x:"y"in a?s>a.y:!1}var la;(function(n){n.Click="click",n.DragStart="dragstart",n.Keydown="keydown",n.ContextMenu="contextmenu",n.Resize="resize",n.SelectionChange="selectionchange",n.VisibilityChange="visibilitychange"})(la||(la={}));function _b(n){n.preventDefault()}function u3(n){n.stopPropagation()}var Ke;(function(n){n.Space="Space",n.Down="ArrowDown",n.Right="ArrowRight",n.Left="ArrowLeft",n.Up="ArrowUp",n.Esc="Escape",n.Enter="Enter",n.Tab="Tab"})(Ke||(Ke={}));const pS={start:[Ke.Space,Ke.Enter],cancel:[Ke.Esc],end:[Ke.Space,Ke.Enter,Ke.Tab]},d3=(n,a)=>{let{currentCoordinates:l}=a;switch(n.code){case Ke.Right:return{...l,x:l.x+25};case Ke.Left:return{...l,x:l.x-25};case Ke.Down:return{...l,y:l.y+25};case Ke.Up:return{...l,y:l.y-25}}};class Mp{constructor(a){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=a;const{event:{target:l}}=a;this.props=a,this.listeners=new Xo(Fs(l)),this.windowListeners=new Xo(zn(l)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(la.Resize,this.handleCancel),this.windowListeners.add(la.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(la.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:a,onStart:l}=this.props,s=a.node.current;s&&o3(s),l(Ea)}handleKeyDown(a){if(Np(a)){const{active:l,context:s,options:c}=this.props,{keyboardCodes:u=pS,coordinateGetter:f=d3,scrollBehavior:p="smooth"}=c,{code:g}=a;if(u.end.includes(g)){this.handleEnd(a);return}if(u.cancel.includes(g)){this.handleCancel(a);return}const{collisionRect:v}=s.current,x=v?{x:v.left,y:v.top}:Ea;this.referenceCoordinates||(this.referenceCoordinates=x);const y=f(a,{active:l,context:s.current,currentCoordinates:x});if(y){const b=ni(y,x),w={x:0,y:0},{scrollableAncestors:E}=s.current;for(const j of E){const C=a.code,{isTop:N,isRight:M,isLeft:T,isBottom:D,maxScroll:O,minScroll:A}=hS(j),U=r3(j),k={x:Math.min(C===Ke.Right?U.right-U.width/2:U.right,Math.max(C===Ke.Right?U.left:U.left+U.width/2,y.x)),y:Math.min(C===Ke.Down?U.bottom-U.height/2:U.bottom,Math.max(C===Ke.Down?U.top:U.top+U.height/2,y.y))},$=C===Ke.Right&&!M||C===Ke.Left&&!T,X=C===Ke.Down&&!D||C===Ke.Up&&!N;if($&&k.x!==y.x){const te=j.scrollLeft+b.x,G=C===Ke.Right&&te<=O.x||C===Ke.Left&&te>=A.x;if(G&&!b.y){j.scrollTo({left:te,behavior:p});return}G?w.x=j.scrollLeft-te:w.x=C===Ke.Right?j.scrollLeft-O.x:j.scrollLeft-A.x,w.x&&j.scrollBy({left:-w.x,behavior:p});break}else if(X&&k.y!==y.y){const te=j.scrollTop+b.y,G=C===Ke.Down&&te<=O.y||C===Ke.Up&&te>=A.y;if(G&&!b.x){j.scrollTo({top:te,behavior:p});return}G?w.y=j.scrollTop-te:w.y=C===Ke.Down?j.scrollTop-O.y:j.scrollTop-A.y,w.y&&j.scrollBy({top:-w.y,behavior:p});break}}this.handleMove(a,Us(ni(y,this.referenceCoordinates),w))}}}handleMove(a,l){const{onMove:s}=this.props;a.preventDefault(),s(l)}handleEnd(a){const{onEnd:l}=this.props;a.preventDefault(),this.detach(),l()}handleCancel(a){const{onCancel:l}=this.props;a.preventDefault(),this.detach(),l()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Mp.activators=[{eventName:"onKeyDown",handler:(n,a,l)=>{let{keyboardCodes:s=pS,onActivation:c}=a,{active:u}=l;const{code:f}=n.nativeEvent;if(s.start.includes(f)){const p=u.activatorNode.current;return p&&n.target!==p?!1:(n.preventDefault(),c==null||c({event:n.nativeEvent}),!0)}return!1}}];function kb(n){return!!(n&&"distance"in n)}function zb(n){return!!(n&&"delay"in n)}class Ap{constructor(a,l,s){var c;s===void 0&&(s=c3(a.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=a,this.events=l;const{event:u}=a,{target:f}=u;this.props=a,this.events=l,this.document=Fs(f),this.documentListeners=new Xo(this.document),this.listeners=new Xo(s),this.windowListeners=new Xo(zn(f)),this.initialCoordinates=(c=fm(u))!=null?c:Ea,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:a,props:{options:{activationConstraint:l,bypassActivationConstraint:s}}}=this;if(this.listeners.add(a.move.name,this.handleMove,{passive:!1}),this.listeners.add(a.end.name,this.handleEnd),a.cancel&&this.listeners.add(a.cancel.name,this.handleCancel),this.windowListeners.add(la.Resize,this.handleCancel),this.windowListeners.add(la.DragStart,_b),this.windowListeners.add(la.VisibilityChange,this.handleCancel),this.windowListeners.add(la.ContextMenu,_b),this.documentListeners.add(la.Keydown,this.handleKeydown),l){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(zb(l)){this.timeoutId=setTimeout(this.handleStart,l.delay),this.handlePending(l);return}if(kb(l)){this.handlePending(l);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(a,l){const{active:s,onPending:c}=this.props;c(s,a,this.initialCoordinates,l)}handleStart(){const{initialCoordinates:a}=this,{onStart:l}=this.props;a&&(this.activated=!0,this.documentListeners.add(la.Click,u3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(la.SelectionChange,this.removeTextSelection),l(a))}handleMove(a){var l;const{activated:s,initialCoordinates:c,props:u}=this,{onMove:f,options:{activationConstraint:p}}=u;if(!c)return;const g=(l=fm(a))!=null?l:Ea,v=ni(c,g);if(!s&&p){if(kb(p)){if(p.tolerance!=null&&zh(v,p.tolerance))return this.handleCancel();if(zh(v,p.distance))return this.handleStart()}if(zb(p)&&zh(v,p.tolerance))return this.handleCancel();this.handlePending(p,v);return}a.cancelable&&a.preventDefault(),f(g)}handleEnd(){const{onAbort:a,onEnd:l}=this.props;this.detach(),this.activated||a(this.props.active),l()}handleCancel(){const{onAbort:a,onCancel:l}=this.props;this.detach(),this.activated||a(this.props.active),l()}handleKeydown(a){a.code===Ke.Esc&&this.handleCancel()}removeTextSelection(){var a;(a=this.document.getSelection())==null||a.removeAllRanges()}}const f3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Dp extends Ap{constructor(a){const{event:l}=a,s=Fs(l.target);super(a,f3,s)}}Dp.activators=[{eventName:"onPointerDown",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;return!l.isPrimary||l.button!==0?!1:(s==null||s({event:l}),!0)}}];const h3={move:{name:"mousemove"},end:{name:"mouseup"}};var mm;(function(n){n[n.RightClick=2]="RightClick"})(mm||(mm={}));class m3 extends Ap{constructor(a){super(a,h3,Fs(a.event.target))}}m3.activators=[{eventName:"onMouseDown",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;return l.button===mm.RightClick?!1:(s==null||s({event:l}),!0)}}];const Lh={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class p3 extends Ap{constructor(a){super(a,Lh)}static setup(){return window.addEventListener(Lh.move.name,a,{capture:!1,passive:!1}),function(){window.removeEventListener(Lh.move.name,a)};function a(){}}}p3.activators=[{eventName:"onTouchStart",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;const{touches:c}=l;return c.length>1?!1:(s==null||s({event:l}),!0)}}];var Fo;(function(n){n[n.Pointer=0]="Pointer",n[n.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var mu;(function(n){n[n.TreeOrder=0]="TreeOrder",n[n.ReversedTreeOrder=1]="ReversedTreeOrder"})(mu||(mu={}));function g3(n){let{acceleration:a,activator:l=Fo.Pointer,canScroll:s,draggingRect:c,enabled:u,interval:f=5,order:p=mu.TreeOrder,pointerCoordinates:g,scrollableAncestors:v,scrollableAncestorRects:x,delta:y,threshold:b}=n;const w=x3({delta:y,disabled:!u}),[E,j]=T_(),C=m.useRef({x:0,y:0}),N=m.useRef({x:0,y:0}),M=m.useMemo(()=>{switch(l){case Fo.Pointer:return g?{top:g.y,bottom:g.y,left:g.x,right:g.x}:null;case Fo.DraggableRect:return c}},[l,c,g]),T=m.useRef(null),D=m.useCallback(()=>{const A=T.current;if(!A)return;const U=C.current.x*N.current.x,k=C.current.y*N.current.y;A.scrollBy(U,k)},[]),O=m.useMemo(()=>p===mu.TreeOrder?[...v].reverse():v,[p,v]);m.useEffect(()=>{if(!u||!v.length||!M){j();return}for(const A of O){if((s==null?void 0:s(A))===!1)continue;const U=v.indexOf(A),k=x[U];if(!k)continue;const{direction:$,speed:X}=a3(A,k,M,a,b);for(const te of["x","y"])w[te][$[te]]||(X[te]=0,$[te]=0);if(X.x>0||X.y>0){j(),T.current=A,E(D,f),C.current=X,N.current=$;return}}C.current={x:0,y:0},N.current={x:0,y:0},j()},[a,D,s,j,u,f,JSON.stringify(M),JSON.stringify(w),E,v,O,x,JSON.stringify(b)])}const v3={x:{[Wt.Backward]:!1,[Wt.Forward]:!1},y:{[Wt.Backward]:!1,[Wt.Forward]:!1}};function x3(n){let{delta:a,disabled:l}=n;const s=dm(a);return vi(c=>{if(l||!s||!c)return v3;const u={x:Math.sign(a.x-s.x),y:Math.sign(a.y-s.y)};return{x:{[Wt.Backward]:c.x[Wt.Backward]||u.x===-1,[Wt.Forward]:c.x[Wt.Forward]||u.x===1},y:{[Wt.Backward]:c.y[Wt.Backward]||u.y===-1,[Wt.Forward]:c.y[Wt.Forward]||u.y===1}}},[l,a,s])}function y3(n,a){const l=a!=null?n.get(a):void 0,s=l?l.node.current:null;return vi(c=>{var u;return a==null?null:(u=s??c)!=null?u:null},[s,a])}function b3(n,a){return m.useMemo(()=>n.reduce((l,s)=>{const{sensor:c}=s,u=c.activators.map(f=>({eventName:f.eventName,handler:a(f.handler,s)}));return[...l,...u]},[]),[n,a])}var ai;(function(n){n[n.Always=0]="Always",n[n.BeforeDragging=1]="BeforeDragging",n[n.WhileDragging=2]="WhileDragging"})(ai||(ai={}));var pm;(function(n){n.Optimized="optimized"})(pm||(pm={}));const Lb=new Map;function w3(n,a){let{dragging:l,dependencies:s,config:c}=a;const[u,f]=m.useState(null),{frequency:p,measure:g,strategy:v}=c,x=m.useRef(n),y=C(),b=ti(y),w=m.useCallback(function(N){N===void 0&&(N=[]),!b.current&&f(M=>M===null?N:M.concat(N.filter(T=>!M.includes(T))))},[b]),E=m.useRef(null),j=vi(N=>{if(y&&!l)return Lb;if(!N||N===Lb||x.current!==n||u!=null){const M=new Map;for(let T of n){if(!T)continue;if(u&&u.length>0&&!u.includes(T.id)&&T.rect.current){M.set(T.id,T.rect.current);continue}const D=T.node.current,O=D?new Tp(g(D),D):null;T.rect.current=O,O&&M.set(T.id,O)}return M}return N},[n,u,l,y,g]);return m.useEffect(()=>{x.current=n},[n]),m.useEffect(()=>{y||w()},[l,y]),m.useEffect(()=>{u&&u.length>0&&f(null)},[JSON.stringify(u)]),m.useEffect(()=>{y||typeof p!="number"||E.current!==null||(E.current=setTimeout(()=>{w(),E.current=null},p))},[p,y,w,...s]),{droppableRects:j,measureDroppableContainers:w,measuringScheduled:u!=null};function C(){switch(v){case ai.Always:return!1;case ai.BeforeDragging:return l;default:return!l}}}function gS(n,a){return vi(l=>n?l||(typeof a=="function"?a(n):n):null,[a,n])}function S3(n,a){return gS(n,a)}function j3(n){let{callback:a,disabled:l}=n;const s=Rp(a),c=m.useMemo(()=>{if(l||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:u}=window;return new u(s)},[s,l]);return m.useEffect(()=>()=>c==null?void 0:c.disconnect(),[c]),c}function Qu(n){let{callback:a,disabled:l}=n;const s=Rp(a),c=m.useMemo(()=>{if(l||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:u}=window;return new u(s)},[l]);return m.useEffect(()=>()=>c==null?void 0:c.disconnect(),[c]),c}function C3(n){return new Tp(Qs(n),n)}function Ub(n,a,l){a===void 0&&(a=C3);const[s,c]=m.useState(null);function u(){c(g=>{if(!n)return null;if(n.isConnected===!1){var v;return(v=g??l)!=null?v:null}const x=a(n);return JSON.stringify(g)===JSON.stringify(x)?g:x})}const f=j3({callback(g){if(n)for(const v of g){const{type:x,target:y}=v;if(x==="childList"&&y instanceof HTMLElement&&y.contains(n)){u();break}}}}),p=Qu({callback:u});return qa(()=>{u(),n?(p==null||p.observe(n),f==null||f.observe(document.body,{childList:!0,subtree:!0})):(p==null||p.disconnect(),f==null||f.disconnect())},[n]),s}function E3(n){const a=gS(n);return iS(n,a)}const Bb=[];function R3(n){const a=m.useRef(n),l=vi(s=>n?s&&s!==Bb&&n&&a.current&&n.parentNode===a.current.parentNode?s:Fu(n):Bb,[n]);return m.useEffect(()=>{a.current=n},[n]),l}function N3(n){const[a,l]=m.useState(null),s=m.useRef(n),c=m.useCallback(u=>{const f=kh(u.target);f&&l(p=>p?(p.set(f,hm(f)),new Map(p)):null)},[]);return m.useEffect(()=>{const u=s.current;if(n!==u){f(u);const p=n.map(g=>{const v=kh(g);return v?(v.addEventListener("scroll",c,{passive:!0}),[v,hm(v)]):null}).filter(g=>g!=null);l(p.length?new Map(p):null),s.current=n}return()=>{f(n),f(u)};function f(p){p.forEach(g=>{const v=kh(g);v==null||v.removeEventListener("scroll",c)})}},[c,n]),m.useMemo(()=>n.length?a?Array.from(a.values()).reduce((u,f)=>Us(u,f),Ea):mS(n):Ea,[n,a])}function Hb(n,a){a===void 0&&(a=[]);const l=m.useRef(null);return m.useEffect(()=>{l.current=null},a),m.useEffect(()=>{const s=n!==Ea;s&&!l.current&&(l.current=n),!s&&l.current&&(l.current=null)},[n]),l.current?ni(n,l.current):Ea}function T3(n){m.useEffect(()=>{if(!Xu)return;const a=n.map(l=>{let{sensor:s}=l;return s.setup==null?void 0:s.setup()});return()=>{for(const l of a)l==null||l()}},n.map(a=>{let{sensor:l}=a;return l}))}function M3(n,a){return m.useMemo(()=>n.reduce((l,s)=>{let{eventName:c,handler:u}=s;return l[c]=f=>{u(f,a)},l},{}),[n,a])}function vS(n){return m.useMemo(()=>n?W_(n):null,[n])}const Ib=[];function A3(n,a){a===void 0&&(a=Qs);const[l]=n,s=vS(l?zn(l):null),[c,u]=m.useState(Ib);function f(){u(()=>n.length?n.map(g=>fS(g)?s:new Tp(a(g),g)):Ib)}const p=Qu({callback:f});return qa(()=>{p==null||p.disconnect(),f(),n.forEach(g=>p==null?void 0:p.observe(g))},[n]),c}function D3(n){if(!n)return null;if(n.children.length>1)return n;const a=n.children[0];return gi(a)?a:n}function O3(n){let{measure:a}=n;const[l,s]=m.useState(null),c=m.useCallback(v=>{for(const{target:x}of v)if(gi(x)){s(y=>{const b=a(x);return y?{...y,width:b.width,height:b.height}:b});break}},[a]),u=Qu({callback:c}),f=m.useCallback(v=>{const x=D3(v);u==null||u.disconnect(),x&&(u==null||u.observe(x)),s(x?a(x):null)},[a,u]),[p,g]=du(f);return m.useMemo(()=>({nodeRef:p,rect:l,setRef:g}),[l,p,g])}const _3=[{sensor:Dp,options:{}},{sensor:Mp,options:{}}],k3={current:{}},eu={draggable:{measure:Ob},droppable:{measure:Ob,strategy:ai.WhileDragging,frequency:pm.Optimized},dragOverlay:{measure:Qs}};class Qo extends Map{get(a){var l;return a!=null&&(l=super.get(a))!=null?l:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(a=>{let{disabled:l}=a;return!l})}getNodeFor(a){var l,s;return(l=(s=this.get(a))==null?void 0:s.node.current)!=null?l:void 0}}const z3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Qo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:hu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:eu,measureDroppableContainers:hu,windowRect:null,measuringScheduled:!1},L3={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:hu,draggableNodes:new Map,over:null,measureDroppableContainers:hu},Zu=m.createContext(L3),xS=m.createContext(z3);function U3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Qo}}}function B3(n,a){switch(a.type){case Gt.DragStart:return{...n,draggable:{...n.draggable,initialCoordinates:a.initialCoordinates,active:a.active}};case Gt.DragMove:return n.draggable.active==null?n:{...n,draggable:{...n.draggable,translate:{x:a.coordinates.x-n.draggable.initialCoordinates.x,y:a.coordinates.y-n.draggable.initialCoordinates.y}}};case Gt.DragEnd:case Gt.DragCancel:return{...n,draggable:{...n.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Gt.RegisterDroppable:{const{element:l}=a,{id:s}=l,c=new Qo(n.droppable.containers);return c.set(s,l),{...n,droppable:{...n.droppable,containers:c}}}case Gt.SetDroppableDisabled:{const{id:l,key:s,disabled:c}=a,u=n.droppable.containers.get(l);if(!u||s!==u.key)return n;const f=new Qo(n.droppable.containers);return f.set(l,{...u,disabled:c}),{...n,droppable:{...n.droppable,containers:f}}}case Gt.UnregisterDroppable:{const{id:l,key:s}=a,c=n.droppable.containers.get(l);if(!c||s!==c.key)return n;const u=new Qo(n.droppable.containers);return u.delete(l),{...n,droppable:{...n.droppable,containers:u}}}default:return n}}function H3(n){let{disabled:a}=n;const{active:l,activatorEvent:s,draggableNodes:c}=m.useContext(Zu),u=dm(s),f=dm(l==null?void 0:l.id);return m.useEffect(()=>{if(!a&&!s&&u&&f!=null){if(!Np(u)||document.activeElement===u.target)return;const p=c.get(f);if(!p)return;const{activatorNode:g,node:v}=p;if(!g.current&&!v.current)return;requestAnimationFrame(()=>{for(const x of[g.current,v.current]){if(!x)continue;const y=D_(x);if(y){y.focus();break}}})}},[s,a,c,f,u]),null}function I3(n,a){let{transform:l,...s}=a;return n!=null&&n.length?n.reduce((c,u)=>u({transform:c,...s}),l):l}function P3(n){return m.useMemo(()=>({draggable:{...eu.draggable,...n==null?void 0:n.draggable},droppable:{...eu.droppable,...n==null?void 0:n.droppable},dragOverlay:{...eu.dragOverlay,...n==null?void 0:n.dragOverlay}}),[n==null?void 0:n.draggable,n==null?void 0:n.droppable,n==null?void 0:n.dragOverlay])}function q3(n){let{activeNode:a,measure:l,initialRect:s,config:c=!0}=n;const u=m.useRef(!1),{x:f,y:p}=typeof c=="boolean"?{x:c,y:c}:c;qa(()=>{if(!f&&!p||!a){u.current=!1;return}if(u.current||!s)return;const v=a==null?void 0:a.node.current;if(!v||v.isConnected===!1)return;const x=l(v),y=iS(x,s);if(f||(y.x=0),p||(y.y=0),u.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const b=cS(v);b&&b.scrollBy({top:y.y,left:y.x})}},[a,f,p,s,l])}const yS=m.createContext({...Ea,scaleX:1,scaleY:1});var al;(function(n){n[n.Uninitialized=0]="Uninitialized",n[n.Initializing=1]="Initializing",n[n.Initialized=2]="Initialized"})(al||(al={}));const V3=m.memo(function(a){var l,s,c,u;let{id:f,accessibility:p,autoScroll:g=!0,children:v,sensors:x=_3,collisionDetection:y=G_,measuring:b,modifiers:w,...E}=a;const j=m.useReducer(B3,void 0,U3),[C,N]=j,[M,T]=U_(),[D,O]=m.useState(al.Uninitialized),A=D===al.Initialized,{draggable:{active:U,nodes:k,translate:$},droppable:{containers:X}}=C,te=U!=null?k.get(U):null,G=m.useRef({initial:null,translated:null}),ie=m.useMemo(()=>{var vt;return U!=null?{id:U,data:(vt=te==null?void 0:te.data)!=null?vt:k3,rect:G}:null},[U,te]),ce=m.useRef(null),[se,_]=m.useState(null),[H,Q]=m.useState(null),J=ti(E,Object.values(E)),ee=xi("DndDescribedBy",f),z=m.useMemo(()=>X.getEnabled(),[X]),I=P3(b),{droppableRects:F,measureDroppableContainers:re,measuringScheduled:he}=w3(z,{dragging:A,dependencies:[$.x,$.y],config:I.droppable}),ge=y3(k,U),q=m.useMemo(()=>H?fm(H):null,[H]),oe=Nr(),de=S3(ge,I.draggable.measure);q3({activeNode:U!=null?k.get(U):null,config:oe.layoutShiftCompensation,initialRect:de,measure:I.draggable.measure});const fe=Ub(ge,I.draggable.measure,de),Te=Ub(ge?ge.parentElement:null),je=m.useRef({activatorEvent:null,active:null,activeNode:ge,collisionRect:null,collisions:null,droppableRects:F,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:X,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),De=X.getNodeFor((l=je.current.over)==null?void 0:l.id),Fe=O3({measure:I.dragOverlay.measure}),et=(s=Fe.nodeRef.current)!=null?s:ge,le=A?(c=Fe.rect)!=null?c:fe:null,Le=!!(Fe.nodeRef.current&&Fe.rect),Ie=E3(Le?null:fe),kt=vS(et?zn(et):null),St=R3(A?De??ge:null),Ft=A3(St),on=I3(w,{transform:{x:$.x-Ie.x,y:$.y-Ie.y,scaleX:1,scaleY:1},activatorEvent:H,active:ie,activeNodeRect:fe,containerNodeRect:Te,draggingNodeRect:le,over:je.current.over,overlayNodeRect:Fe.rect,scrollableAncestors:St,scrollableAncestorRects:Ft,windowRect:kt}),Qt=q?Us(q,$):null,jt=N3(St),fn=Hb(jt),Mt=Hb(jt,[fe]),At=Us(on,fn),cn=le?F_(le,on):null,fa=ie&&cn?y({active:ie,collisionRect:cn,droppableRects:F,droppableContainers:z,pointerCoordinates:Qt}):null,Ta=oS(fa,"id"),[Gn,dl]=m.useState(null),ha=Le?on:Us(on,Mt),Dt=K_(ha,(u=Gn==null?void 0:Gn.rect)!=null?u:null,fe),hn=m.useRef(null),Tt=m.useCallback((vt,st)=>{let{sensor:Bt,options:Ce}=st;if(ce.current==null)return;const ke=k.get(ce.current);if(!ke)return;const Ue=vt.nativeEvent,gt=new Bt({active:ce.current,activeNode:ke,event:Ue,options:Ce,context:je,onAbort(ct){if(!k.get(ct))return;const{onDragAbort:xt}=J.current,zt={id:ct};xt==null||xt(zt),M({type:"onDragAbort",event:zt})},onPending(ct,$t,xt,zt){if(!k.get(ct))return;const{onDragPending:Ka}=J.current,ma={id:ct,constraint:$t,initialCoordinates:xt,offset:zt};Ka==null||Ka(ma),M({type:"onDragPending",event:ma})},onStart(ct){const $t=ce.current;if($t==null)return;const xt=k.get($t);if(!xt)return;const{onDragStart:zt}=J.current,Ga={activatorEvent:Ue,active:{id:$t,data:xt.data,rect:G}};ba.unstable_batchedUpdates(()=>{zt==null||zt(Ga),O(al.Initializing),N({type:Gt.DragStart,initialCoordinates:ct,active:$t}),M({type:"onDragStart",event:Ga}),_(hn.current),Q(Ue)})},onMove(ct){N({type:Gt.DragMove,coordinates:ct})},onEnd:Ct(Gt.DragEnd),onCancel:Ct(Gt.DragCancel)});hn.current=gt;function Ct(ct){return async function(){const{active:xt,collisions:zt,over:Ga,scrollAdjustedTranslate:Ka}=je.current;let ma=null;if(xt&&Ka){const{cancelDrop:Tr}=J.current;ma={activatorEvent:Ue,active:xt,collisions:zt,delta:Ka,over:Ga},ct===Gt.DragEnd&&typeof Tr=="function"&&await Promise.resolve(Tr(ma))&&(ct=Gt.DragCancel)}ce.current=null,ba.unstable_batchedUpdates(()=>{N({type:ct}),O(al.Uninitialized),dl(null),_(null),Q(null),hn.current=null;const Tr=ct===Gt.DragEnd?"onDragEnd":"onDragCancel";if(ma){const Kn=J.current[Tr];Kn==null||Kn(ma),M({type:Tr,event:ma})}})}}},[k]),Js=m.useCallback((vt,st)=>(Bt,Ce)=>{const ke=Bt.nativeEvent,Ue=k.get(Ce);if(ce.current!==null||!Ue||ke.dndKit||ke.defaultPrevented)return;const gt={active:Ue};vt(Bt,st.options,gt)===!0&&(ke.dndKit={capturedBy:st.sensor},ce.current=Ce,Tt(Bt,st))},[k,Tt]),Pl=b3(x,Js);T3(x),qa(()=>{fe&&D===al.Initializing&&O(al.Initialized)},[fe,D]),m.useEffect(()=>{const{onDragMove:vt}=J.current,{active:st,activatorEvent:Bt,collisions:Ce,over:ke}=je.current;if(!st||!Bt)return;const Ue={active:st,activatorEvent:Bt,collisions:Ce,delta:{x:At.x,y:At.y},over:ke};ba.unstable_batchedUpdates(()=>{vt==null||vt(Ue),M({type:"onDragMove",event:Ue})})},[At.x,At.y]),m.useEffect(()=>{const{active:vt,activatorEvent:st,collisions:Bt,droppableContainers:Ce,scrollAdjustedTranslate:ke}=je.current;if(!vt||ce.current==null||!st||!ke)return;const{onDragOver:Ue}=J.current,gt=Ce.get(Ta),Ct=gt&>.rect.current?{id:gt.id,rect:gt.rect.current,data:gt.data,disabled:gt.disabled}:null,ct={active:vt,activatorEvent:st,collisions:Bt,delta:{x:ke.x,y:ke.y},over:Ct};ba.unstable_batchedUpdates(()=>{dl(Ct),Ue==null||Ue(ct),M({type:"onDragOver",event:ct})})},[Ta]),qa(()=>{je.current={activatorEvent:H,active:ie,activeNode:ge,collisionRect:cn,collisions:fa,droppableRects:F,draggableNodes:k,draggingNode:et,draggingNodeRect:le,droppableContainers:X,over:Gn,scrollableAncestors:St,scrollAdjustedTranslate:At},G.current={initial:le,translated:cn}},[ie,ge,fa,cn,k,et,le,F,X,Gn,St,At]),g3({...oe,delta:$,draggingRect:cn,pointerCoordinates:Qt,scrollableAncestors:St,scrollableAncestorRects:Ft});const ql=m.useMemo(()=>({active:ie,activeNode:ge,activeNodeRect:fe,activatorEvent:H,collisions:fa,containerNodeRect:Te,dragOverlay:Fe,draggableNodes:k,droppableContainers:X,droppableRects:F,over:Gn,measureDroppableContainers:re,scrollableAncestors:St,scrollableAncestorRects:Ft,measuringConfiguration:I,measuringScheduled:he,windowRect:kt}),[ie,ge,fe,H,fa,Te,Fe,k,X,F,Gn,re,St,Ft,I,he,kt]),Ya=m.useMemo(()=>({activatorEvent:H,activators:Pl,active:ie,activeNodeRect:fe,ariaDescribedById:{draggable:ee},dispatch:N,draggableNodes:k,over:Gn,measureDroppableContainers:re}),[H,Pl,ie,fe,N,ee,k,Gn,re]);return ue.createElement(rS.Provider,{value:T},ue.createElement(Zu.Provider,{value:Ya},ue.createElement(xS.Provider,{value:ql},ue.createElement(yS.Provider,{value:Dt},v)),ue.createElement(H3,{disabled:(p==null?void 0:p.restoreFocus)===!1})),ue.createElement(I_,{...p,hiddenTextDescribedById:ee}));function Nr(){const vt=(se==null?void 0:se.autoScrollEnabled)===!1,st=typeof g=="object"?g.enabled===!1:g===!1,Bt=A&&!vt&&!st;return typeof g=="object"?{...g,enabled:Bt}:{enabled:Bt}}}),$3=m.createContext(null),Pb="button",Y3="Draggable";function G3(n){let{id:a,data:l,disabled:s=!1,attributes:c}=n;const u=xi(Y3),{activators:f,activatorEvent:p,active:g,activeNodeRect:v,ariaDescribedById:x,draggableNodes:y,over:b}=m.useContext(Zu),{role:w=Pb,roleDescription:E="draggable",tabIndex:j=0}=c??{},C=(g==null?void 0:g.id)===a,N=m.useContext(C?yS:$3),[M,T]=du(),[D,O]=du(),A=M3(f,a),U=ti(l);qa(()=>(y.set(a,{id:a,key:u,node:M,activatorNode:D,data:U}),()=>{const $=y.get(a);$&&$.key===u&&y.delete(a)}),[y,a]);const k=m.useMemo(()=>({role:w,tabIndex:j,"aria-disabled":s,"aria-pressed":C&&w===Pb?!0:void 0,"aria-roledescription":E,"aria-describedby":x.draggable}),[s,w,j,C,E,x.draggable]);return{active:g,activatorEvent:p,activeNodeRect:v,attributes:k,isDragging:C,listeners:s?void 0:A,node:M,over:b,setNodeRef:T,setActivatorNodeRef:O,transform:N}}function K3(){return m.useContext(xS)}const X3="Droppable",F3={timeout:25};function Q3(n){let{data:a,disabled:l=!1,id:s,resizeObserverConfig:c}=n;const u=xi(X3),{active:f,dispatch:p,over:g,measureDroppableContainers:v}=m.useContext(Zu),x=m.useRef({disabled:l}),y=m.useRef(!1),b=m.useRef(null),w=m.useRef(null),{disabled:E,updateMeasurementsFor:j,timeout:C}={...F3,...c},N=ti(j??s),M=m.useCallback(()=>{if(!y.current){y.current=!0;return}w.current!=null&&clearTimeout(w.current),w.current=setTimeout(()=>{v(Array.isArray(N.current)?N.current:[N.current]),w.current=null},C)},[C]),T=Qu({callback:M,disabled:E||!f}),D=m.useCallback((k,$)=>{T&&($&&(T.unobserve($),y.current=!1),k&&T.observe(k))},[T]),[O,A]=du(D),U=ti(a);return m.useEffect(()=>{!T||!O.current||(T.disconnect(),y.current=!1,T.observe(O.current))},[O,T]),m.useEffect(()=>(p({type:Gt.RegisterDroppable,element:{id:s,key:u,disabled:l,node:O,rect:b,data:U}}),()=>p({type:Gt.UnregisterDroppable,key:u,id:s})),[s]),m.useEffect(()=>{l!==x.current.disabled&&(p({type:Gt.SetDroppableDisabled,id:s,key:u,disabled:l}),x.current.disabled=l)},[s,u,l,p]),{active:f,rect:b,isOver:(g==null?void 0:g.id)===s,node:O,over:g,setNodeRef:A}}function Z3(n,a,l){const s={...n};return a.top+n.y<=l.top?s.y=l.top-a.top:a.bottom+n.y>=l.top+l.height&&(s.y=l.top+l.height-a.bottom),a.left+n.x<=l.left?s.x=l.left-a.left:a.right+n.x>=l.left+l.width&&(s.x=l.left+l.width-a.right),s}const J3=n=>{let{containerNodeRect:a,draggingNodeRect:l,transform:s}=n;return!l||!a?s:Z3(s,l,a)},W3=n=>{let{transform:a}=n;return{...a,x:0}};function Op(n,a,l){const s=n.slice();return s.splice(l<0?s.length+l:l,0,s.splice(a,1)[0]),s}function ek(n,a){return n.reduce((l,s,c)=>{const u=a.get(s);return u&&(l[c]=u),l},Array(n.length))}function Pc(n){return n!==null&&n>=0}function tk(n,a){if(n===a)return!0;if(n.length!==a.length)return!1;for(let l=0;l<n.length;l++)if(n[l]!==a[l])return!1;return!0}function nk(n){return typeof n=="boolean"?{draggable:n,droppable:n}:n}const bS=n=>{let{rects:a,activeIndex:l,overIndex:s,index:c}=n;const u=Op(a,s,l),f=a[c],p=u[c];return!p||!f?null:{x:p.left-f.left,y:p.top-f.top,scaleX:p.width/f.width,scaleY:p.height/f.height}},qc={scaleX:1,scaleY:1},ak=n=>{var a;let{activeIndex:l,activeNodeRect:s,index:c,rects:u,overIndex:f}=n;const p=(a=u[l])!=null?a:s;if(!p)return null;if(c===l){const v=u[f];return v?{x:0,y:l<f?v.top+v.height-(p.top+p.height):v.top-p.top,...qc}:null}const g=rk(u,c,l);return c>l&&c<=f?{x:0,y:-p.height-g,...qc}:c<l&&c>=f?{x:0,y:p.height+g,...qc}:{x:0,y:0,...qc}};function rk(n,a,l){const s=n[a],c=n[a-1],u=n[a+1];return s?l<a?c?s.top-(c.top+c.height):u?u.top-(s.top+s.height):0:u?u.top-(s.top+s.height):c?s.top-(c.top+c.height):0:0}const wS="Sortable",SS=ue.createContext({activeIndex:-1,containerId:wS,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:bS,disabled:{draggable:!1,droppable:!1}});function lk(n){let{children:a,id:l,items:s,strategy:c=bS,disabled:u=!1}=n;const{active:f,dragOverlay:p,droppableRects:g,over:v,measureDroppableContainers:x}=K3(),y=xi(wS,l),b=p.rect!==null,w=m.useMemo(()=>s.map(A=>typeof A=="object"&&"id"in A?A.id:A),[s]),E=f!=null,j=f?w.indexOf(f.id):-1,C=v?w.indexOf(v.id):-1,N=m.useRef(w),M=!tk(w,N.current),T=C!==-1&&j===-1||M,D=nk(u);qa(()=>{M&&E&&x(w)},[M,w,E,x]),m.useEffect(()=>{N.current=w},[w]);const O=m.useMemo(()=>({activeIndex:j,containerId:y,disabled:D,disableTransforms:T,items:w,overIndex:C,useDragOverlay:b,sortedRects:ek(w,g),strategy:c}),[j,y,D.draggable,D.droppable,T,w,C,g,b,c]);return ue.createElement(SS.Provider,{value:O},a)}const sk=n=>{let{id:a,items:l,activeIndex:s,overIndex:c}=n;return Op(l,s,c).indexOf(a)},ok=n=>{let{containerId:a,isSorting:l,wasDragging:s,index:c,items:u,newIndex:f,previousItems:p,previousContainerId:g,transition:v}=n;return!v||!s||p!==u&&c===f?!1:l?!0:f!==c&&a===g},ik={duration:200,easing:"ease"},jS="transform",ck=fu.Transition.toString({property:jS,duration:0,easing:"linear"}),uk={roleDescription:"sortable"};function dk(n){let{disabled:a,index:l,node:s,rect:c}=n;const[u,f]=m.useState(null),p=m.useRef(l);return qa(()=>{if(!a&&l!==p.current&&s.current){const g=c.current;if(g){const v=Qs(s.current,{ignoreTransform:!0}),x={x:g.left-v.left,y:g.top-v.top,scaleX:g.width/v.width,scaleY:g.height/v.height};(x.x||x.y)&&f(x)}}l!==p.current&&(p.current=l)},[a,l,s,c]),m.useEffect(()=>{u&&f(null)},[u]),u}function fk(n){let{animateLayoutChanges:a=ok,attributes:l,disabled:s,data:c,getNewIndex:u=sk,id:f,strategy:p,resizeObserverConfig:g,transition:v=ik}=n;const{items:x,containerId:y,activeIndex:b,disabled:w,disableTransforms:E,sortedRects:j,overIndex:C,useDragOverlay:N,strategy:M}=m.useContext(SS),T=hk(s,w),D=x.indexOf(f),O=m.useMemo(()=>({sortable:{containerId:y,index:D,items:x},...c}),[y,c,D,x]),A=m.useMemo(()=>x.slice(x.indexOf(f)),[x,f]),{rect:U,node:k,isOver:$,setNodeRef:X}=Q3({id:f,data:O,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:A,...g}}),{active:te,activatorEvent:G,activeNodeRect:ie,attributes:ce,setNodeRef:se,listeners:_,isDragging:H,over:Q,setActivatorNodeRef:J,transform:ee}=G3({id:f,data:O,attributes:{...uk,...l},disabled:T.draggable}),z=N_(X,se),I=!!te,F=I&&!E&&Pc(b)&&Pc(C),re=!N&&H,he=re&&F?ee:null,q=F?he??(p??M)({rects:j,activeNodeRect:ie,activeIndex:b,overIndex:C,index:D}):null,oe=Pc(b)&&Pc(C)?u({id:f,items:x,activeIndex:b,overIndex:C}):D,de=te==null?void 0:te.id,fe=m.useRef({activeId:de,items:x,newIndex:oe,containerId:y}),Te=x!==fe.current.items,je=a({active:te,containerId:y,isDragging:H,isSorting:I,id:f,index:D,items:x,newIndex:fe.current.newIndex,previousItems:fe.current.items,previousContainerId:fe.current.containerId,transition:v,wasDragging:fe.current.activeId!=null}),De=dk({disabled:!je,index:D,node:k,rect:U});return m.useEffect(()=>{I&&fe.current.newIndex!==oe&&(fe.current.newIndex=oe),y!==fe.current.containerId&&(fe.current.containerId=y),x!==fe.current.items&&(fe.current.items=x)},[I,oe,y,x]),m.useEffect(()=>{if(de===fe.current.activeId)return;if(de!=null&&fe.current.activeId==null){fe.current.activeId=de;return}const et=setTimeout(()=>{fe.current.activeId=de},50);return()=>clearTimeout(et)},[de]),{active:te,activeIndex:b,attributes:ce,data:O,rect:U,index:D,newIndex:oe,items:x,isOver:$,isSorting:I,isDragging:H,listeners:_,node:k,overIndex:C,over:Q,setNodeRef:z,setActivatorNodeRef:J,setDroppableNodeRef:X,setDraggableNodeRef:se,transform:De??q,transition:Fe()};function Fe(){if(De||Te&&fe.current.newIndex===D)return ck;if(!(re&&!Np(G)||!v)&&(I||je))return fu.Transition.toString({...v,property:jS})}}function hk(n,a){var l,s;return typeof n=="boolean"?{draggable:n,droppable:!1}:{draggable:(l=n==null?void 0:n.draggable)!=null?l:a.draggable,droppable:(s=n==null?void 0:n.droppable)!=null?s:a.droppable}}function pu(n){if(!n)return!1;const a=n.data.current;return!!(a&&"sortable"in a&&typeof a.sortable=="object"&&"containerId"in a.sortable&&"items"in a.sortable&&"index"in a.sortable)}const mk=[Ke.Down,Ke.Right,Ke.Up,Ke.Left],pk=(n,a)=>{let{context:{active:l,collisionRect:s,droppableRects:c,droppableContainers:u,over:f,scrollableAncestors:p}}=a;if(mk.includes(n.code)){if(n.preventDefault(),!l||!s)return;const g=[];u.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const b=c.get(y.id);if(b)switch(n.code){case Ke.Down:s.top<b.top&&g.push(y);break;case Ke.Up:s.top>b.top&&g.push(y);break;case Ke.Left:s.left>b.left&&g.push(y);break;case Ke.Right:s.left<b.left&&g.push(y);break}});const v=$_({collisionRect:s,droppableRects:c,droppableContainers:g});let x=oS(v,"id");if(x===(f==null?void 0:f.id)&&v.length>1&&(x=v[1].id),x!=null){const y=u.get(l.id),b=u.get(x),w=b?c.get(b.id):null,E=b==null?void 0:b.node.current;if(E&&w&&y&&b){const C=Fu(E).some((A,U)=>p[U]!==A),N=CS(y,b),M=gk(y,b),T=C||!N?{x:0,y:0}:{x:M?s.width-w.width:0,y:M?s.height-w.height:0},D={x:w.left,y:w.top};return T.x&&T.y?D:ni(D,T)}}}};function CS(n,a){return!pu(n)||!pu(a)?!1:n.data.current.sortable.containerId===a.data.current.sortable.containerId}function gk(n,a){return!pu(n)||!pu(a)||!CS(n,a)?!1:n.data.current.sortable.index<a.data.current.sortable.index}const Uh={maxTotalAttempts:3,fallbackOnConnection:!0,fallbackOnConnectTimeout:!0,fallbackOnFirstTokenTimeout:!0,fallbackOn408:!0,fallbackOn429:!0,fallbackOn5xx:!0},vk={member_disabled:"member disabled",model_missing:"model missing",provider_disabled:"provider disabled",provider_down:"provider down",model_disabled:"model disabled",upstream_unavailable:"upstream unavailable",circuit_open:"circuit open",chat_capability_unavailable:"chat capability unavailable"},gu=n=>n.map((a,l)=>({...a,position:l}));function xk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState(!1),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(!1),[b,w]=m.useState(!1),[E,j]=m.useState(null),[C,N]=m.useState(null),[M,T]=m.useState({name:"",slug:"",enabled:!0,...Uh,members:[]}),[D,O]=m.useState({name:"",slug:"",enabled:!0,...Uh,members:[]}),[A,U]=m.useState(null),k=async()=>{const[_,H]=await Promise.all([Se.get("/api/admin/combos"),Se.get("/api/admin/models")]);a(_.combos),s(H.models)};m.useEffect(()=>{k()},[]);const $=async _=>{j(_.id);try{N(await Se.post("/api/admin/combos/"+_.id+"/test"))}catch(H){ve.error(H.message)}finally{j(null)}},X=async()=>{if(M.members.length===0){ve.error("Add at least one member");return}y(!0);try{await Se.post("/api/admin/combos",{name:M.name,slug:M.slug||void 0,enabled:M.enabled,...M,members:M.members}),ve.success("Combo created"),u(!1),T({name:"",slug:"",enabled:!0,...Uh,members:[]}),k()}catch(_){ve.error(_.message)}finally{y(!1)}},te=async _=>{try{const Q=(await Se.get(`/api/admin/combos/${_.id}`)).combo;v(Q.id),O({name:Q.name,slug:Q.publicModelId.startsWith("combo/")?Q.slug:"",enabled:Q.enabled,maxTotalAttempts:Q.maxTotalAttempts,fallbackOnConnection:Q.fallbackOnConnection,fallbackOnConnectTimeout:Q.fallbackOnConnectTimeout,fallbackOnFirstTokenTimeout:Q.fallbackOnFirstTokenTimeout,fallbackOn408:Q.fallbackOn408,fallbackOn429:Q.fallbackOn429,fallbackOn5xx:Q.fallbackOn5xx,members:Q.members.map(J=>({modelId:J.modelId,position:J.position,enabled:J.enabled}))}),p(!0)}catch(H){ve.error(H.message)}},G=async()=>{if(g){if(D.members.length===0){ve.error("Add at least one member");return}w(!0);try{await Se.patch("/api/admin/combos",{id:g,name:D.name,slug:D.slug||void 0,enabled:D.enabled,...D,members:D.members}),ve.success("Combo updated"),p(!1),v(null),k()}catch(_){ve.error(_.message)}finally{w(!1)}}},ie=_=>{T(H=>({...H,members:gu([...H.members,{modelId:_,position:H.members.length,enabled:!0}])}))},ce=_=>{O(H=>({...H,members:gu([...H.members,{modelId:_,position:H.members.length,enabled:!0}])}))},se=async _=>{try{await Se.del(`/api/admin/combos/${_}`),ve.success("Combo removed"),U(null),k()}catch(H){ve.error(H.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Combos",description:"Virtual models combining physical models",actions:o.jsxs(Mn,{open:c,onOpenChange:u,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New combo"]})}),o.jsxs(vn,{className:"max-h-[calc(100vh-2rem)] max-w-2xl grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden",children:[o.jsx(xn,{children:o.jsx(yn,{children:"New combo"})}),o.jsxs("div",{className:"min-h-0 space-y-3 overflow-y-auto pr-1",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:M.name,onChange:_=>T({...M,name:_.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional — empty uses the name as the model ID)"}),o.jsx(Ae,{value:M.slug,onChange:_=>T({...M,slug:_.target.value}),placeholder:"empty → gpt-5.5 · set → combo/gpt-5.5"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:M.enabled,onCheckedChange:_=>T({...M,enabled:_})}),o.jsx(we,{children:"Enabled"})]}),o.jsx(qb,{value:M,onChange:_=>T(H=>({...H,..._}))}),o.jsxs("div",{children:[o.jsx(we,{children:"Members — priority order · drag to reorder"}),o.jsx(Yb,{models:l,addedIds:M.members.map(_=>_.modelId),onAdd:ie}),o.jsx(Vb,{members:M.members,modelFor:_=>l.find(H=>H.id===_.modelId)??null}),o.jsx($b,{className:"mt-2",members:M.members,label:_=>{var H;return((H=l.find(Q=>Q.id===_.modelId))==null?void 0:H.publicModelId)??_.modelId},modelFor:_=>l.find(H=>H.id===_.modelId)??null,onChange:_=>T(H=>({...H,members:_}))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),o.jsx(me,{disabled:!M.name||x,onClick:X,children:x?"Creating…":"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All combos"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Public ID"}),o.jsx(ye,{children:"Members"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:5,className:"text-center text-muted-foreground",children:"No combos yet."})}),n.map(_=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:_.publicModelId}),o.jsx(pe,{children:_.memberCount}),o.jsxs(pe,{children:[o.jsxs(Qe,{variant:_.status==="ready"?"success":_.status==="disabled"?"secondary":"destructive",children:[_.healthyMemberCount,"/",_.memberCount," ready"]}),_.capabilityWarnings.length>0&&o.jsx("div",{className:"text-xs text-amber-600",children:"Capability metadata differs"}),_.status==="unavailable"&&_.unavailableReasons.length>0&&o.jsx("div",{className:"text-xs text-muted-foreground",children:_.unavailableReasons.map(H=>vk[H]??H).join(", ")})]}),o.jsx(pe,{children:_.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[o.jsxs(me,{size:"sm",variant:"outline",title:"Sends a real non-streaming inference request",onClick:()=>void $(_),disabled:E===_.id,children:[E===_.id?o.jsx(_s,{className:"mr-1 h-3.5 w-3.5 animate-spin"}):o.jsx(A0,{className:"mr-1 h-3.5 w-3.5"})," Test"]}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>void te(_),children:[o.jsx(xR,{className:"h-3.5 w-3.5"})," Sửa"]}),o.jsxs(me,{size:"sm",variant:"destructive",onClick:()=>U(_),children:[o.jsx(ju,{className:"h-3.5 w-3.5"})," Delete"]})]})})]},_.id))]})]})})]}),o.jsx(Mn,{open:f,onOpenChange:p,children:o.jsxs(vn,{className:"max-h-[calc(100vh-2rem)] max-w-2xl grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Edit combo"})}),o.jsxs("div",{className:"min-h-0 space-y-3 overflow-y-auto pr-1",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:D.name,onChange:_=>O({...D,name:_.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional — leave empty to use the name as the model ID)"}),o.jsx(Ae,{value:D.slug,onChange:_=>O({...D,slug:_.target.value}),placeholder:"empty → gpt-5.5 · set → combo/gpt-5.5"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:D.enabled,onCheckedChange:_=>O({...D,enabled:_})}),o.jsx(we,{children:"Enabled"})]}),o.jsx(qb,{value:D,onChange:_=>O(H=>({...H,..._}))}),o.jsxs("div",{children:[o.jsx(we,{children:"Members — priority order · drag to reorder"}),o.jsx(Yb,{models:l,addedIds:D.members.map(_=>_.modelId),onAdd:ce}),o.jsx(Vb,{members:D.members,modelFor:_=>l.find(H=>H.id===_.modelId)??null}),o.jsx($b,{className:"mt-2",members:D.members,label:_=>{var H;return((H=l.find(Q=>Q.id===_.modelId))==null?void 0:H.publicModelId)??_.modelId},modelFor:_=>l.find(H=>H.id===_.modelId)??null,onChange:_=>O(H=>({...H,members:_}))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(me,{disabled:!D.name||b,onClick:G,children:b?"Saving…":"Save"})]})]})}),o.jsx(Mn,{open:C!==null,onOpenChange:_=>{_||N(null)},children:o.jsxs(vn,{className:"max-w-2xl",children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"Combo test result"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Test sends a real non-streaming inference request through this combo."})]}),C&&o.jsx(yk,{result:C}),o.jsx(An,{children:o.jsx(me,{onClick:()=>N(null),children:"Close"})})]})}),o.jsx(up,{open:A!==null,onOpenChange:_=>{_||U(null)},children:o.jsxs(Pu,{children:[o.jsxs(dp,{children:[o.jsx(qu,{children:"Delete combo?"}),o.jsx(Vu,{children:"This removes the virtual model and its ordered fallback configuration. Request history is preserved."})]}),o.jsxs(fp,{children:[o.jsx(Yu,{children:"Cancel"}),o.jsx($u,{onClick:()=>A&&void se(A.id),children:"Delete"})]})]})})]})}function qb({value:n,onChange:a}){const l=[["fallbackOnConnection","Connection failure"],["fallbackOnConnectTimeout","Connect timeout"],["fallbackOnFirstTokenTimeout","First-token timeout"],["fallbackOn408","HTTP 408"],["fallbackOn429","HTTP 429"],["fallbackOn5xx","HTTP 5xx"]];return o.jsxs("div",{className:"rounded border bg-muted/20 p-3",children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Fallback policy"}),o.jsxs("div",{className:"grid gap-3 sm:grid-cols-[10rem_1fr]",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Max total attempts"}),o.jsx(Ae,{type:"number",min:1,max:8,value:n.maxTotalAttempts,onChange:s=>a({maxTotalAttempts:Math.min(8,Math.max(1,Number(s.target.value)||1))})})]}),o.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:l.map(([s,c])=>o.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[o.jsx(Ca,{checked:!!n[s],onCheckedChange:u=>a({[s]:u})}),o.jsx("span",{children:c})]},s))})]})]})}function Vb({members:n,modelFor:a}){if(n.length===0)return null;const l=n.map(a).filter(c=>!!c),s=["chat","streaming","tools","structured_output","image_input","reasoning"].filter(c=>new Set(l.map(u=>u.capabilities[c]===!0?"yes":u.capabilities[c]===!1?"no":"unknown")).size>1);return o.jsxs("div",{className:"rounded border bg-muted/20 p-2 text-xs",children:[o.jsxs("div",{className:"mb-1 font-medium",children:["Route preview ",o.jsx("span",{className:"font-normal text-muted-foreground",children:"(first available member wins)"})]}),s.length>0&&o.jsxs("div",{className:"mb-2 flex items-center gap-1 text-amber-600",children:[o.jsx(O0,{className:"h-3.5 w-3.5"})," Members differ on: ",s.join(", ")]}),o.jsx("div",{className:"space-y-1",children:n.map((c,u)=>{const f=a(c);return o.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[o.jsxs("span",{className:"w-4 text-muted-foreground",children:[u+1,"."]}),o.jsx("span",{children:(f==null?void 0:f.publicModelId)??c.modelId}),o.jsxs("span",{className:"text-muted-foreground",children:["→ ",(f==null?void 0:f.upstreamModelId)??"upstream model unknown"]})]},c.id??c.modelId)})})]})}function yk({result:n}){return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between rounded border p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[n.success?o.jsx(ci,{className:"h-4 w-4 text-emerald-600"}):o.jsx(O0,{className:"h-4 w-4 text-amber-600"}),o.jsx(Qe,{variant:n.success?"success":"warning",children:n.success?"Success":"Failed"})]}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.latencyMs," ms total"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-sm font-medium",children:"Selected upstream"}),n.selectedModel?o.jsxs("div",{className:"rounded border bg-muted/20 p-2 font-mono text-xs",children:[n.selectedModel.publicModelId," → ",n.selectedModel.upstreamModelId,o.jsxs("span",{className:"ml-2 text-muted-foreground",children:["(",n.selectedModel.providerSlug,")"]})]}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"No member completed successfully."})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-sm font-medium",children:"Attempts"}),o.jsx("div",{className:"space-y-1",children:n.attempts.map((a,l)=>o.jsxs("div",{className:"flex items-center gap-2 rounded border p-2 text-xs",children:[o.jsxs("span",{className:"w-4 text-muted-foreground",children:[l+1,"."]}),o.jsxs("span",{className:"min-w-0 flex-1 font-mono",children:[a.publicModelId," → ",a.upstreamModelId]}),o.jsxs("span",{className:"text-muted-foreground",children:[a.latencyMs," ms"]}),o.jsx(Qe,{variant:a.success?"success":"warning",children:a.success?"Used":a.failureReason??"Skipped"})]},a.publicModelId+"-"+l))})]}),n.text&&o.jsx("pre",{className:"max-h-32 overflow-auto whitespace-pre-wrap rounded border bg-muted/20 p-2 text-xs",children:n.text})]})}function $b({members:n,label:a,modelFor:l,onChange:s,className:c}){const u=P_(Mb(Dp,{activationConstraint:{distance:4}}),Mb(Mp,{coordinateGetter:pk}));if(n.length===0)return o.jsx("p",{className:Ee("text-xs text-muted-foreground",c),children:"No members yet — add at least one."});const f=({active:p,over:g})=>{!g||p.id===g.id||s(gu(Op(n,Number(p.id),Number(g.id))))};return o.jsx(V3,{sensors:u,collisionDetection:V_,modifiers:[W3,J3],onDragEnd:f,children:o.jsx(lk,{items:n.map((p,g)=>g),strategy:ak,children:o.jsx("div",{className:Ee("space-y-1",c),children:n.map((p,g)=>o.jsx(bk,{index:g,label:a(p),model:l(p),onRemove:()=>s(gu(n.filter((v,x)=>x!==g)))},p.id??p.modelId))})})})}function bk({index:n,label:a,model:l,onRemove:s}){const{attributes:c,listeners:u,setNodeRef:f,transform:p,transition:g,isDragging:v}=fk({id:n});return o.jsxs("div",{ref:f,style:{transform:p?`translate3d(${p.x}px, ${p.y}px, 0)`:void 0,transition:g},className:Ee("flex items-center gap-2 rounded border p-2 text-sm",v&&"relative z-10 bg-muted/60 shadow-sm"),children:[o.jsx("button",{type:"button",...c,...u,"aria-label":`Reorder ${a}`,title:"Drag to change priority",className:"cursor-grab touch-none rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground active:cursor-grabbing",children:o.jsx(cR,{className:"h-4 w-4"})}),o.jsx("span",{className:"w-5 text-xs tabular-nums text-muted-foreground",children:n+1}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate font-mono text-xs",children:a}),o.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[(l==null?void 0:l.providerSlug)||"provider"," · upstream: ",(l==null?void 0:l.upstreamModelId)??"unknown"]})]}),o.jsx(Qe,{variant:l&&l.enabled&&l.providerEnabled&&l.providerHealth!=="down"&&l.providerHealth!=="circuit_open"&&!l.circuitOpen&&l.upstreamAvailable&&l.capabilities.chat!==!1?"success":"warning",children:l&&l.enabled&&l.providerEnabled&&l.providerHealth!=="down"&&l.providerHealth!=="circuit_open"&&!l.circuitOpen&&l.upstreamAvailable&&l.capabilities.chat!==!1?"Ready":"Unavailable"}),o.jsx(me,{size:"sm",variant:"outline",onClick:s,children:"Remove"})]})}function Yb({models:n,addedIds:a,onAdd:l}){const[s,c]=m.useState(""),f=(s?n.filter(p=>{const g=s.toLowerCase();return p.publicModelId.toLowerCase().includes(g)||p.displayName.toLowerCase().includes(g)}):n).filter(p=>!a.includes(p.id));return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"relative",children:[o.jsx(D0,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(Ae,{className:"pl-8",placeholder:"Search models…",value:s,onChange:p=>c(p.target.value)}),s&&o.jsx("button",{className:"absolute right-2 top-2.5 text-muted-foreground hover:text-foreground",onClick:()=>c(""),children:o.jsx(Cu,{className:"h-4 w-4"})})]}),f.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No models match."}):o.jsx("div",{className:"max-h-40 space-y-1 overflow-auto rounded border p-1",children:f.map(p=>o.jsxs("div",{className:"flex items-center justify-between rounded p-1 text-sm hover:bg-accent",children:[o.jsx("span",{className:"font-mono text-xs",children:p.publicModelId}),o.jsx(me,{size:"sm",variant:"ghost",onClick:()=>l(p.id),children:"+ Add"})]},p.id))})]})}function wk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState([]),[f,p]=m.useState(!1),[g,v]=m.useState({alias:"",targetKind:"model",targetId:"",enabled:!0}),x=async()=>{const[b,w,E]=await Promise.all([Se.get("/api/admin/aliases"),Se.get("/api/admin/models"),Se.get("/api/admin/combos")]);a(b.aliases),s(w.models),u(E.combos)};m.useEffect(()=>{x()},[]);const y=async()=>{try{await Se.post("/api/admin/aliases",g),ve.success("Alias created"),p(!1),v({alias:"",targetKind:"model",targetId:"",enabled:!0}),x()}catch(b){ve.error(b.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Aliases",description:"Stable client-visible names for models or combos",actions:o.jsxs(Mn,{open:f,onOpenChange:p,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New alias"]})}),o.jsxs(vn,{children:[o.jsx(xn,{children:o.jsx(yn,{children:"New alias"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Alias"}),o.jsx(Ae,{value:g.alias,onChange:b=>v({...g,alias:b.target.value}),placeholder:"coding"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Target type"}),o.jsxs(Ua,{value:g.targetKind,onValueChange:b=>v({...g,targetKind:b}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"model",children:"Model"}),o.jsx(Rt,{value:"combo",children:"Combo"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Target"}),o.jsxs(Ua,{value:g.targetId,onValueChange:b=>v({...g,targetId:b}),children:[o.jsx(Sa,{children:o.jsx(Ba,{placeholder:"Choose target"})}),o.jsx(ja,{children:(g.targetKind==="model"?l:c).map(b=>o.jsx(Rt,{value:b.id,children:b.publicModelId},b.id))})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:g.enabled,onCheckedChange:b=>v({...g,enabled:b})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(me,{disabled:!g.alias||!g.targetId,onClick:y,children:"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All aliases"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Alias"}),o.jsx(ye,{children:"Target"}),o.jsx(ye,{children:"Type"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:5,className:"text-center text-muted-foreground",children:"No aliases yet."})}),n.map(b=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:b.alias}),o.jsx(pe,{className:"font-mono text-xs",children:b.targetName??b.targetId}),o.jsx(pe,{children:o.jsx(Qe,{variant:"outline",children:b.targetKind})}),o.jsx(pe,{children:b.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsx(me,{size:"sm",variant:"outline",onClick:async()=>{await Se.del(`/api/admin/aliases/${b.id}`),ve.success("Removed"),x()},children:"Delete"})})]},b.id))]})]})})]})]})}function Sk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState([]),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(null),[E,j]=m.useState({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),C=async()=>{const[A,U,k]=await Promise.all([Se.get("/api/admin/api-keys"),Se.get("/api/admin/models"),Se.get("/api/admin/combos")]);a(A.apiKeys),s(U.models),u(k.combos)};m.useEffect(()=>{C()},[]);const N=async()=>{try{if(g){await Se.patch("/api/admin/api-keys",{id:g,name:E.name,expiresAt:E.expiresAt||null,allowAllModels:E.allowAll,permissions:E.allowAll?[]:E.permissions,rpmLimit:E.rpmLimit?Number(E.rpmLimit):null,tpmLimit:E.tpmLimit?Number(E.tpmLimit):null,maxConcurrent:E.concurrency?Number(E.concurrency):null}),p(!1),v(null),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),ve.success("Key updated"),C();return}const A=await Se.post("/api/admin/api-keys",{name:E.name,expiresAt:E.expiresAt||null,allowAllModels:E.allowAll,permissions:E.allowAll?void 0:E.permissions,rpmLimit:E.rpmLimit?Number(E.rpmLimit):null,tpmLimit:E.tpmLimit?Number(E.tpmLimit):null,maxConcurrent:E.concurrency?Number(E.concurrency):null,...E.customSecret.trim()?{secret:E.customSecret.trim()}:{}});p(!1),y({secret:A.secret,name:A.name}),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),C()}catch(A){ve.error(A.message)}},M=async A=>{try{const k=((await Se.get(`/api/admin/api-keys/${A.id}`)).apiKey.permissions??[]).filter($=>$.targetKind==="model"||$.targetKind==="combo");v(A.id),j({name:A.name,expiresAt:A.expiresAt?A.expiresAt.slice(0,16):"",allowAll:A.allowAllModels,permissions:k,rpmLimit:A.rpmLimit!=null?String(A.rpmLimit):"",tpmLimit:A.tpmLimit!=null?String(A.tpmLimit):"",concurrency:A.concurrencyLimit!=null?String(A.concurrencyLimit):"",customSecret:""}),p(!0)}catch(U){ve.error(U.message)}},T=()=>{p(!1),v(null),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""})},D=async(A,U)=>{try{await Se.patch("/api/admin/api-keys",{id:A,enabled:!U}),ve.success(U?"Key disabled":"Key enabled"),C()}catch(k){ve.error(k.message)}},O=async A=>{if(window.confirm("Delete this API key? This cannot be undone."))try{await Se.del(`/api/admin/api-keys/${A}`),ve.success("Key deleted"),C()}catch(U){ve.error(U.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"API Keys",description:"Gateway bearer keys for client applications",actions:o.jsxs(Mn,{open:f,onOpenChange:A=>{A?p(!0):T()},children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New key"]})}),o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:g?"Edit API key":"New API key"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:E.name,onChange:A=>j({...E,name:A.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Expires (optional)"}),o.jsx(Ae,{type:"datetime-local",value:E.expiresAt,onChange:A=>j({...E,expiresAt:A.target.value})})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[o.jsxs("div",{children:[o.jsx(we,{children:"RPM limit"}),o.jsx(Ae,{value:E.rpmLimit,onChange:A=>j({...E,rpmLimit:A.target.value}),type:"number"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"TPM limit"}),o.jsx(Ae,{value:E.tpmLimit,onChange:A=>j({...E,tpmLimit:A.target.value}),type:"number"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Concurrency"}),o.jsx(Ae,{value:E.concurrency,onChange:A=>j({...E,concurrency:A.target.value}),type:"number"})]})]}),!g&&o.jsxs("div",{children:[o.jsx(we,{children:"Key value (optional)"}),o.jsx(Ae,{value:E.customSecret,onChange:A=>j({...E,customSecret:A.target.value}),placeholder:"Leave empty to auto-generate ld-…"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"If provided, this exact value is stored as the key. Otherwise a random ld-… key is generated."})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:E.allowAll,onCheckedChange:A=>j({...E,allowAll:A})}),o.jsx(we,{children:"Allow all current and future models"})]}),!E.allowAll&&o.jsxs("div",{children:[o.jsx(we,{children:"Scope"}),o.jsx("div",{className:"max-h-48 space-y-1 overflow-auto rounded border p-2",children:[...l.map(A=>({targetKind:"model",targetId:A.id,label:A.publicModelId})),...c.map(A=>({targetKind:"combo",targetId:A.id,label:A.publicModelId}))].map(A=>{const U=E.permissions.some(k=>k.targetKind===A.targetKind&&k.targetId===A.targetId);return o.jsxs("label",{className:"flex items-center gap-2 rounded p-1 text-sm hover:bg-accent",children:[o.jsx(jp,{checked:U,onCheckedChange:k=>{j($=>({...$,permissions:k?[...$.permissions,{targetKind:A.targetKind,targetId:A.targetId}]:$.permissions.filter(X=>!(X.targetKind===A.targetKind&&X.targetId===A.targetId))}))}}),o.jsx("span",{className:"font-mono text-xs",children:A.label}),o.jsx(Qe,{variant:"outline",className:"ml-1",children:A.targetKind})]},`${A.targetKind}:${A.targetId}`)})})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:T,children:"Cancel"}),o.jsx(me,{disabled:!E.name,onClick:N,children:g?"Save changes":"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All keys"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Name"}),o.jsx(ye,{children:"Prefix"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Scope"}),o.jsx(ye,{children:"RPM/TPM/Conc"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:6,className:"text-center text-muted-foreground",children:"No API keys yet."})}),n.map(A=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-medium",children:A.name}),o.jsxs(pe,{className:"font-mono text-xs",children:[A.keyPrefix,"…"]}),o.jsx(pe,{children:A.enabled?o.jsx(Qe,{variant:"success",children:"enabled"}):o.jsx(Qe,{variant:"destructive",children:"disabled"})}),o.jsx(pe,{children:A.allowAllModels?"all":`${A.modelScopeCount} scoped`}),o.jsx(pe,{className:"text-xs",children:[A.rpmLimit,A.tpmLimit,A.concurrencyLimit].map((U,k)=>U?["","RPM","TPM","Conc"][k+1]:null).filter(Boolean).join(" / ")||"—"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[A.secret&&o.jsxs(o.Fragment,{children:[o.jsx(me,{size:"sm",variant:"ghost",title:"Copy secret",onClick:()=>{navigator.clipboard.writeText(A.secret),ve.success("Copied")},children:o.jsx(Fc,{className:"h-3.5 w-3.5"})}),o.jsx(me,{size:"sm",variant:"ghost",title:"Show secret",onClick:()=>w({secret:A.secret,name:A.name}),children:o.jsx(sR,{className:"h-3.5 w-3.5"})})]}),o.jsx(me,{size:"sm",variant:"ghost",title:"Edit",onClick:()=>void M(A),children:o.jsx(hR,{className:"h-3.5 w-3.5"})}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>D(A.id,A.enabled),children:[A.enabled?o.jsx(FE,{className:"mr-1 h-3.5 w-3.5"}):o.jsx(ci,{className:"mr-1 h-3.5 w-3.5"}),A.enabled?"Disable":"Enable"]}),o.jsx(me,{size:"sm",variant:"destructive",onClick:()=>O(A.id),children:o.jsx(ju,{className:"h-3.5 w-3.5"})})]})})]},A.id))]})]})})]}),o.jsx(Mn,{open:!!x,onOpenChange:A=>{A||y(null)},children:o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"API key created"}),o.jsx(uu,{children:"Copy now — this secret will not be shown again."})]}),o.jsx("div",{className:"rounded border bg-muted p-3 font-mono text-xs break-all",children:x==null?void 0:x.secret}),o.jsxs(An,{children:[o.jsxs(me,{onClick:()=>{x&&(navigator.clipboard.writeText(x.secret),ve.success("Copied"))},children:[o.jsx(Fc,{className:"mr-1 h-4 w-4"})," Copy"]}),o.jsx(me,{variant:"outline",onClick:()=>y(null),children:"I have saved it"})]})]})}),o.jsx(Mn,{open:!!b,onOpenChange:A=>{A||w(null)},children:o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsxs(yn,{children:["API key: ",b==null?void 0:b.name]}),o.jsx(uu,{children:"Full secret for this key, readable any time."})]}),o.jsx("div",{className:"rounded border bg-muted p-3 font-mono text-xs break-all",children:b==null?void 0:b.secret}),o.jsxs(An,{children:[o.jsxs(me,{onClick:()=>{b&&(navigator.clipboard.writeText(b.secret),ve.success("Copied"))},children:[o.jsx(Fc,{className:"mr-1 h-4 w-4"})," Copy"]}),o.jsx(me,{variant:"outline",onClick:()=>w(null),children:"Close"})]})]})})]})}const jk=3e3;function Ck(n,a){return!(a.success!=="all"&&n.success!==(a.success==="true")||a.protocol!=="all"&&n.protocol!==a.protocol||a.streaming!=="all"&&n.streaming!==(a.streaming==="true")||a.model&&!n.requestedModel.toLowerCase().includes(a.model.toLowerCase()))}function Ek(){const[n,a]=m.useState([]),[l,s]=m.useState(0),[c,u]=m.useState(0),[f,p]=m.useState({success:"all",protocol:"all",streaming:"all",model:""}),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(0),E=50,j=m.useRef(Date.now()),C=m.useRef(new Set),N=m.useRef(f);N.current=f;const M=m.useRef(c);M.current=c;const T=m.useCallback(async()=>{const O=new URLSearchParams;O.set("limit",String(E)),O.set("offset",String(c)),f.success!=="all"&&O.set("success",f.success),f.protocol!=="all"&&O.set("protocol",f.protocol),f.streaming!=="all"&&O.set("streaming",f.streaming),f.model&&O.set("requestedModel",f.model);const A=await Se.get(`/api/admin/requests?${O.toString()}`);a(A.requests),s(A.total);for(const U of A.requests)C.current.add(U.id)},[c,f]);m.useEffect(()=>{T()},[T]),m.useEffect(()=>{w(0)},[c,f]),m.useEffect(()=>{let O=!1,A=null;const U=new Set,k=()=>{O||(A=new EventSource(`/api/admin/requests/stream?since=${j.current}`),A.addEventListener("request",$=>{if(!O)try{const X=JSON.parse($.data),te=new Date(X.createdAt).getTime();if(Number.isFinite(te)&&(j.current=Math.max(j.current,te)),C.current.has(X.id))return;C.current.add(X.id),w(G=>G+1),M.current===0&&Ck(X,N.current)&&(a(G=>G.some(ie=>ie.id===X.id)?G:[X,...G].slice(0,E)),s(G=>G+1))}catch{}}),A.onerror=()=>{A==null||A.close(),A=null,O||U.add(setTimeout(k,jk))})};return k(),()=>{O=!0,A==null||A.close();for(const $ of U)clearTimeout($);U.clear()}},[]);const D=async O=>{v(O);const A=await Se.get(`/api/admin/requests/${O}`);y(A)};return o.jsxs("div",{children:[o.jsx($a,{title:"Requests",description:`${l} matching · live updates`}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Ua,{value:f.success,onValueChange:O=>{u(0),p({...f,success:O})},children:[o.jsx(Sa,{className:"w-36",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"All"}),o.jsx(Rt,{value:"true",children:"Success"}),o.jsx(Rt,{value:"false",children:"Failed"})]})]}),o.jsxs(Ua,{value:f.protocol,onValueChange:O=>{u(0),p({...f,protocol:O})},children:[o.jsx(Sa,{className:"w-32",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"Any protocol"}),o.jsx(Rt,{value:"openai",children:"OpenAI"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic"})]})]}),o.jsxs(Ua,{value:f.streaming,onValueChange:O=>{u(0),p({...f,streaming:O})},children:[o.jsx(Sa,{className:"w-32",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"Any"}),o.jsx(Rt,{value:"true",children:"Streaming"}),o.jsx(Rt,{value:"false",children:"Non-stream"})]})]}),o.jsx(Ae,{className:"max-w-xs",placeholder:"Model contains…",value:f.model,onChange:O=>{u(0),p({...f,model:O.target.value})}}),b>0&&o.jsxs(me,{size:"sm",variant:"secondary",onClick:()=>{w(0),T()},children:[b," new request",b>1?"s":""," — refresh"]})]}),o.jsx(rt,{className:"mt-3 text-base",children:"Results"})]}),o.jsxs(lt,{children:[o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Time"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Requested"}),o.jsx(ye,{children:"Final"}),o.jsx(ye,{children:"Tokens"}),o.jsx(ye,{children:"Latency"}),o.jsx(ye,{children:"Attempts"}),o.jsx(ye,{children:"Key"}),o.jsx(ye,{children:"IP"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:10,className:"text-center text-muted-foreground",children:"No requests yet."})}),n.map(O=>o.jsxs(We,{className:"cursor-pointer",onClick:()=>D(O.id),children:[o.jsx(pe,{className:"text-xs",children:Lm(O.createdAt)}),o.jsx(pe,{children:O.success?o.jsx(Qe,{variant:"success",children:O.httpStatus}):o.jsx(Qe,{variant:"destructive",children:O.httpStatus})}),o.jsx(pe,{className:"font-mono text-xs",children:O.requestedModel}),o.jsx(pe,{className:"font-mono text-xs text-muted-foreground",children:O.finalModelPublicId??"—"}),o.jsxs(pe,{className:"text-xs",children:[Kt(O.inputTokens+O.outputTokens)," ",O.cacheReadTokens?o.jsxs("span",{className:"text-amber-600",children:["(+",O.cacheReadTokens," cache)"]}):null]}),o.jsxs(pe,{className:"text-xs",children:[Ol(O.totalLatencyMs),O.ttftMs?o.jsxs("span",{className:"text-muted-foreground",children:[" · ttft ",O.ttftMs,"ms"]}):null]}),o.jsxs(pe,{className:"text-xs",children:[O.attemptsCount,O.gatewayCacheHit?o.jsx(Qe,{variant:"secondary",className:"ml-1",children:"cache"}):null]}),o.jsx(pe,{className:"text-xs",children:O.apiKeyName??"—"}),o.jsx(pe,{className:"text-xs",children:O.clientIp}),o.jsx(pe,{className:"text-right",children:o.jsx(me,{size:"sm",variant:"ghost",children:"View"})})]},O.id))]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("span",{className:"text-xs text-muted-foreground",children:["Showing ",c+1,"–",Math.min(c+E,l)," of ",l]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(me,{size:"sm",variant:"outline",disabled:c===0,onClick:()=>u(Math.max(0,c-E)),children:"Prev"}),o.jsx(me,{size:"sm",variant:"outline",disabled:c+E>=l,onClick:()=>u(c+E),children:"Next"})]})]})]})]}),o.jsx(Mn,{open:!!g,onOpenChange:O=>{O||(v(null),y(null))},children:o.jsxs(vn,{className:"max-w-3xl",children:[o.jsx(xn,{children:o.jsxs(yn,{children:["Request ",tN(g,16)]})}),x?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Requested model"}),o.jsx("span",{className:"font-mono text-xs",children:x.request.requestedModel})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Upstream model"}),o.jsx("span",{className:"font-mono text-xs",children:x.request.finalModelUpstreamId??"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Provider"}),x.request.providerId?o.jsx(ra,{className:"text-primary underline",to:`/providers?providerId=${encodeURIComponent(x.request.providerId)}`,children:x.request.providerName??x.request.providerSlug??x.request.providerId}):"—"]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Route"}),x.request.resolvedTargetId?o.jsx(ra,{className:"text-primary underline",to:x.request.resolvedTargetKind==="combo"?"/combos":"/models",children:x.request.resolvedTargetKind??"target"}):"—"]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Status"}),x.request.success?o.jsx(Qe,{variant:"success",children:x.request.httpStatus}):o.jsx(Qe,{variant:"destructive",children:x.request.httpStatus})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Latency"}),Ol(x.request.totalLatencyMs)]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Tokens"}),"in ",Kt(x.request.inputTokens)," · out ",Kt(x.request.outputTokens)," · cache ",Kt(x.request.cacheReadTokens)]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Attempts"}),x.request.attemptsCount]})]}),x.request.errorType&&o.jsxs("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Error"}),o.jsxs("div",{className:"font-mono text-xs",children:[x.request.errorType,": ",x.request.errorMessage]})]}),x.request.fallbackReasons.length>0&&o.jsxs("div",{className:"rounded border border-amber-500/40 bg-amber-500/10 p-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Fallback reasons"}),o.jsx("div",{className:"text-xs",children:x.request.fallbackReasons.join(", ")})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"Safe replay curl"}),o.jsxs(me,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(x.request.reproductionCurl).then(()=>ve.success("Curl copied"))},children:[o.jsx(Fc,{className:"mr-1 h-3.5 w-3.5"})," Copy"]})]}),o.jsx("pre",{className:"max-h-36 overflow-auto whitespace-pre-wrap rounded bg-muted p-2 font-mono text-xs",children:x.request.reproductionCurl}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Replace the placeholder key before running. No stored secret is included."})]}),x.request.requestPayload&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Request content"}),o.jsx("pre",{className:"max-h-60 overflow-auto rounded bg-muted p-2 font-mono text-xs whitespace-pre-wrap",children:x.request.requestPayload})]}),x.request.responsePayload&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Response content"}),o.jsx("pre",{className:"max-h-60 overflow-auto rounded bg-muted p-2 font-mono text-xs whitespace-pre-wrap",children:x.request.responsePayload})]}),x.attempts.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Attempts"}),o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"#"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Latency"}),o.jsx(ye,{children:"Reason"})]})}),o.jsx(da,{children:x.attempts.map(O=>o.jsxs(We,{children:[o.jsx(pe,{children:O.attemptNumber}),o.jsx(pe,{children:O.providerName}),o.jsxs(pe,{children:[o.jsx("div",{className:"font-mono text-xs",children:O.modelPublicId}),o.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["upstream: ",O.upstreamModelId]})]}),o.jsx(pe,{children:O.success?o.jsx(Qe,{variant:"success",children:String(O.statusCode??"OK")}):o.jsx(Qe,{variant:"destructive",children:String(O.statusCode??"err")})}),o.jsx(pe,{className:"text-xs",children:Ol(O.latencyMs)}),o.jsx(pe,{className:"text-xs",children:O.failureReason??O.selectionReason})]},O.id))})]})]})]}):o.jsx("div",{className:"text-muted-foreground",children:"Loading…"})]})})]})}var Rk=Object.defineProperty,Zs=(n,a)=>Rk(n,"name",{value:a,configurable:!0}),_p="Tabs",[Nk,Z4]=kn(_p,[Lu]),ES=Lu(),[Tk,kp]=Nk(_p),Mk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,onValueChange:u,defaultValue:f,orientation:p="horizontal",dir:g,activationMode:v="automatic",...x}=a,y=di(g),[b,w]=yr({prop:c,onChange:u,defaultProp:f??"",caller:_p});return o.jsx(Tk,{scope:s,baseId:La(),value:b,onValueChange:w,orientation:p,dir:y,activationMode:v,children:o.jsx(Ve.div,{dir:y,"data-orientation":p,...x,ref:l})})},"Tabs")),Ak="TabsList",Dk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,loop:c=!0,...u}=a,f=kp(Ak,s),p=ES(s);return o.jsx(G1,{asChild:!0,...p,orientation:f.orientation,dir:f.dir,loop:c,children:o.jsx(Ve.div,{role:"tablist","aria-orientation":f.orientation,...u,ref:l})})},"TabsList")),Ok="TabsTrigger",_k=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,disabled:u=!1,...f}=a,p=kp(Ok,s),g=ES(s),v=zp(p.baseId,c),x=Lp(p.baseId,c),y=c===p.value;return o.jsx(K1,{asChild:!0,...g,focusable:!u,active:y,children:o.jsx(Ve.button,{type:"button",role:"tab","aria-selected":y,"aria-controls":x,"data-state":y?"active":"inactive","data-disabled":u?"":void 0,disabled:u,id:v,...f,ref:l,onMouseDown:Ne(a.onMouseDown,b=>{!u&&b.button===0&&b.ctrlKey===!1?p.onValueChange(c):b.preventDefault()}),onKeyDown:Ne(a.onKeyDown,b=>{u||b.target!==b.currentTarget||[" ","Enter"].includes(b.key)&&p.onValueChange(c)}),onFocus:Ne(a.onFocus,()=>{const b=p.activationMode!=="manual";!y&&!u&&b&&p.onValueChange(c)})})})},"TabsTrigger")),kk="TabsContent",zk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,forceMount:u,children:f,...p}=a,g=kp(kk,s),v=zp(g.baseId,c),x=Lp(g.baseId,c),y=c===g.value,b=m.useRef(y);return m.useEffect(()=>{const w=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(w)},[]),o.jsx(Cr,{present:u||y,children:({present:w})=>o.jsx(Ve.div,{"data-state":y?"active":"inactive","data-orientation":g.orientation,role:"tabpanel","aria-labelledby":v,hidden:!w,id:x,tabIndex:0,...p,ref:l,style:{...a.style,animationDuration:b.current?"0s":void 0},children:w&&f})})},"TabsContent"));function zp(n,a){return`${n}-trigger-${a}`}Zs(zp,"makeTriggerId");function Lp(n,a){return`${n}-content-${a}`}Zs(Lp,"makeContentId");var Lk=Mk,RS=Dk,NS=_k,TS=zk;const MS=Lk,Up=m.forwardRef(({className:n,...a},l)=>o.jsx(RS,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",n),...a}));Up.displayName=RS.displayName;const mr=m.forwardRef(({className:n,...a},l)=>o.jsx(NS,{ref:l,className:Ee("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",n),...a}));mr.displayName=NS.displayName;const Os=m.forwardRef(({className:n,...a},l)=>o.jsx(TS,{ref:l,className:Ee("mt-2 ring-offset-background focus-visible:outline-none",n),...a}));Os.displayName=TS.displayName;const Uk=3e3,Bk=1600,Hk=10,Ik=3,Pk=12,qk=10*6e4,Vk={cacheReadTokens:0,promptTokens:0,gatewayCacheHits:0,fallbacks:0};function AS(n,a,l){return l==="anthropic"?n+a:n}function $k(n){return n.promptTokens>0?n.cacheReadTokens/n.promptTokens:0}function Yk(n,a){return a>0?n.fallbacks/a:0}function Gk(n,a){return a>0?n.gatewayCacheHits/a:0}function Kk(n,a,l){const s=n.totalRequests+1,c=n.successfulRequests+(l.success?1:0),u={cacheReadTokens:a.cacheReadTokens+l.cacheReadTokens,promptTokens:a.promptTokens+AS(l.inputTokens,l.cacheReadTokens,l.providerType),gatewayCacheHits:a.gatewayCacheHits+(l.gatewayCacheHit?1:0),fallbacks:a.fallbacks+(l.attemptsCount>1?1:0)};return{...n,...u,totalRequests:s,successfulRequests:c,failedRequests:n.failedRequests+(l.success?0:1),successRate:c/s,inputTokens:n.inputTokens+l.inputTokens,outputTokens:n.outputTokens+l.outputTokens,totalTokens:n.totalTokens+l.inputTokens+l.outputTokens,cacheHitRate:$k(u),gatewayCacheHitRate:Gk(u,s),fallbackRate:Yk(u,s),averageLatencyMs:(n.averageLatencyMs*n.totalRequests+l.totalLatencyMs)/s}}function Xk(n){const[a,l]=m.useState(null),[s,c]=m.useState(null),[u,f]=m.useState([]),[p,g]=m.useState([]),[v,x]=m.useState([]),[y,b]=m.useState([]),[w,E]=m.useState(!0),[j,C]=m.useState(null),N=m.useRef([]),M=m.useRef(null),T=m.useRef(Vk),D=m.useRef(new Set),O=m.useRef(Date.now()),A=m.useRef(0),U=m.useRef([]),k=m.useRef([]);return m.useEffect(()=>{let $=!1;return E(!0),C(null),D.current=new Set,O.current=Date.now(),Se.get(`/api/admin/stats?preset=${n}`).then(X=>{if(!$){l(X),c(X.summary),M.current=X.summary,T.current={cacheReadTokens:X.summary.cacheReadTokens,promptTokens:X.summary.cacheHitRate>0?Math.round(X.summary.cacheReadTokens/X.summary.cacheHitRate):X.summary.inputTokens,gatewayCacheHits:Math.round(X.summary.gatewayCacheHitRate*X.summary.totalRequests),fallbacks:Math.round(X.summary.fallbackRate*X.summary.totalRequests)},f(X.recent),g(X.providers),N.current=X.providers;for(const te of X.recent)D.current.add(te.id);E(!1)}}).catch(X=>{$||(C(X.message),E(!1))}),()=>{$=!0}},[n]),m.useEffect(()=>{let $=!1,X=null;const te=new Set,G=()=>{$||(X=new EventSource(`/api/admin/requests/stream?since=${O.current}`),X.addEventListener("request",ce=>{if(!$)try{const se=JSON.parse(ce.data),_=new Date(se.createdAt).getTime();if(Number.isFinite(_)&&(O.current=Math.max(O.current,_)),D.current.has(se.id))return;D.current.add(se.id);const H={cacheReadTokens:T.current.cacheReadTokens+se.cacheReadTokens,promptTokens:T.current.promptTokens+AS(se.inputTokens,se.cacheReadTokens,se.providerType),gatewayCacheHits:T.current.gatewayCacheHits+(se.gatewayCacheHit?1:0),fallbacks:T.current.fallbacks+(se.attemptsCount>1?1:0)};if(T.current=H,M.current&&c(Kk(M.current,H,se)),f(Q=>Q.some(J=>J.id===se.id)?Q:[se,...Q].slice(0,Hk)),se.providerId){N.current=N.current.map(z=>z.id===se.providerId?{...z,requests:z.requests+1,errorRate:z.requests+1?(z.errorRate*z.requests+(se.success?0:1))/(z.requests+1):0}:z),g(N.current);const Q=`p${++A.current}`,J={id:Q,providerId:se.providerId,success:se.success};U.current=[...U.current.slice(-(Ik*4)),J],x(U.current);const ee=setTimeout(()=>{U.current=U.current.filter(z=>z.id!==Q),x(U.current)},Bk);te.add(ee)}k.current.some(Q=>Q.id===se.id)&&(k.current=k.current.filter(Q=>Q.id!==se.id),b(k.current))}catch{}}),X.addEventListener("request_started",ce=>{if(!$)try{const se=JSON.parse(ce.data);if(!se.providerId||se.providerId==="")return;k.current=[...k.current.filter(_=>_.id!==se.requestId).slice(-(Pk-1)),{id:se.requestId,providerId:se.providerId,startedAt:Date.now(),ttftMs:se.ttftMs??0}],b(k.current)}catch{}}),X.onerror=()=>{X==null||X.close(),X=null,$||te.add(setTimeout(G,Uk))})};G();const ie=setInterval(()=>{const ce=Date.now()-qk;k.current.some(se=>se.startedAt<ce)&&(k.current=k.current.filter(se=>se.startedAt>=ce),b(k.current))},3e4);return()=>{$=!0,X==null||X.close();for(const ce of te)clearTimeout(ce);te.clear(),clearInterval(ie)}},[]),m.useEffect(()=>{const $=setInterval(()=>{Se.get("/api/admin/providers").then(X=>{const te=new Map(X.providers.map(G=>[G.id,G]));N.current=N.current.map(G=>{const ie=te.get(G.id);return ie?{...G,health:ie.health,enabled:ie.enabled}:G}),g(N.current)}).catch(()=>{})},3e4);return()=>clearInterval($)},[]),{snapshot:a,live:s??(a==null?void 0:a.summary)??Fk,recent:u,providers:p,pulses:v,activeRoutes:y,loading:w,error:j}}const Fk={totalRequests:0,successfulRequests:0,failedRequests:0,successRate:0,inputTokens:0,outputTokens:0,totalTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0,averageLatencyMs:0,p95LatencyMs:0,averageTtftMs:null,p95TtftMs:null,cacheHitRate:0,gatewayCacheHitRate:0,fallbackRate:0};function DS({data:n,className:a,strokeClass:l="stroke-primary",fillClass:s}){if(n.length===0)return o.jsx("svg",{className:Ee("h-6 w-20",a),viewBox:"0 0 80 24"});const f=Math.max(...n),p=Math.min(...n),g=f-p||1,x=n.map((y,b)=>{const w=b/(n.length-1)*78+1,E=22-(y-p)/g*20;return`${w.toFixed(1)},${E.toFixed(1)}`}).join(" ");return o.jsxs("svg",{className:Ee("h-6 w-20",a),viewBox:"0 0 80 24",preserveAspectRatio:"none",children:[s&&o.jsx("polygon",{points:`1,23 ${x} 79,23`,className:s}),o.jsx("polyline",{points:x,fill:"none",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:l})]})}function Qk(n,a,l){const s=performance.now();let c=0;const u=f=>{const p=Math.min((f-s)/a,1),g=Math.round(n*p);g!==c&&(c=g,l(g)),p<1&&requestAnimationFrame(u)};requestAnimationFrame(u)}function Zk({delta:n,inverse:a}){if(Math.abs(n)<.005)return null;const l=n>0,s=a?!l:l,c=`${(Math.abs(n)*100).toFixed(1)}%`;return o.jsxs("span",{className:Ee("ml-1.5 inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",s?"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300":"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"),children:[o.jsx("span",{className:"mr-0.5",children:l?"▲":"▼"}),c]})}function el({icon:n,label:a,value:l,format:s="number",delta:c,deltaInverse:u,sparkData:f,sparkStroke:p}){const[g,v]=m.useState(0),x=m.useRef(0);m.useEffect(()=>{const b=x.current,w=l;x.current=l,b!==w&&Qk(Math.abs(w-b),600,E=>v(b+(w>b?E:-E)))},[l]);const y=s==="percent"?Eu(g):s==="latency"?Ol(g):Kt(Math.round(g));return o.jsxs(nt,{children:[o.jsxs(at,{className:"flex flex-row items-center justify-between pb-1",children:[o.jsxs(rt,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[o.jsx(n,{className:"h-4 w-4"}),a]}),c!==void 0&&o.jsx(Zk,{delta:c,inverse:u})]}),o.jsxs(lt,{className:"flex items-end justify-between",children:[o.jsx("span",{className:"text-2xl font-semibold tabular-nums",children:y}),f&&f.length>1&&o.jsx(DS,{data:f,strokeClass:p??"stroke-primary",fillClass:"fill-primary/10"})]})]})}const OS=1e3,Gb=380,Vc=60,tl=OS/2,nl=720,Bh=62,Jk=260;function Wk(n){return n==="healthy"?"fill-emerald-400":n==="degraded"?"fill-amber-400":"fill-red-400"}function $c(n,a,l,s){const c=n+(l-n)*.45,u=n+(l-n)*.55;return`M${n},${a} C${c},${a} ${u},${s} ${l},${s}`}function e4({liveRequests:n,successRate:a,providers:l,pulses:s,activeRoutes:c}){const u=Gb/2,f=u,p=Math.max(1,l.reduce((x,y)=>x+y.requests,0)),g=new Set(c.map(x=>x.providerId)),v=g.size>0;return o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(rt,{className:"text-base",children:"Real-time Request Routing"}),o.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," healthy"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-400"})," degraded"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-red-400"})," down"]})]})]})}),o.jsx(lt,{className:"pt-0",children:o.jsx("div",{className:"relative w-full",children:o.jsxs("svg",{viewBox:`0 0 ${OS} ${Gb}`,className:"w-full h-auto",preserveAspectRatio:"xMidYMid meet",children:[o.jsx("defs",{children:o.jsxs("filter",{id:"glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[o.jsx("feGaussianBlur",{stdDeviation:"3",result:"blur"}),o.jsxs("feMerge",{children:[o.jsx("feMergeNode",{in:"blur"}),o.jsx("feMergeNode",{in:"SourceGraphic"})]})]})}),l.map(x=>{const b=60+l.indexOf(x)*Bh,w=x.requests/p,E=Math.max(1.5,Math.min(6,2+w*8)),j=g.has(x.id);return o.jsxs("g",{children:[j&&o.jsx("path",{d:$c(tl,u,nl-20,b),fill:"none",stroke:"hsl(var(--primary) / 0.25)",strokeWidth:E+6,strokeLinecap:"round"}),o.jsx("path",{d:$c(tl,u,nl-20,b),fill:"none",stroke:j?"hsl(var(--primary))":"hsl(var(--border))",strokeWidth:j?E+1:E,strokeLinecap:"round",opacity:j?.95:.6,className:j?"route-active":void 0})]},x.id)}),o.jsx("path",{d:$c(Vc+30,f,tl-30,u),fill:"none",stroke:v?"hsl(var(--primary))":"hsl(var(--border))",strokeWidth:3,strokeLinecap:"round",strokeDasharray:"6 3",opacity:v?.9:.5,className:v?"route-active":void 0}),s.map(x=>{const y=l.findIndex(j=>j.id===x.providerId);if(y===-1)return null;const b=60+y*Bh,w=$c(tl,u,nl-20,b),E=x.success?"var(--primary)":"#f87171";return o.jsxs("g",{filter:"url(#glow)",children:[o.jsx("circle",{r:5,fill:E,opacity:.9,children:o.jsx("animateMotion",{dur:"1.4s",fill:"freeze",path:w})}),o.jsx("circle",{r:9,fill:E,opacity:.25,children:o.jsx("animateMotion",{dur:"1.4s",fill:"freeze",path:w})})]},x.id)}),o.jsx("circle",{cx:Vc,cy:f,r:28,fill:"hsl(var(--card))",stroke:"hsl(var(--border))",strokeWidth:1.5}),o.jsx("text",{x:Vc,y:f-4,textAnchor:"middle",className:"fill-foreground",fontSize:12,fontWeight:600,children:Kb(n)}),o.jsx("text",{x:Vc,y:f+10,textAnchor:"middle",className:"fill-muted-foreground",fontSize:9,children:"requests"}),o.jsx("circle",{cx:tl,cy:u,r:36,fill:"hsl(var(--card))",stroke:"var(--primary)",strokeWidth:2}),o.jsx("image",{x:tl-12,y:u-16,width:24,height:24,href:"/logo.png"}),o.jsx("text",{x:tl,y:u+28,textAnchor:"middle",className:"fill-muted-foreground",fontSize:9,children:"AI Gateway"}),o.jsxs("text",{x:tl,y:u+38,textAnchor:"middle",className:"fill-emerald-500",fontSize:10,fontWeight:600,children:[(a*100).toFixed(1),"%"]}),l.map((x,y)=>{const b=60+y*Bh,w=x.requests/p,E=!x.enabled||x.requests===0;return o.jsxs("g",{opacity:E?.4:1,children:[o.jsx("rect",{x:nl-20,y:b-14,width:Jk,height:50,rx:8,fill:"hsl(var(--card))",stroke:"hsl(var(--border))",strokeWidth:1}),o.jsx("circle",{cx:nl-6,cy:b+10,r:4,className:Wk(x.health)}),o.jsx("text",{x:nl+6,y:b-2,className:"fill-foreground",fontSize:12,fontWeight:500,children:x.name}),o.jsxs("text",{x:nl+6,y:b+12,className:"fill-muted-foreground",fontSize:10,children:[x.modelCount," model",x.modelCount!==1?"s":""," · ",Kb(x.requests)," req"]}),o.jsxs("text",{x:nl+6,y:b+25,className:"fill-muted-foreground",fontSize:10,children:[(w*100).toFixed(1),"% traffic · ",x.avgLatencyMs<1e3?`${Math.round(x.avgLatencyMs)}ms`:`${(x.avgLatencyMs/1e3).toFixed(1)}s`," avg",x.errorRate>0&&o.jsxs("tspan",{className:"fill-red-500",children:[" · ",(x.errorRate*100).toFixed(0),"% err"]})]})]},x.id)})]})})})]})}function Kb(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}K`:String(n)}function t4({rows:n}){return o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Recent Requests"})}),o.jsx(lt,{children:n.length===0?o.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No requests yet — traffic will appear here live."}):o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Tokens"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Time"})]})}),o.jsx(da,{children:n.map(a=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:a.requestedModel}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:a.providerName??"—"}),o.jsxs(pe,{className:"text-xs",children:[o.jsxs("span",{className:"font-mono",children:["in ",Kt(a.inputTokens)," · out ",Kt(a.outputTokens)]}),a.cacheReadTokens>0&&o.jsxs("span",{className:"ml-1 text-amber-600",children:["(+",Kt(a.cacheReadTokens)," cache)"]})]}),o.jsx(pe,{children:o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:a.success?"h-2 w-2 rounded-full bg-emerald-400":"h-2 w-2 rounded-full bg-red-400"}),o.jsx("span",{className:"text-xs",children:a.success?a.httpStatus:`${a.httpStatus} err`})]})}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:nN(a.createdAt)})]},a.id))})]})})]})}const gm=34,Xb=2*Math.PI*gm;function n4(n){return n>=.95?{stroke:"#4ade80",text:"text-emerald-500"}:n>=.8?{stroke:"#fbbf24",text:"text-amber-500"}:{stroke:"#f87171",text:"text-red-500"}}function a4({successRate:n,averageLatencyMs:a,latencySpark:l}){const{stroke:s,text:c}=n4(n),u=Math.min(1,Math.max(0,n)),f=Xb*(1-u);return o.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Success Rate"})}),o.jsxs(lt,{className:"flex items-center gap-4",children:[o.jsxs("div",{className:"relative h-20 w-20",children:[o.jsxs("svg",{viewBox:"0 0 80 80",className:"h-20 w-20 -rotate-90",children:[o.jsx("circle",{cx:"40",cy:"40",r:gm,fill:"none",stroke:"hsl(var(--border))",strokeWidth:7}),o.jsx("circle",{cx:"40",cy:"40",r:gm,fill:"none",stroke:s,strokeWidth:7,strokeLinecap:"round",strokeDasharray:Xb,strokeDashoffset:f,style:{transition:"stroke-dashoffset 0.6s ease, stroke 0.4s ease"}})]}),o.jsx("span",{className:`absolute inset-0 flex items-center justify-center text-sm font-semibold tabular-nums ${c}`,children:Eu(n)})]}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Share of requests that completed successfully over the selected window. Updated in real time."})]})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Average Latency"})}),o.jsxs(lt,{className:"flex items-end justify-between",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:Ol(a)}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Live average across the selected window"})]}),o.jsx(DS,{data:l,strokeClass:"stroke-amber-500",fillClass:"fill-amber-500/10",className:"h-10 w-28"})]})]})]})}function r4(){const[n,a]=m.useState("7d"),{snapshot:l,live:s,recent:c,providers:u,pulses:f,activeRoutes:p,loading:g,error:v}=Xk(n);if(g)return o.jsx("div",{className:"text-muted-foreground",children:"Loading…"});if(v||!l)return o.jsxs("div",{className:"text-destructive",children:["Failed to load statistics: ",v??"unknown error"]});const x=s,y=l.previous,b=l.series;function w(C,N){return N>0?(C-N)/N:void 0}const E=b.map(C=>C.requests),j=b.map(C=>C.avgLatency);return o.jsxs("div",{children:[o.jsx($a,{title:"Statistics",description:"Real-time monitoring dashboard",actions:o.jsx(MS,{value:n,onValueChange:C=>void a(C),children:o.jsxs(Up,{children:[o.jsx(mr,{value:"today",children:"Today"}),o.jsx(mr,{value:"7d",children:"7 days"}),o.jsx(mr,{value:"30d",children:"30 days"})]})})}),o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsx(el,{icon:km,label:"Requests",value:x.totalRequests,delta:w(x.totalRequests,y.totalRequests),sparkData:E}),o.jsx(el,{icon:ci,label:"Success rate",format:"percent",value:x.successRate,delta:w(x.successRate,y.successRate),sparkData:E,sparkStroke:"stroke-emerald-500"}),o.jsx(el,{icon:rR,label:"Total tokens",value:x.totalTokens,delta:w(x.totalTokens,y.totalTokens),sparkData:b.map(C=>C.inputTokens+C.outputTokens)}),o.jsx(el,{icon:lR,label:"Cache hit rate",format:"percent",value:x.cacheHitRate,delta:w(x.cacheHitRate,y.cacheHitRate),sparkData:b.map(C=>C.cacheRead)}),o.jsx(el,{icon:tR,label:"Avg latency",format:"latency",value:x.averageLatencyMs,delta:w(x.averageLatencyMs,y.averageLatencyMs),deltaInverse:!0,sparkData:j,sparkStroke:"stroke-amber-500"}),o.jsx(el,{icon:R0,label:"p95 latency",format:"latency",value:x.p95LatencyMs}),o.jsx(el,{icon:bR,label:"Avg TTFT",format:"latency",value:x.averageTtftMs??0}),o.jsx(el,{icon:mR,label:"Fallback rate",format:"percent",value:x.fallbackRate,delta:w(x.fallbackRate,y.fallbackRate),deltaInverse:!0})]}),o.jsx("div",{className:"mt-6",children:o.jsx(e4,{liveRequests:x.totalRequests,successRate:x.successRate,providers:u,pulses:f,activeRoutes:p})}),o.jsxs("div",{className:"mt-6 grid gap-4 lg:grid-cols-3",children:[o.jsx("div",{className:"lg:col-span-2",children:o.jsx(t4,{rows:c})}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Top Models"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Req"}),o.jsx(ye,{children:"Errors"}),o.jsx(ye,{children:"Tokens"})]})}),o.jsxs(da,{children:[l.topModels.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:4,className:"text-muted-foreground text-center",children:"No data"})}),l.topModels.map(C=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:C.publicId}),o.jsx(pe,{className:"text-xs",children:Kt(C.requests)}),o.jsx(pe,{className:"text-xs",children:o.jsx("span",{className:C.errorRate>.1?"text-destructive":"text-muted-foreground",children:Eu(C.errorRate)})}),o.jsx(pe,{className:"text-xs",children:Kt(C.totalTokens)})]},C.publicId))]})]})})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Top API Keys"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Key"}),o.jsx(ye,{children:"Requests"}),o.jsx(ye,{children:"Tokens"})]})}),o.jsxs(da,{children:[l.topApiKeys.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:3,className:"text-muted-foreground text-center",children:"No data"})}),l.topApiKeys.map((C,N)=>o.jsxs(We,{children:[o.jsx(pe,{className:"text-xs",children:C.name}),o.jsx(pe,{className:"text-xs",children:Kt(C.requests)}),o.jsx(pe,{className:"text-xs",children:Kt(C.totalTokens)})]},N))]})]})})]})]})]}),o.jsx("div",{className:"mt-6",children:o.jsx(a4,{successRate:x.successRate,averageLatencyMs:x.averageLatencyMs,latencySpark:j})})]})}function l4(){const[n,a]=m.useState([]),[l,s]=m.useState(0);return m.useEffect(()=>{Se.get("/api/admin/audit?limit=200").then(c=>{a(c.rows),s(c.total)})},[]),o.jsxs("div",{children:[o.jsx($a,{title:"Audit Logs",description:`${l} entries · immutable`}),o.jsxs(nt,{children:[o.jsx(at,{children:o.jsx(rt,{className:"text-base",children:"All entries"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Time"}),o.jsx(ye,{children:"Action"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Target"}),o.jsx(ye,{children:"IP"}),o.jsx(ye,{children:"Actor"})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:6,className:"text-center text-muted-foreground",children:"No audit events yet."})}),n.map(c=>o.jsxs(We,{children:[o.jsx(pe,{className:"text-xs",children:Lm(c.createdAt)}),o.jsx(pe,{className:"font-mono text-xs",children:c.action}),o.jsx(pe,{children:c.success?o.jsx(Qe,{variant:"success",children:"ok"}):o.jsx(Qe,{variant:"destructive",children:"fail"})}),o.jsx(pe,{className:"text-xs",children:c.targetName??c.targetId??"—"}),o.jsx(pe,{className:"text-xs",children:c.ip}),o.jsx(pe,{className:"text-xs",children:c.actor})]},c.id))]})]})})]})]})}const vm={enabled:!0,sound:!0};let ri=vm,xm=!1,Yc=null;const ym=new Set;function _S(){for(const n of ym)n()}function kS(n=!1){return xm&&!n?Promise.resolve():(!n&&Yc||(Yc=(async()=>{try{const a=await Se.get("/api/admin/settings");ri={enabled:a.settings.notificationsEnabled??vm.enabled,sound:a.settings.notificationSoundEnabled??vm.sound},xm=!0,_S()}catch{}})()),Yc)}async function Fb(n){const a={};n.enabled!==void 0&&(a.notificationsEnabled=n.enabled),n.sound!==void 0&&(a.notificationSoundEnabled=n.sound),await Se.patch("/api/admin/settings",a),ri={...ri,...n},xm=!0,_S()}function s4(n){return ym.add(n),()=>ym.delete(n)}function zS(){return m.useSyncExternalStore(s4,()=>ri,()=>ri)}const bm=m.forwardRef(({className:n,...a},l)=>o.jsx("textarea",{ref:l,className:Ee("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",n),...a}));bm.displayName="Textarea";function o4(){const[n]=BE(),[a,l]=m.useState(null),[s,c]=m.useState(null),[u,f]=m.useState({current:"",next:""}),[p,g]=m.useState(""),[v,x]=m.useState(""),[y,b]=m.useState(null),[w,E]=m.useState(!1),[j,C]=m.useState("idle"),[N,M]=m.useState(null),T=async(le=!1)=>{C("checking"),M(null);try{const Le=await Se.get(`/api/admin/update/check${le?"?force=1":""}`);b(Le),C("idle")}catch(Le){M(Le.message),C("error")}},D=async()=>{E(!0),C("installing"),M(null);try{const le=await Se.post("/api/admin/update/run");C("restarting"),ve.success(le.message||"Update started — the gateway will restart shortly.");const Le=setInterval(()=>{fetch("/health").then(Ie=>{Ie.ok&&(clearInterval(Le),window.location.reload())}).catch(()=>{})},3e3);setTimeout(()=>clearInterval(Le),12e4)}catch(le){ve.error(le.message),M(le.message),C("error")}finally{E(!1)}},[O,A]=m.useState("disabled"),[U,k]=m.useState(""),[$,X]=m.useState(""),[te,G]=m.useState(""),[ie,ce]=m.useState([]),[se,_]=m.useState(""),[H,Q]=m.useState(""),[J,ee]=m.useState(!1),[z,I]=m.useState(null),[F,re]=m.useState(""),[he,ge]=m.useState(""),[q,oe]=m.useState(""),de=async()=>{const le=await Se.get("/api/admin/settings");l(le.settings),g(le.settings.adminIpAllow??""),x(le.settings.adminIpBlock??"");const Le=await Se.get("/api/admin/settings/system");c(Le);try{const Ie=await Se.get("/api/admin/me");A(Ie.totpEnabled?"enabled":"disabled")}catch{}};if(m.useEffect(()=>{kS(!0)},[]),m.useEffect(()=>{de(),T(!0)},[]),!a)return o.jsx("div",{className:"text-muted-foreground",children:"Loading…"});const fe=async le=>{try{await Se.patch("/api/admin/settings",le),ve.success("Saved"),de()}catch(Le){ve.error(Le.message)}},Te=async()=>{try{const le=await Se.post("/api/admin/account/totp/begin");k(le.secret),X(le.qr),A("setup"),ve.info("Scan the QR code with your authenticator app")}catch(le){ve.error(le.message)}},je=async()=>{if(!te||te.length!==6){ve.error("Enter a 6-digit code");return}try{const le=await Se.post("/api/admin/account/totp/verify",{code:te});ce(le.recoveryCodes),A("showingRecovery"),ve.success("TOTP enabled successfully")}catch(le){ve.error(le.message)}},De=async()=>{if(!se){ve.error("Enter your password");return}if(!H){ve.error("Enter a TOTP code or recovery code");return}try{await Se.post("/api/admin/account/totp/disable",{password:se,totp:H}),A("disabled"),_(""),Q(""),ve.success("TOTP disabled"),de()}catch(le){ve.error(le.message)}},Fe=async()=>{ee(!0);try{const le=await Se.post("/api/admin/account/totp/recovery/regenerate",{password:se,totp:H});ce(le.recoveryCodes),A("showingRecovery"),ve.success("Recovery codes regenerated")}catch(le){ve.error(le.message)}ee(!1)},et=n.get("tab")||"logging";return o.jsxs("div",{children:[o.jsx($a,{title:"Settings",description:"Logging, security, backup, and system info"}),o.jsxs(MS,{defaultValue:et,children:[o.jsxs(Up,{children:[o.jsx(mr,{value:"logging",children:"Logging"}),o.jsx(mr,{value:"access",children:"Access Control"}),o.jsx(mr,{value:"security",children:"Security"}),o.jsx(mr,{value:"backup",children:"Backup"}),o.jsx(mr,{value:"system",children:"System"})]}),o.jsx(Os,{value:"logging",children:o.jsxs(nt,{children:[o.jsx(at,{children:o.jsx(rt,{className:"text-base",children:"Logging policy"})}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Request-content logging"}),o.jsxs(Ua,{value:a.contentLogMode,onValueChange:le=>fe({contentLogMode:le}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"off",children:"Off"}),o.jsx(Rt,{value:"metadata",children:"Metadata only (default)"}),o.jsx(Rt,{value:"prompt",children:"Prompt (sanitized)"}),o.jsx(Rt,{value:"prompt_and_response",children:"Prompt + response (sanitized)"})]})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Retention (days)"}),o.jsx(Ae,{type:"number",min:1,max:3650,value:a.retentionDays,onChange:le=>fe({retentionDays:Number(le.target.value)})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Database size limit (MB)"}),o.jsx(Ae,{type:"number",min:64,value:a.dbSizeLimitMb,onChange:le=>fe({dbSizeLimitMb:Number(le.target.value)})})]}),o.jsx("div",{className:"flex items-center gap-2 pt-2",children:o.jsx(me,{onClick:async()=>{const le=await Se.post("/api/admin/settings/cleanup");ve.success(`Deleted ${le.deletedRequests} old requests`)},children:"Run cleanup now"})})]})]})}),o.jsx(Os,{value:"access",children:o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"IP access control"}),o.jsx(gn,{children:"Allowlist / Blocklist for this admin website (not model traffic)"})]}),o.jsxs(lt,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(we,{children:"Allow only these IPs"}),o.jsx(bm,{placeholder:`192.168.1.0/24
|
|
348
|
+
`},H_={onDragStart(n){let{active:a}=n;return"Picked up draggable item "+a.id+"."},onDragOver(n){let{active:a,over:l}=n;return l?"Draggable item "+a.id+" was moved over droppable area "+l.id+".":"Draggable item "+a.id+" is no longer over a droppable area."},onDragEnd(n){let{active:a,over:l}=n;return l?"Draggable item "+a.id+" was dropped over droppable area "+l.id:"Draggable item "+a.id+" was dropped."},onDragCancel(n){let{active:a}=n;return"Dragging was cancelled. Draggable item "+a.id+" was dropped."}};function I_(n){let{announcements:a=H_,container:l,hiddenTextDescribedById:s,screenReaderInstructions:c=B_}=n;const{announce:u,announcement:f}=z_(),p=xi("DndLiveRegion"),[g,v]=m.useState(!1);if(m.useEffect(()=>{v(!0)},[]),L_(m.useMemo(()=>({onDragStart(y){let{active:b}=y;u(a.onDragStart({active:b}))},onDragMove(y){let{active:b,over:w}=y;a.onDragMove&&u(a.onDragMove({active:b,over:w}))},onDragOver(y){let{active:b,over:w}=y;u(a.onDragOver({active:b,over:w}))},onDragEnd(y){let{active:b,over:w}=y;u(a.onDragEnd({active:b,over:w}))},onDragCancel(y){let{active:b,over:w}=y;u(a.onDragCancel({active:b,over:w}))}}),[u,a])),!g)return null;const x=ue.createElement(ue.Fragment,null,ue.createElement(__,{id:s,value:c.draggable}),ue.createElement(k_,{id:p,announcement:f}));return l?ba.createPortal(x,l):x}var Gt;(function(n){n.DragStart="dragStart",n.DragMove="dragMove",n.DragEnd="dragEnd",n.DragCancel="dragCancel",n.DragOver="dragOver",n.RegisterDroppable="registerDroppable",n.SetDroppableDisabled="setDroppableDisabled",n.UnregisterDroppable="unregisterDroppable"})(Gt||(Gt={}));function hu(){}function Mb(n,a){return m.useMemo(()=>({sensor:n,options:a??{}}),[n,a])}function P_(){for(var n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];return m.useMemo(()=>[...a].filter(s=>s!=null),[...a])}const Ea=Object.freeze({x:0,y:0});function lS(n,a){return Math.sqrt(Math.pow(n.x-a.x,2)+Math.pow(n.y-a.y,2))}function sS(n,a){let{data:{value:l}}=n,{data:{value:s}}=a;return l-s}function q_(n,a){let{data:{value:l}}=n,{data:{value:s}}=a;return s-l}function Ab(n){let{left:a,top:l,height:s,width:c}=n;return[{x:a,y:l},{x:a+c,y:l},{x:a,y:l+s},{x:a+c,y:l+s}]}function oS(n,a){if(!n||n.length===0)return null;const[l]=n;return l[a]}function Db(n,a,l){return a===void 0&&(a=n.left),l===void 0&&(l=n.top),{x:a+n.width*.5,y:l+n.height*.5}}const V_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=Db(a,a.left,a.top),u=[];for(const f of s){const{id:p}=f,g=l.get(p);if(g){const v=lS(Db(g),c);u.push({id:p,data:{droppableContainer:f,value:v}})}}return u.sort(sS)},$_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=Ab(a),u=[];for(const f of s){const{id:p}=f,g=l.get(p);if(g){const v=Ab(g),x=c.reduce((b,w,E)=>b+lS(v[E],w),0),y=Number((x/4).toFixed(4));u.push({id:p,data:{droppableContainer:f,value:y}})}}return u.sort(sS)};function Y_(n,a){const l=Math.max(a.top,n.top),s=Math.max(a.left,n.left),c=Math.min(a.left+a.width,n.left+n.width),u=Math.min(a.top+a.height,n.top+n.height),f=c-s,p=u-l;if(s<c&&l<u){const g=a.width*a.height,v=n.width*n.height,x=f*p,y=x/(g+v-x);return Number(y.toFixed(4))}return 0}const G_=n=>{let{collisionRect:a,droppableRects:l,droppableContainers:s}=n;const c=[];for(const u of s){const{id:f}=u,p=l.get(f);if(p){const g=Y_(p,a);g>0&&c.push({id:f,data:{droppableContainer:u,value:g}})}}return c.sort(q_)};function K_(n,a,l){return{...n,scaleX:a&&l?a.width/l.width:1,scaleY:a&&l?a.height/l.height:1}}function iS(n,a){return n&&a?{x:n.left-a.left,y:n.top-a.top}:Ea}function X_(n){return function(l){for(var s=arguments.length,c=new Array(s>1?s-1:0),u=1;u<s;u++)c[u-1]=arguments[u];return c.reduce((f,p)=>({...f,top:f.top+n*p.y,bottom:f.bottom+n*p.y,left:f.left+n*p.x,right:f.right+n*p.x}),{...l})}}const F_=X_(1);function Q_(n){if(n.startsWith("matrix3d(")){const a=n.slice(9,-1).split(/, /);return{x:+a[12],y:+a[13],scaleX:+a[0],scaleY:+a[5]}}else if(n.startsWith("matrix(")){const a=n.slice(7,-1).split(/, /);return{x:+a[4],y:+a[5],scaleX:+a[0],scaleY:+a[3]}}return null}function Z_(n,a,l){const s=Q_(a);if(!s)return n;const{scaleX:c,scaleY:u,x:f,y:p}=s,g=n.left-f-(1-c)*parseFloat(l),v=n.top-p-(1-u)*parseFloat(l.slice(l.indexOf(" ")+1)),x=c?n.width/c:n.width,y=u?n.height/u:n.height;return{width:x,height:y,top:v,right:g+x,bottom:v+y,left:g}}const J_={ignoreTransform:!1};function Qs(n,a){a===void 0&&(a=J_);let l=n.getBoundingClientRect();if(a.ignoreTransform){const{transform:v,transformOrigin:x}=zn(n).getComputedStyle(n);v&&(l=Z_(l,v,x))}const{top:s,left:c,width:u,height:f,bottom:p,right:g}=l;return{top:s,left:c,width:u,height:f,bottom:p,right:g}}function Ob(n){return Qs(n,{ignoreTransform:!0})}function W_(n){const a=n.innerWidth,l=n.innerHeight;return{top:0,left:0,right:a,bottom:l,width:a,height:l}}function e3(n,a){return a===void 0&&(a=zn(n).getComputedStyle(n)),a.position==="fixed"}function t3(n,a){a===void 0&&(a=zn(n).getComputedStyle(n));const l=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(c=>{const u=a[c];return typeof u=="string"?l.test(u):!1})}function Fu(n,a){const l=[];function s(c){if(a!=null&&l.length>=a||!c)return l;if(Ep(c)&&c.scrollingElement!=null&&!l.includes(c.scrollingElement))return l.push(c.scrollingElement),l;if(!gi(c)||nS(c)||l.includes(c))return l;const u=zn(n).getComputedStyle(c);return c!==n&&t3(c,u)&&l.push(c),e3(c,u)?l:s(c.parentNode)}return n?s(n):l}function cS(n){const[a]=Fu(n,1);return a??null}function kh(n){return!Xu||!n?null:Xs(n)?n:Cp(n)?Ep(n)||n===Fs(n).scrollingElement?window:gi(n)?n:null:null}function uS(n){return Xs(n)?n.scrollX:n.scrollLeft}function dS(n){return Xs(n)?n.scrollY:n.scrollTop}function hm(n){return{x:uS(n),y:dS(n)}}var Wt;(function(n){n[n.Forward=1]="Forward",n[n.Backward=-1]="Backward"})(Wt||(Wt={}));function fS(n){return!Xu||!n?!1:n===document.scrollingElement}function hS(n){const a={x:0,y:0},l=fS(n)?{height:window.innerHeight,width:window.innerWidth}:{height:n.clientHeight,width:n.clientWidth},s={x:n.scrollWidth-l.width,y:n.scrollHeight-l.height},c=n.scrollTop<=a.y,u=n.scrollLeft<=a.x,f=n.scrollTop>=s.y,p=n.scrollLeft>=s.x;return{isTop:c,isLeft:u,isBottom:f,isRight:p,maxScroll:s,minScroll:a}}const n3={x:.2,y:.2};function a3(n,a,l,s,c){let{top:u,left:f,right:p,bottom:g}=l;s===void 0&&(s=10),c===void 0&&(c=n3);const{isTop:v,isBottom:x,isLeft:y,isRight:b}=hS(n),w={x:0,y:0},E={x:0,y:0},j={height:a.height*c.y,width:a.width*c.x};return!v&&u<=a.top+j.height?(w.y=Wt.Backward,E.y=s*Math.abs((a.top+j.height-u)/j.height)):!x&&g>=a.bottom-j.height&&(w.y=Wt.Forward,E.y=s*Math.abs((a.bottom-j.height-g)/j.height)),!b&&p>=a.right-j.width?(w.x=Wt.Forward,E.x=s*Math.abs((a.right-j.width-p)/j.width)):!y&&f<=a.left+j.width&&(w.x=Wt.Backward,E.x=s*Math.abs((a.left+j.width-f)/j.width)),{direction:w,speed:E}}function r3(n){if(n===document.scrollingElement){const{innerWidth:u,innerHeight:f}=window;return{top:0,left:0,right:u,bottom:f,width:u,height:f}}const{top:a,left:l,right:s,bottom:c}=n.getBoundingClientRect();return{top:a,left:l,right:s,bottom:c,width:n.clientWidth,height:n.clientHeight}}function mS(n){return n.reduce((a,l)=>Us(a,hm(l)),Ea)}function l3(n){return n.reduce((a,l)=>a+uS(l),0)}function s3(n){return n.reduce((a,l)=>a+dS(l),0)}function o3(n,a){if(a===void 0&&(a=Qs),!n)return;const{top:l,left:s,bottom:c,right:u}=a(n);cS(n)&&(c<=0||u<=0||l>=window.innerHeight||s>=window.innerWidth)&&n.scrollIntoView({block:"center",inline:"center"})}const i3=[["x",["left","right"],l3],["y",["top","bottom"],s3]];class Tp{constructor(a,l){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=Fu(l),c=mS(s);this.rect={...a},this.width=a.width,this.height=a.height;for(const[u,f,p]of i3)for(const g of f)Object.defineProperty(this,g,{get:()=>{const v=p(s),x=c[u]-v;return this.rect[g]+x},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Xo{constructor(a){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(l=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...l)})},this.target=a}add(a,l,s){var c;(c=this.target)==null||c.addEventListener(a,l,s),this.listeners.push([a,l,s])}}function c3(n){const{EventTarget:a}=zn(n);return n instanceof a?n:Fs(n)}function zh(n,a){const l=Math.abs(n.x),s=Math.abs(n.y);return typeof a=="number"?Math.sqrt(l**2+s**2)>a:"x"in a&&"y"in a?l>a.x&&s>a.y:"x"in a?l>a.x:"y"in a?s>a.y:!1}var la;(function(n){n.Click="click",n.DragStart="dragstart",n.Keydown="keydown",n.ContextMenu="contextmenu",n.Resize="resize",n.SelectionChange="selectionchange",n.VisibilityChange="visibilitychange"})(la||(la={}));function _b(n){n.preventDefault()}function u3(n){n.stopPropagation()}var Ke;(function(n){n.Space="Space",n.Down="ArrowDown",n.Right="ArrowRight",n.Left="ArrowLeft",n.Up="ArrowUp",n.Esc="Escape",n.Enter="Enter",n.Tab="Tab"})(Ke||(Ke={}));const pS={start:[Ke.Space,Ke.Enter],cancel:[Ke.Esc],end:[Ke.Space,Ke.Enter,Ke.Tab]},d3=(n,a)=>{let{currentCoordinates:l}=a;switch(n.code){case Ke.Right:return{...l,x:l.x+25};case Ke.Left:return{...l,x:l.x-25};case Ke.Down:return{...l,y:l.y+25};case Ke.Up:return{...l,y:l.y-25}}};class Mp{constructor(a){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=a;const{event:{target:l}}=a;this.props=a,this.listeners=new Xo(Fs(l)),this.windowListeners=new Xo(zn(l)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(la.Resize,this.handleCancel),this.windowListeners.add(la.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(la.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:a,onStart:l}=this.props,s=a.node.current;s&&o3(s),l(Ea)}handleKeyDown(a){if(Np(a)){const{active:l,context:s,options:c}=this.props,{keyboardCodes:u=pS,coordinateGetter:f=d3,scrollBehavior:p="smooth"}=c,{code:g}=a;if(u.end.includes(g)){this.handleEnd(a);return}if(u.cancel.includes(g)){this.handleCancel(a);return}const{collisionRect:v}=s.current,x=v?{x:v.left,y:v.top}:Ea;this.referenceCoordinates||(this.referenceCoordinates=x);const y=f(a,{active:l,context:s.current,currentCoordinates:x});if(y){const b=ni(y,x),w={x:0,y:0},{scrollableAncestors:E}=s.current;for(const j of E){const C=a.code,{isTop:N,isRight:M,isLeft:T,isBottom:D,maxScroll:O,minScroll:A}=hS(j),U=r3(j),k={x:Math.min(C===Ke.Right?U.right-U.width/2:U.right,Math.max(C===Ke.Right?U.left:U.left+U.width/2,y.x)),y:Math.min(C===Ke.Down?U.bottom-U.height/2:U.bottom,Math.max(C===Ke.Down?U.top:U.top+U.height/2,y.y))},$=C===Ke.Right&&!M||C===Ke.Left&&!T,X=C===Ke.Down&&!D||C===Ke.Up&&!N;if($&&k.x!==y.x){const te=j.scrollLeft+b.x,G=C===Ke.Right&&te<=O.x||C===Ke.Left&&te>=A.x;if(G&&!b.y){j.scrollTo({left:te,behavior:p});return}G?w.x=j.scrollLeft-te:w.x=C===Ke.Right?j.scrollLeft-O.x:j.scrollLeft-A.x,w.x&&j.scrollBy({left:-w.x,behavior:p});break}else if(X&&k.y!==y.y){const te=j.scrollTop+b.y,G=C===Ke.Down&&te<=O.y||C===Ke.Up&&te>=A.y;if(G&&!b.x){j.scrollTo({top:te,behavior:p});return}G?w.y=j.scrollTop-te:w.y=C===Ke.Down?j.scrollTop-O.y:j.scrollTop-A.y,w.y&&j.scrollBy({top:-w.y,behavior:p});break}}this.handleMove(a,Us(ni(y,this.referenceCoordinates),w))}}}handleMove(a,l){const{onMove:s}=this.props;a.preventDefault(),s(l)}handleEnd(a){const{onEnd:l}=this.props;a.preventDefault(),this.detach(),l()}handleCancel(a){const{onCancel:l}=this.props;a.preventDefault(),this.detach(),l()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Mp.activators=[{eventName:"onKeyDown",handler:(n,a,l)=>{let{keyboardCodes:s=pS,onActivation:c}=a,{active:u}=l;const{code:f}=n.nativeEvent;if(s.start.includes(f)){const p=u.activatorNode.current;return p&&n.target!==p?!1:(n.preventDefault(),c==null||c({event:n.nativeEvent}),!0)}return!1}}];function kb(n){return!!(n&&"distance"in n)}function zb(n){return!!(n&&"delay"in n)}class Ap{constructor(a,l,s){var c;s===void 0&&(s=c3(a.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=a,this.events=l;const{event:u}=a,{target:f}=u;this.props=a,this.events=l,this.document=Fs(f),this.documentListeners=new Xo(this.document),this.listeners=new Xo(s),this.windowListeners=new Xo(zn(f)),this.initialCoordinates=(c=fm(u))!=null?c:Ea,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:a,props:{options:{activationConstraint:l,bypassActivationConstraint:s}}}=this;if(this.listeners.add(a.move.name,this.handleMove,{passive:!1}),this.listeners.add(a.end.name,this.handleEnd),a.cancel&&this.listeners.add(a.cancel.name,this.handleCancel),this.windowListeners.add(la.Resize,this.handleCancel),this.windowListeners.add(la.DragStart,_b),this.windowListeners.add(la.VisibilityChange,this.handleCancel),this.windowListeners.add(la.ContextMenu,_b),this.documentListeners.add(la.Keydown,this.handleKeydown),l){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(zb(l)){this.timeoutId=setTimeout(this.handleStart,l.delay),this.handlePending(l);return}if(kb(l)){this.handlePending(l);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(a,l){const{active:s,onPending:c}=this.props;c(s,a,this.initialCoordinates,l)}handleStart(){const{initialCoordinates:a}=this,{onStart:l}=this.props;a&&(this.activated=!0,this.documentListeners.add(la.Click,u3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(la.SelectionChange,this.removeTextSelection),l(a))}handleMove(a){var l;const{activated:s,initialCoordinates:c,props:u}=this,{onMove:f,options:{activationConstraint:p}}=u;if(!c)return;const g=(l=fm(a))!=null?l:Ea,v=ni(c,g);if(!s&&p){if(kb(p)){if(p.tolerance!=null&&zh(v,p.tolerance))return this.handleCancel();if(zh(v,p.distance))return this.handleStart()}if(zb(p)&&zh(v,p.tolerance))return this.handleCancel();this.handlePending(p,v);return}a.cancelable&&a.preventDefault(),f(g)}handleEnd(){const{onAbort:a,onEnd:l}=this.props;this.detach(),this.activated||a(this.props.active),l()}handleCancel(){const{onAbort:a,onCancel:l}=this.props;this.detach(),this.activated||a(this.props.active),l()}handleKeydown(a){a.code===Ke.Esc&&this.handleCancel()}removeTextSelection(){var a;(a=this.document.getSelection())==null||a.removeAllRanges()}}const f3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Dp extends Ap{constructor(a){const{event:l}=a,s=Fs(l.target);super(a,f3,s)}}Dp.activators=[{eventName:"onPointerDown",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;return!l.isPrimary||l.button!==0?!1:(s==null||s({event:l}),!0)}}];const h3={move:{name:"mousemove"},end:{name:"mouseup"}};var mm;(function(n){n[n.RightClick=2]="RightClick"})(mm||(mm={}));class m3 extends Ap{constructor(a){super(a,h3,Fs(a.event.target))}}m3.activators=[{eventName:"onMouseDown",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;return l.button===mm.RightClick?!1:(s==null||s({event:l}),!0)}}];const Lh={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class p3 extends Ap{constructor(a){super(a,Lh)}static setup(){return window.addEventListener(Lh.move.name,a,{capture:!1,passive:!1}),function(){window.removeEventListener(Lh.move.name,a)};function a(){}}}p3.activators=[{eventName:"onTouchStart",handler:(n,a)=>{let{nativeEvent:l}=n,{onActivation:s}=a;const{touches:c}=l;return c.length>1?!1:(s==null||s({event:l}),!0)}}];var Fo;(function(n){n[n.Pointer=0]="Pointer",n[n.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var mu;(function(n){n[n.TreeOrder=0]="TreeOrder",n[n.ReversedTreeOrder=1]="ReversedTreeOrder"})(mu||(mu={}));function g3(n){let{acceleration:a,activator:l=Fo.Pointer,canScroll:s,draggingRect:c,enabled:u,interval:f=5,order:p=mu.TreeOrder,pointerCoordinates:g,scrollableAncestors:v,scrollableAncestorRects:x,delta:y,threshold:b}=n;const w=x3({delta:y,disabled:!u}),[E,j]=T_(),C=m.useRef({x:0,y:0}),N=m.useRef({x:0,y:0}),M=m.useMemo(()=>{switch(l){case Fo.Pointer:return g?{top:g.y,bottom:g.y,left:g.x,right:g.x}:null;case Fo.DraggableRect:return c}},[l,c,g]),T=m.useRef(null),D=m.useCallback(()=>{const A=T.current;if(!A)return;const U=C.current.x*N.current.x,k=C.current.y*N.current.y;A.scrollBy(U,k)},[]),O=m.useMemo(()=>p===mu.TreeOrder?[...v].reverse():v,[p,v]);m.useEffect(()=>{if(!u||!v.length||!M){j();return}for(const A of O){if((s==null?void 0:s(A))===!1)continue;const U=v.indexOf(A),k=x[U];if(!k)continue;const{direction:$,speed:X}=a3(A,k,M,a,b);for(const te of["x","y"])w[te][$[te]]||(X[te]=0,$[te]=0);if(X.x>0||X.y>0){j(),T.current=A,E(D,f),C.current=X,N.current=$;return}}C.current={x:0,y:0},N.current={x:0,y:0},j()},[a,D,s,j,u,f,JSON.stringify(M),JSON.stringify(w),E,v,O,x,JSON.stringify(b)])}const v3={x:{[Wt.Backward]:!1,[Wt.Forward]:!1},y:{[Wt.Backward]:!1,[Wt.Forward]:!1}};function x3(n){let{delta:a,disabled:l}=n;const s=dm(a);return vi(c=>{if(l||!s||!c)return v3;const u={x:Math.sign(a.x-s.x),y:Math.sign(a.y-s.y)};return{x:{[Wt.Backward]:c.x[Wt.Backward]||u.x===-1,[Wt.Forward]:c.x[Wt.Forward]||u.x===1},y:{[Wt.Backward]:c.y[Wt.Backward]||u.y===-1,[Wt.Forward]:c.y[Wt.Forward]||u.y===1}}},[l,a,s])}function y3(n,a){const l=a!=null?n.get(a):void 0,s=l?l.node.current:null;return vi(c=>{var u;return a==null?null:(u=s??c)!=null?u:null},[s,a])}function b3(n,a){return m.useMemo(()=>n.reduce((l,s)=>{const{sensor:c}=s,u=c.activators.map(f=>({eventName:f.eventName,handler:a(f.handler,s)}));return[...l,...u]},[]),[n,a])}var ai;(function(n){n[n.Always=0]="Always",n[n.BeforeDragging=1]="BeforeDragging",n[n.WhileDragging=2]="WhileDragging"})(ai||(ai={}));var pm;(function(n){n.Optimized="optimized"})(pm||(pm={}));const Lb=new Map;function w3(n,a){let{dragging:l,dependencies:s,config:c}=a;const[u,f]=m.useState(null),{frequency:p,measure:g,strategy:v}=c,x=m.useRef(n),y=C(),b=ti(y),w=m.useCallback(function(N){N===void 0&&(N=[]),!b.current&&f(M=>M===null?N:M.concat(N.filter(T=>!M.includes(T))))},[b]),E=m.useRef(null),j=vi(N=>{if(y&&!l)return Lb;if(!N||N===Lb||x.current!==n||u!=null){const M=new Map;for(let T of n){if(!T)continue;if(u&&u.length>0&&!u.includes(T.id)&&T.rect.current){M.set(T.id,T.rect.current);continue}const D=T.node.current,O=D?new Tp(g(D),D):null;T.rect.current=O,O&&M.set(T.id,O)}return M}return N},[n,u,l,y,g]);return m.useEffect(()=>{x.current=n},[n]),m.useEffect(()=>{y||w()},[l,y]),m.useEffect(()=>{u&&u.length>0&&f(null)},[JSON.stringify(u)]),m.useEffect(()=>{y||typeof p!="number"||E.current!==null||(E.current=setTimeout(()=>{w(),E.current=null},p))},[p,y,w,...s]),{droppableRects:j,measureDroppableContainers:w,measuringScheduled:u!=null};function C(){switch(v){case ai.Always:return!1;case ai.BeforeDragging:return l;default:return!l}}}function gS(n,a){return vi(l=>n?l||(typeof a=="function"?a(n):n):null,[a,n])}function S3(n,a){return gS(n,a)}function j3(n){let{callback:a,disabled:l}=n;const s=Rp(a),c=m.useMemo(()=>{if(l||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:u}=window;return new u(s)},[s,l]);return m.useEffect(()=>()=>c==null?void 0:c.disconnect(),[c]),c}function Qu(n){let{callback:a,disabled:l}=n;const s=Rp(a),c=m.useMemo(()=>{if(l||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:u}=window;return new u(s)},[l]);return m.useEffect(()=>()=>c==null?void 0:c.disconnect(),[c]),c}function C3(n){return new Tp(Qs(n),n)}function Ub(n,a,l){a===void 0&&(a=C3);const[s,c]=m.useState(null);function u(){c(g=>{if(!n)return null;if(n.isConnected===!1){var v;return(v=g??l)!=null?v:null}const x=a(n);return JSON.stringify(g)===JSON.stringify(x)?g:x})}const f=j3({callback(g){if(n)for(const v of g){const{type:x,target:y}=v;if(x==="childList"&&y instanceof HTMLElement&&y.contains(n)){u();break}}}}),p=Qu({callback:u});return qa(()=>{u(),n?(p==null||p.observe(n),f==null||f.observe(document.body,{childList:!0,subtree:!0})):(p==null||p.disconnect(),f==null||f.disconnect())},[n]),s}function E3(n){const a=gS(n);return iS(n,a)}const Bb=[];function R3(n){const a=m.useRef(n),l=vi(s=>n?s&&s!==Bb&&n&&a.current&&n.parentNode===a.current.parentNode?s:Fu(n):Bb,[n]);return m.useEffect(()=>{a.current=n},[n]),l}function N3(n){const[a,l]=m.useState(null),s=m.useRef(n),c=m.useCallback(u=>{const f=kh(u.target);f&&l(p=>p?(p.set(f,hm(f)),new Map(p)):null)},[]);return m.useEffect(()=>{const u=s.current;if(n!==u){f(u);const p=n.map(g=>{const v=kh(g);return v?(v.addEventListener("scroll",c,{passive:!0}),[v,hm(v)]):null}).filter(g=>g!=null);l(p.length?new Map(p):null),s.current=n}return()=>{f(n),f(u)};function f(p){p.forEach(g=>{const v=kh(g);v==null||v.removeEventListener("scroll",c)})}},[c,n]),m.useMemo(()=>n.length?a?Array.from(a.values()).reduce((u,f)=>Us(u,f),Ea):mS(n):Ea,[n,a])}function Hb(n,a){a===void 0&&(a=[]);const l=m.useRef(null);return m.useEffect(()=>{l.current=null},a),m.useEffect(()=>{const s=n!==Ea;s&&!l.current&&(l.current=n),!s&&l.current&&(l.current=null)},[n]),l.current?ni(n,l.current):Ea}function T3(n){m.useEffect(()=>{if(!Xu)return;const a=n.map(l=>{let{sensor:s}=l;return s.setup==null?void 0:s.setup()});return()=>{for(const l of a)l==null||l()}},n.map(a=>{let{sensor:l}=a;return l}))}function M3(n,a){return m.useMemo(()=>n.reduce((l,s)=>{let{eventName:c,handler:u}=s;return l[c]=f=>{u(f,a)},l},{}),[n,a])}function vS(n){return m.useMemo(()=>n?W_(n):null,[n])}const Ib=[];function A3(n,a){a===void 0&&(a=Qs);const[l]=n,s=vS(l?zn(l):null),[c,u]=m.useState(Ib);function f(){u(()=>n.length?n.map(g=>fS(g)?s:new Tp(a(g),g)):Ib)}const p=Qu({callback:f});return qa(()=>{p==null||p.disconnect(),f(),n.forEach(g=>p==null?void 0:p.observe(g))},[n]),c}function D3(n){if(!n)return null;if(n.children.length>1)return n;const a=n.children[0];return gi(a)?a:n}function O3(n){let{measure:a}=n;const[l,s]=m.useState(null),c=m.useCallback(v=>{for(const{target:x}of v)if(gi(x)){s(y=>{const b=a(x);return y?{...y,width:b.width,height:b.height}:b});break}},[a]),u=Qu({callback:c}),f=m.useCallback(v=>{const x=D3(v);u==null||u.disconnect(),x&&(u==null||u.observe(x)),s(x?a(x):null)},[a,u]),[p,g]=du(f);return m.useMemo(()=>({nodeRef:p,rect:l,setRef:g}),[l,p,g])}const _3=[{sensor:Dp,options:{}},{sensor:Mp,options:{}}],k3={current:{}},eu={draggable:{measure:Ob},droppable:{measure:Ob,strategy:ai.WhileDragging,frequency:pm.Optimized},dragOverlay:{measure:Qs}};class Qo extends Map{get(a){var l;return a!=null&&(l=super.get(a))!=null?l:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(a=>{let{disabled:l}=a;return!l})}getNodeFor(a){var l,s;return(l=(s=this.get(a))==null?void 0:s.node.current)!=null?l:void 0}}const z3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Qo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:hu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:eu,measureDroppableContainers:hu,windowRect:null,measuringScheduled:!1},L3={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:hu,draggableNodes:new Map,over:null,measureDroppableContainers:hu},Zu=m.createContext(L3),xS=m.createContext(z3);function U3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Qo}}}function B3(n,a){switch(a.type){case Gt.DragStart:return{...n,draggable:{...n.draggable,initialCoordinates:a.initialCoordinates,active:a.active}};case Gt.DragMove:return n.draggable.active==null?n:{...n,draggable:{...n.draggable,translate:{x:a.coordinates.x-n.draggable.initialCoordinates.x,y:a.coordinates.y-n.draggable.initialCoordinates.y}}};case Gt.DragEnd:case Gt.DragCancel:return{...n,draggable:{...n.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Gt.RegisterDroppable:{const{element:l}=a,{id:s}=l,c=new Qo(n.droppable.containers);return c.set(s,l),{...n,droppable:{...n.droppable,containers:c}}}case Gt.SetDroppableDisabled:{const{id:l,key:s,disabled:c}=a,u=n.droppable.containers.get(l);if(!u||s!==u.key)return n;const f=new Qo(n.droppable.containers);return f.set(l,{...u,disabled:c}),{...n,droppable:{...n.droppable,containers:f}}}case Gt.UnregisterDroppable:{const{id:l,key:s}=a,c=n.droppable.containers.get(l);if(!c||s!==c.key)return n;const u=new Qo(n.droppable.containers);return u.delete(l),{...n,droppable:{...n.droppable,containers:u}}}default:return n}}function H3(n){let{disabled:a}=n;const{active:l,activatorEvent:s,draggableNodes:c}=m.useContext(Zu),u=dm(s),f=dm(l==null?void 0:l.id);return m.useEffect(()=>{if(!a&&!s&&u&&f!=null){if(!Np(u)||document.activeElement===u.target)return;const p=c.get(f);if(!p)return;const{activatorNode:g,node:v}=p;if(!g.current&&!v.current)return;requestAnimationFrame(()=>{for(const x of[g.current,v.current]){if(!x)continue;const y=D_(x);if(y){y.focus();break}}})}},[s,a,c,f,u]),null}function I3(n,a){let{transform:l,...s}=a;return n!=null&&n.length?n.reduce((c,u)=>u({transform:c,...s}),l):l}function P3(n){return m.useMemo(()=>({draggable:{...eu.draggable,...n==null?void 0:n.draggable},droppable:{...eu.droppable,...n==null?void 0:n.droppable},dragOverlay:{...eu.dragOverlay,...n==null?void 0:n.dragOverlay}}),[n==null?void 0:n.draggable,n==null?void 0:n.droppable,n==null?void 0:n.dragOverlay])}function q3(n){let{activeNode:a,measure:l,initialRect:s,config:c=!0}=n;const u=m.useRef(!1),{x:f,y:p}=typeof c=="boolean"?{x:c,y:c}:c;qa(()=>{if(!f&&!p||!a){u.current=!1;return}if(u.current||!s)return;const v=a==null?void 0:a.node.current;if(!v||v.isConnected===!1)return;const x=l(v),y=iS(x,s);if(f||(y.x=0),p||(y.y=0),u.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const b=cS(v);b&&b.scrollBy({top:y.y,left:y.x})}},[a,f,p,s,l])}const yS=m.createContext({...Ea,scaleX:1,scaleY:1});var al;(function(n){n[n.Uninitialized=0]="Uninitialized",n[n.Initializing=1]="Initializing",n[n.Initialized=2]="Initialized"})(al||(al={}));const V3=m.memo(function(a){var l,s,c,u;let{id:f,accessibility:p,autoScroll:g=!0,children:v,sensors:x=_3,collisionDetection:y=G_,measuring:b,modifiers:w,...E}=a;const j=m.useReducer(B3,void 0,U3),[C,N]=j,[M,T]=U_(),[D,O]=m.useState(al.Uninitialized),A=D===al.Initialized,{draggable:{active:U,nodes:k,translate:$},droppable:{containers:X}}=C,te=U!=null?k.get(U):null,G=m.useRef({initial:null,translated:null}),ie=m.useMemo(()=>{var vt;return U!=null?{id:U,data:(vt=te==null?void 0:te.data)!=null?vt:k3,rect:G}:null},[U,te]),ce=m.useRef(null),[se,_]=m.useState(null),[H,Q]=m.useState(null),J=ti(E,Object.values(E)),ee=xi("DndDescribedBy",f),z=m.useMemo(()=>X.getEnabled(),[X]),I=P3(b),{droppableRects:F,measureDroppableContainers:re,measuringScheduled:he}=w3(z,{dragging:A,dependencies:[$.x,$.y],config:I.droppable}),ge=y3(k,U),q=m.useMemo(()=>H?fm(H):null,[H]),oe=Nr(),de=S3(ge,I.draggable.measure);q3({activeNode:U!=null?k.get(U):null,config:oe.layoutShiftCompensation,initialRect:de,measure:I.draggable.measure});const fe=Ub(ge,I.draggable.measure,de),Te=Ub(ge?ge.parentElement:null),je=m.useRef({activatorEvent:null,active:null,activeNode:ge,collisionRect:null,collisions:null,droppableRects:F,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:X,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),De=X.getNodeFor((l=je.current.over)==null?void 0:l.id),Fe=O3({measure:I.dragOverlay.measure}),et=(s=Fe.nodeRef.current)!=null?s:ge,le=A?(c=Fe.rect)!=null?c:fe:null,Le=!!(Fe.nodeRef.current&&Fe.rect),Ie=E3(Le?null:fe),kt=vS(et?zn(et):null),St=R3(A?De??ge:null),Ft=A3(St),on=I3(w,{transform:{x:$.x-Ie.x,y:$.y-Ie.y,scaleX:1,scaleY:1},activatorEvent:H,active:ie,activeNodeRect:fe,containerNodeRect:Te,draggingNodeRect:le,over:je.current.over,overlayNodeRect:Fe.rect,scrollableAncestors:St,scrollableAncestorRects:Ft,windowRect:kt}),Qt=q?Us(q,$):null,jt=N3(St),fn=Hb(jt),Mt=Hb(jt,[fe]),At=Us(on,fn),cn=le?F_(le,on):null,fa=ie&&cn?y({active:ie,collisionRect:cn,droppableRects:F,droppableContainers:z,pointerCoordinates:Qt}):null,Ta=oS(fa,"id"),[Gn,dl]=m.useState(null),ha=Le?on:Us(on,Mt),Dt=K_(ha,(u=Gn==null?void 0:Gn.rect)!=null?u:null,fe),hn=m.useRef(null),Tt=m.useCallback((vt,st)=>{let{sensor:Bt,options:Ce}=st;if(ce.current==null)return;const ke=k.get(ce.current);if(!ke)return;const Ue=vt.nativeEvent,gt=new Bt({active:ce.current,activeNode:ke,event:Ue,options:Ce,context:je,onAbort(ct){if(!k.get(ct))return;const{onDragAbort:xt}=J.current,zt={id:ct};xt==null||xt(zt),M({type:"onDragAbort",event:zt})},onPending(ct,$t,xt,zt){if(!k.get(ct))return;const{onDragPending:Ka}=J.current,ma={id:ct,constraint:$t,initialCoordinates:xt,offset:zt};Ka==null||Ka(ma),M({type:"onDragPending",event:ma})},onStart(ct){const $t=ce.current;if($t==null)return;const xt=k.get($t);if(!xt)return;const{onDragStart:zt}=J.current,Ga={activatorEvent:Ue,active:{id:$t,data:xt.data,rect:G}};ba.unstable_batchedUpdates(()=>{zt==null||zt(Ga),O(al.Initializing),N({type:Gt.DragStart,initialCoordinates:ct,active:$t}),M({type:"onDragStart",event:Ga}),_(hn.current),Q(Ue)})},onMove(ct){N({type:Gt.DragMove,coordinates:ct})},onEnd:Ct(Gt.DragEnd),onCancel:Ct(Gt.DragCancel)});hn.current=gt;function Ct(ct){return async function(){const{active:xt,collisions:zt,over:Ga,scrollAdjustedTranslate:Ka}=je.current;let ma=null;if(xt&&Ka){const{cancelDrop:Tr}=J.current;ma={activatorEvent:Ue,active:xt,collisions:zt,delta:Ka,over:Ga},ct===Gt.DragEnd&&typeof Tr=="function"&&await Promise.resolve(Tr(ma))&&(ct=Gt.DragCancel)}ce.current=null,ba.unstable_batchedUpdates(()=>{N({type:ct}),O(al.Uninitialized),dl(null),_(null),Q(null),hn.current=null;const Tr=ct===Gt.DragEnd?"onDragEnd":"onDragCancel";if(ma){const Kn=J.current[Tr];Kn==null||Kn(ma),M({type:Tr,event:ma})}})}}},[k]),Js=m.useCallback((vt,st)=>(Bt,Ce)=>{const ke=Bt.nativeEvent,Ue=k.get(Ce);if(ce.current!==null||!Ue||ke.dndKit||ke.defaultPrevented)return;const gt={active:Ue};vt(Bt,st.options,gt)===!0&&(ke.dndKit={capturedBy:st.sensor},ce.current=Ce,Tt(Bt,st))},[k,Tt]),Pl=b3(x,Js);T3(x),qa(()=>{fe&&D===al.Initializing&&O(al.Initialized)},[fe,D]),m.useEffect(()=>{const{onDragMove:vt}=J.current,{active:st,activatorEvent:Bt,collisions:Ce,over:ke}=je.current;if(!st||!Bt)return;const Ue={active:st,activatorEvent:Bt,collisions:Ce,delta:{x:At.x,y:At.y},over:ke};ba.unstable_batchedUpdates(()=>{vt==null||vt(Ue),M({type:"onDragMove",event:Ue})})},[At.x,At.y]),m.useEffect(()=>{const{active:vt,activatorEvent:st,collisions:Bt,droppableContainers:Ce,scrollAdjustedTranslate:ke}=je.current;if(!vt||ce.current==null||!st||!ke)return;const{onDragOver:Ue}=J.current,gt=Ce.get(Ta),Ct=gt&>.rect.current?{id:gt.id,rect:gt.rect.current,data:gt.data,disabled:gt.disabled}:null,ct={active:vt,activatorEvent:st,collisions:Bt,delta:{x:ke.x,y:ke.y},over:Ct};ba.unstable_batchedUpdates(()=>{dl(Ct),Ue==null||Ue(ct),M({type:"onDragOver",event:ct})})},[Ta]),qa(()=>{je.current={activatorEvent:H,active:ie,activeNode:ge,collisionRect:cn,collisions:fa,droppableRects:F,draggableNodes:k,draggingNode:et,draggingNodeRect:le,droppableContainers:X,over:Gn,scrollableAncestors:St,scrollAdjustedTranslate:At},G.current={initial:le,translated:cn}},[ie,ge,fa,cn,k,et,le,F,X,Gn,St,At]),g3({...oe,delta:$,draggingRect:cn,pointerCoordinates:Qt,scrollableAncestors:St,scrollableAncestorRects:Ft});const ql=m.useMemo(()=>({active:ie,activeNode:ge,activeNodeRect:fe,activatorEvent:H,collisions:fa,containerNodeRect:Te,dragOverlay:Fe,draggableNodes:k,droppableContainers:X,droppableRects:F,over:Gn,measureDroppableContainers:re,scrollableAncestors:St,scrollableAncestorRects:Ft,measuringConfiguration:I,measuringScheduled:he,windowRect:kt}),[ie,ge,fe,H,fa,Te,Fe,k,X,F,Gn,re,St,Ft,I,he,kt]),Ya=m.useMemo(()=>({activatorEvent:H,activators:Pl,active:ie,activeNodeRect:fe,ariaDescribedById:{draggable:ee},dispatch:N,draggableNodes:k,over:Gn,measureDroppableContainers:re}),[H,Pl,ie,fe,N,ee,k,Gn,re]);return ue.createElement(rS.Provider,{value:T},ue.createElement(Zu.Provider,{value:Ya},ue.createElement(xS.Provider,{value:ql},ue.createElement(yS.Provider,{value:Dt},v)),ue.createElement(H3,{disabled:(p==null?void 0:p.restoreFocus)===!1})),ue.createElement(I_,{...p,hiddenTextDescribedById:ee}));function Nr(){const vt=(se==null?void 0:se.autoScrollEnabled)===!1,st=typeof g=="object"?g.enabled===!1:g===!1,Bt=A&&!vt&&!st;return typeof g=="object"?{...g,enabled:Bt}:{enabled:Bt}}}),$3=m.createContext(null),Pb="button",Y3="Draggable";function G3(n){let{id:a,data:l,disabled:s=!1,attributes:c}=n;const u=xi(Y3),{activators:f,activatorEvent:p,active:g,activeNodeRect:v,ariaDescribedById:x,draggableNodes:y,over:b}=m.useContext(Zu),{role:w=Pb,roleDescription:E="draggable",tabIndex:j=0}=c??{},C=(g==null?void 0:g.id)===a,N=m.useContext(C?yS:$3),[M,T]=du(),[D,O]=du(),A=M3(f,a),U=ti(l);qa(()=>(y.set(a,{id:a,key:u,node:M,activatorNode:D,data:U}),()=>{const $=y.get(a);$&&$.key===u&&y.delete(a)}),[y,a]);const k=m.useMemo(()=>({role:w,tabIndex:j,"aria-disabled":s,"aria-pressed":C&&w===Pb?!0:void 0,"aria-roledescription":E,"aria-describedby":x.draggable}),[s,w,j,C,E,x.draggable]);return{active:g,activatorEvent:p,activeNodeRect:v,attributes:k,isDragging:C,listeners:s?void 0:A,node:M,over:b,setNodeRef:T,setActivatorNodeRef:O,transform:N}}function K3(){return m.useContext(xS)}const X3="Droppable",F3={timeout:25};function Q3(n){let{data:a,disabled:l=!1,id:s,resizeObserverConfig:c}=n;const u=xi(X3),{active:f,dispatch:p,over:g,measureDroppableContainers:v}=m.useContext(Zu),x=m.useRef({disabled:l}),y=m.useRef(!1),b=m.useRef(null),w=m.useRef(null),{disabled:E,updateMeasurementsFor:j,timeout:C}={...F3,...c},N=ti(j??s),M=m.useCallback(()=>{if(!y.current){y.current=!0;return}w.current!=null&&clearTimeout(w.current),w.current=setTimeout(()=>{v(Array.isArray(N.current)?N.current:[N.current]),w.current=null},C)},[C]),T=Qu({callback:M,disabled:E||!f}),D=m.useCallback((k,$)=>{T&&($&&(T.unobserve($),y.current=!1),k&&T.observe(k))},[T]),[O,A]=du(D),U=ti(a);return m.useEffect(()=>{!T||!O.current||(T.disconnect(),y.current=!1,T.observe(O.current))},[O,T]),m.useEffect(()=>(p({type:Gt.RegisterDroppable,element:{id:s,key:u,disabled:l,node:O,rect:b,data:U}}),()=>p({type:Gt.UnregisterDroppable,key:u,id:s})),[s]),m.useEffect(()=>{l!==x.current.disabled&&(p({type:Gt.SetDroppableDisabled,id:s,key:u,disabled:l}),x.current.disabled=l)},[s,u,l,p]),{active:f,rect:b,isOver:(g==null?void 0:g.id)===s,node:O,over:g,setNodeRef:A}}function Z3(n,a,l){const s={...n};return a.top+n.y<=l.top?s.y=l.top-a.top:a.bottom+n.y>=l.top+l.height&&(s.y=l.top+l.height-a.bottom),a.left+n.x<=l.left?s.x=l.left-a.left:a.right+n.x>=l.left+l.width&&(s.x=l.left+l.width-a.right),s}const J3=n=>{let{containerNodeRect:a,draggingNodeRect:l,transform:s}=n;return!l||!a?s:Z3(s,l,a)},W3=n=>{let{transform:a}=n;return{...a,x:0}};function Op(n,a,l){const s=n.slice();return s.splice(l<0?s.length+l:l,0,s.splice(a,1)[0]),s}function ek(n,a){return n.reduce((l,s,c)=>{const u=a.get(s);return u&&(l[c]=u),l},Array(n.length))}function Pc(n){return n!==null&&n>=0}function tk(n,a){if(n===a)return!0;if(n.length!==a.length)return!1;for(let l=0;l<n.length;l++)if(n[l]!==a[l])return!1;return!0}function nk(n){return typeof n=="boolean"?{draggable:n,droppable:n}:n}const bS=n=>{let{rects:a,activeIndex:l,overIndex:s,index:c}=n;const u=Op(a,s,l),f=a[c],p=u[c];return!p||!f?null:{x:p.left-f.left,y:p.top-f.top,scaleX:p.width/f.width,scaleY:p.height/f.height}},qc={scaleX:1,scaleY:1},ak=n=>{var a;let{activeIndex:l,activeNodeRect:s,index:c,rects:u,overIndex:f}=n;const p=(a=u[l])!=null?a:s;if(!p)return null;if(c===l){const v=u[f];return v?{x:0,y:l<f?v.top+v.height-(p.top+p.height):v.top-p.top,...qc}:null}const g=rk(u,c,l);return c>l&&c<=f?{x:0,y:-p.height-g,...qc}:c<l&&c>=f?{x:0,y:p.height+g,...qc}:{x:0,y:0,...qc}};function rk(n,a,l){const s=n[a],c=n[a-1],u=n[a+1];return s?l<a?c?s.top-(c.top+c.height):u?u.top-(s.top+s.height):0:u?u.top-(s.top+s.height):c?s.top-(c.top+c.height):0:0}const wS="Sortable",SS=ue.createContext({activeIndex:-1,containerId:wS,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:bS,disabled:{draggable:!1,droppable:!1}});function lk(n){let{children:a,id:l,items:s,strategy:c=bS,disabled:u=!1}=n;const{active:f,dragOverlay:p,droppableRects:g,over:v,measureDroppableContainers:x}=K3(),y=xi(wS,l),b=p.rect!==null,w=m.useMemo(()=>s.map(A=>typeof A=="object"&&"id"in A?A.id:A),[s]),E=f!=null,j=f?w.indexOf(f.id):-1,C=v?w.indexOf(v.id):-1,N=m.useRef(w),M=!tk(w,N.current),T=C!==-1&&j===-1||M,D=nk(u);qa(()=>{M&&E&&x(w)},[M,w,E,x]),m.useEffect(()=>{N.current=w},[w]);const O=m.useMemo(()=>({activeIndex:j,containerId:y,disabled:D,disableTransforms:T,items:w,overIndex:C,useDragOverlay:b,sortedRects:ek(w,g),strategy:c}),[j,y,D.draggable,D.droppable,T,w,C,g,b,c]);return ue.createElement(SS.Provider,{value:O},a)}const sk=n=>{let{id:a,items:l,activeIndex:s,overIndex:c}=n;return Op(l,s,c).indexOf(a)},ok=n=>{let{containerId:a,isSorting:l,wasDragging:s,index:c,items:u,newIndex:f,previousItems:p,previousContainerId:g,transition:v}=n;return!v||!s||p!==u&&c===f?!1:l?!0:f!==c&&a===g},ik={duration:200,easing:"ease"},jS="transform",ck=fu.Transition.toString({property:jS,duration:0,easing:"linear"}),uk={roleDescription:"sortable"};function dk(n){let{disabled:a,index:l,node:s,rect:c}=n;const[u,f]=m.useState(null),p=m.useRef(l);return qa(()=>{if(!a&&l!==p.current&&s.current){const g=c.current;if(g){const v=Qs(s.current,{ignoreTransform:!0}),x={x:g.left-v.left,y:g.top-v.top,scaleX:g.width/v.width,scaleY:g.height/v.height};(x.x||x.y)&&f(x)}}l!==p.current&&(p.current=l)},[a,l,s,c]),m.useEffect(()=>{u&&f(null)},[u]),u}function fk(n){let{animateLayoutChanges:a=ok,attributes:l,disabled:s,data:c,getNewIndex:u=sk,id:f,strategy:p,resizeObserverConfig:g,transition:v=ik}=n;const{items:x,containerId:y,activeIndex:b,disabled:w,disableTransforms:E,sortedRects:j,overIndex:C,useDragOverlay:N,strategy:M}=m.useContext(SS),T=hk(s,w),D=x.indexOf(f),O=m.useMemo(()=>({sortable:{containerId:y,index:D,items:x},...c}),[y,c,D,x]),A=m.useMemo(()=>x.slice(x.indexOf(f)),[x,f]),{rect:U,node:k,isOver:$,setNodeRef:X}=Q3({id:f,data:O,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:A,...g}}),{active:te,activatorEvent:G,activeNodeRect:ie,attributes:ce,setNodeRef:se,listeners:_,isDragging:H,over:Q,setActivatorNodeRef:J,transform:ee}=G3({id:f,data:O,attributes:{...uk,...l},disabled:T.draggable}),z=N_(X,se),I=!!te,F=I&&!E&&Pc(b)&&Pc(C),re=!N&&H,he=re&&F?ee:null,q=F?he??(p??M)({rects:j,activeNodeRect:ie,activeIndex:b,overIndex:C,index:D}):null,oe=Pc(b)&&Pc(C)?u({id:f,items:x,activeIndex:b,overIndex:C}):D,de=te==null?void 0:te.id,fe=m.useRef({activeId:de,items:x,newIndex:oe,containerId:y}),Te=x!==fe.current.items,je=a({active:te,containerId:y,isDragging:H,isSorting:I,id:f,index:D,items:x,newIndex:fe.current.newIndex,previousItems:fe.current.items,previousContainerId:fe.current.containerId,transition:v,wasDragging:fe.current.activeId!=null}),De=dk({disabled:!je,index:D,node:k,rect:U});return m.useEffect(()=>{I&&fe.current.newIndex!==oe&&(fe.current.newIndex=oe),y!==fe.current.containerId&&(fe.current.containerId=y),x!==fe.current.items&&(fe.current.items=x)},[I,oe,y,x]),m.useEffect(()=>{if(de===fe.current.activeId)return;if(de!=null&&fe.current.activeId==null){fe.current.activeId=de;return}const et=setTimeout(()=>{fe.current.activeId=de},50);return()=>clearTimeout(et)},[de]),{active:te,activeIndex:b,attributes:ce,data:O,rect:U,index:D,newIndex:oe,items:x,isOver:$,isSorting:I,isDragging:H,listeners:_,node:k,overIndex:C,over:Q,setNodeRef:z,setActivatorNodeRef:J,setDroppableNodeRef:X,setDraggableNodeRef:se,transform:De??q,transition:Fe()};function Fe(){if(De||Te&&fe.current.newIndex===D)return ck;if(!(re&&!Np(G)||!v)&&(I||je))return fu.Transition.toString({...v,property:jS})}}function hk(n,a){var l,s;return typeof n=="boolean"?{draggable:n,droppable:!1}:{draggable:(l=n==null?void 0:n.draggable)!=null?l:a.draggable,droppable:(s=n==null?void 0:n.droppable)!=null?s:a.droppable}}function pu(n){if(!n)return!1;const a=n.data.current;return!!(a&&"sortable"in a&&typeof a.sortable=="object"&&"containerId"in a.sortable&&"items"in a.sortable&&"index"in a.sortable)}const mk=[Ke.Down,Ke.Right,Ke.Up,Ke.Left],pk=(n,a)=>{let{context:{active:l,collisionRect:s,droppableRects:c,droppableContainers:u,over:f,scrollableAncestors:p}}=a;if(mk.includes(n.code)){if(n.preventDefault(),!l||!s)return;const g=[];u.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const b=c.get(y.id);if(b)switch(n.code){case Ke.Down:s.top<b.top&&g.push(y);break;case Ke.Up:s.top>b.top&&g.push(y);break;case Ke.Left:s.left>b.left&&g.push(y);break;case Ke.Right:s.left<b.left&&g.push(y);break}});const v=$_({collisionRect:s,droppableRects:c,droppableContainers:g});let x=oS(v,"id");if(x===(f==null?void 0:f.id)&&v.length>1&&(x=v[1].id),x!=null){const y=u.get(l.id),b=u.get(x),w=b?c.get(b.id):null,E=b==null?void 0:b.node.current;if(E&&w&&y&&b){const C=Fu(E).some((A,U)=>p[U]!==A),N=CS(y,b),M=gk(y,b),T=C||!N?{x:0,y:0}:{x:M?s.width-w.width:0,y:M?s.height-w.height:0},D={x:w.left,y:w.top};return T.x&&T.y?D:ni(D,T)}}}};function CS(n,a){return!pu(n)||!pu(a)?!1:n.data.current.sortable.containerId===a.data.current.sortable.containerId}function gk(n,a){return!pu(n)||!pu(a)||!CS(n,a)?!1:n.data.current.sortable.index<a.data.current.sortable.index}const Uh={maxTotalAttempts:3,fallbackOnConnection:!0,fallbackOnConnectTimeout:!0,fallbackOnFirstTokenTimeout:!0,fallbackOn408:!0,fallbackOn429:!0,fallbackOn5xx:!0},vk={member_disabled:"member disabled",model_missing:"model missing",provider_disabled:"provider disabled",provider_down:"provider down",model_disabled:"model disabled",upstream_unavailable:"upstream unavailable",circuit_open:"circuit open",chat_capability_unavailable:"chat capability unavailable"},gu=n=>n.map((a,l)=>({...a,position:l}));function xk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState(!1),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(!1),[b,w]=m.useState(!1),[E,j]=m.useState(null),[C,N]=m.useState(null),[M,T]=m.useState({name:"",slug:"",enabled:!0,...Uh,members:[]}),[D,O]=m.useState({name:"",slug:"",enabled:!0,...Uh,members:[]}),[A,U]=m.useState(null),k=async()=>{const[_,H]=await Promise.all([Se.get("/api/admin/combos"),Se.get("/api/admin/models")]);a(_.combos),s(H.models)};m.useEffect(()=>{k()},[]);const $=async _=>{j(_.id);try{N(await Se.post("/api/admin/combos/"+_.id+"/test"))}catch(H){ve.error(H.message)}finally{j(null)}},X=async()=>{if(M.members.length===0){ve.error("Add at least one member");return}y(!0);try{await Se.post("/api/admin/combos",{name:M.name,slug:M.slug.trim()||void 0,enabled:M.enabled,...M,members:M.members}),ve.success("Combo created"),u(!1),T({name:"",slug:"",enabled:!0,...Uh,members:[]}),k()}catch(_){ve.error(_.message)}finally{y(!1)}},te=async _=>{try{const Q=(await Se.get(`/api/admin/combos/${_.id}`)).combo;v(Q.id),O({name:Q.name,slug:Q.publicModelId.startsWith("combo/")?Q.slug:"",enabled:Q.enabled,maxTotalAttempts:Q.maxTotalAttempts,fallbackOnConnection:Q.fallbackOnConnection,fallbackOnConnectTimeout:Q.fallbackOnConnectTimeout,fallbackOnFirstTokenTimeout:Q.fallbackOnFirstTokenTimeout,fallbackOn408:Q.fallbackOn408,fallbackOn429:Q.fallbackOn429,fallbackOn5xx:Q.fallbackOn5xx,members:Q.members.map(J=>({modelId:J.modelId,position:J.position,enabled:J.enabled}))}),p(!0)}catch(H){ve.error(H.message)}},G=async()=>{if(g){if(D.members.length===0){ve.error("Add at least one member");return}w(!0);try{await Se.patch("/api/admin/combos",{id:g,name:D.name,slug:D.slug.trim()||void 0,enabled:D.enabled,...D,members:D.members}),ve.success("Combo updated"),p(!1),v(null),k()}catch(_){ve.error(_.message)}finally{w(!1)}}},ie=_=>{T(H=>({...H,members:gu([...H.members,{modelId:_,position:H.members.length,enabled:!0}])}))},ce=_=>{O(H=>({...H,members:gu([...H.members,{modelId:_,position:H.members.length,enabled:!0}])}))},se=async _=>{try{await Se.del(`/api/admin/combos/${_}`),ve.success("Combo removed"),U(null),k()}catch(H){ve.error(H.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Combos",description:"Virtual models combining physical models",actions:o.jsxs(Mn,{open:c,onOpenChange:u,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New combo"]})}),o.jsxs(vn,{className:"max-h-[calc(100vh-2rem)] max-w-2xl grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden",children:[o.jsx(xn,{children:o.jsx(yn,{children:"New combo"})}),o.jsxs("div",{className:"min-h-0 space-y-3 overflow-y-auto pr-1",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:M.name,onChange:_=>T({...M,name:_.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional — empty uses the name as the model ID)"}),o.jsx(Ae,{value:M.slug,onChange:_=>T({...M,slug:_.target.value}),placeholder:"empty → gpt-5.5 · set → combo/gpt-5.5"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:M.enabled,onCheckedChange:_=>T({...M,enabled:_})}),o.jsx(we,{children:"Enabled"})]}),o.jsx(qb,{value:M,onChange:_=>T(H=>({...H,..._}))}),o.jsxs("div",{children:[o.jsx(we,{children:"Members — priority order · drag to reorder"}),o.jsx(Yb,{models:l,addedIds:M.members.map(_=>_.modelId),onAdd:ie}),o.jsx(Vb,{members:M.members,modelFor:_=>l.find(H=>H.id===_.modelId)??null}),o.jsx($b,{className:"mt-2",members:M.members,label:_=>{var H;return((H=l.find(Q=>Q.id===_.modelId))==null?void 0:H.publicModelId)??_.modelId},modelFor:_=>l.find(H=>H.id===_.modelId)??null,onChange:_=>T(H=>({...H,members:_}))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),o.jsx(me,{disabled:!M.name||x,onClick:X,children:x?"Creating…":"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All combos"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Public ID"}),o.jsx(ye,{children:"Members"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:5,className:"text-center text-muted-foreground",children:"No combos yet."})}),n.map(_=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:_.publicModelId}),o.jsx(pe,{children:_.memberCount}),o.jsxs(pe,{children:[o.jsxs(Qe,{variant:_.status==="ready"?"success":_.status==="disabled"?"secondary":"destructive",children:[_.healthyMemberCount,"/",_.memberCount," ready"]}),_.capabilityWarnings.length>0&&o.jsx("div",{className:"text-xs text-amber-600",children:"Capability metadata differs"}),_.status==="unavailable"&&_.unavailableReasons.length>0&&o.jsx("div",{className:"text-xs text-muted-foreground",children:_.unavailableReasons.map(H=>vk[H]??H).join(", ")})]}),o.jsx(pe,{children:_.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[o.jsxs(me,{size:"sm",variant:"outline",title:"Sends a real non-streaming inference request",onClick:()=>void $(_),disabled:E===_.id,children:[E===_.id?o.jsx(_s,{className:"mr-1 h-3.5 w-3.5 animate-spin"}):o.jsx(A0,{className:"mr-1 h-3.5 w-3.5"})," Test"]}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>void te(_),children:[o.jsx(xR,{className:"h-3.5 w-3.5"})," Sửa"]}),o.jsxs(me,{size:"sm",variant:"destructive",onClick:()=>U(_),children:[o.jsx(ju,{className:"h-3.5 w-3.5"})," Delete"]})]})})]},_.id))]})]})})]}),o.jsx(Mn,{open:f,onOpenChange:p,children:o.jsxs(vn,{className:"max-h-[calc(100vh-2rem)] max-w-2xl grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden",children:[o.jsx(xn,{children:o.jsx(yn,{children:"Edit combo"})}),o.jsxs("div",{className:"min-h-0 space-y-3 overflow-y-auto pr-1",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:D.name,onChange:_=>O({...D,name:_.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Slug (optional — leave empty to use the name as the model ID)"}),o.jsx(Ae,{value:D.slug,onChange:_=>O({...D,slug:_.target.value}),placeholder:"empty → gpt-5.5 · set → combo/gpt-5.5"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:D.enabled,onCheckedChange:_=>O({...D,enabled:_})}),o.jsx(we,{children:"Enabled"})]}),o.jsx(qb,{value:D,onChange:_=>O(H=>({...H,..._}))}),o.jsxs("div",{children:[o.jsx(we,{children:"Members — priority order · drag to reorder"}),o.jsx(Yb,{models:l,addedIds:D.members.map(_=>_.modelId),onAdd:ce}),o.jsx(Vb,{members:D.members,modelFor:_=>l.find(H=>H.id===_.modelId)??null}),o.jsx($b,{className:"mt-2",members:D.members,label:_=>{var H;return((H=l.find(Q=>Q.id===_.modelId))==null?void 0:H.publicModelId)??_.modelId},modelFor:_=>l.find(H=>H.id===_.modelId)??null,onChange:_=>O(H=>({...H,members:_}))})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(me,{disabled:!D.name||b,onClick:G,children:b?"Saving…":"Save"})]})]})}),o.jsx(Mn,{open:C!==null,onOpenChange:_=>{_||N(null)},children:o.jsxs(vn,{className:"max-w-2xl",children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"Combo test result"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Test sends a real non-streaming inference request through this combo."})]}),C&&o.jsx(yk,{result:C}),o.jsx(An,{children:o.jsx(me,{onClick:()=>N(null),children:"Close"})})]})}),o.jsx(up,{open:A!==null,onOpenChange:_=>{_||U(null)},children:o.jsxs(Pu,{children:[o.jsxs(dp,{children:[o.jsx(qu,{children:"Delete combo?"}),o.jsx(Vu,{children:"This removes the virtual model and its ordered fallback configuration. Request history is preserved."})]}),o.jsxs(fp,{children:[o.jsx(Yu,{children:"Cancel"}),o.jsx($u,{onClick:()=>A&&void se(A.id),children:"Delete"})]})]})})]})}function qb({value:n,onChange:a}){const l=[["fallbackOnConnection","Connection failure"],["fallbackOnConnectTimeout","Connect timeout"],["fallbackOnFirstTokenTimeout","First-token timeout"],["fallbackOn408","HTTP 408"],["fallbackOn429","HTTP 429"],["fallbackOn5xx","HTTP 5xx"]];return o.jsxs("div",{className:"rounded border bg-muted/20 p-3",children:[o.jsx("div",{className:"mb-2 text-sm font-medium",children:"Fallback policy"}),o.jsxs("div",{className:"grid gap-3 sm:grid-cols-[10rem_1fr]",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Max total attempts"}),o.jsx(Ae,{type:"number",min:1,max:8,value:n.maxTotalAttempts,onChange:s=>a({maxTotalAttempts:Math.min(8,Math.max(1,Number(s.target.value)||1))})})]}),o.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:l.map(([s,c])=>o.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[o.jsx(Ca,{checked:!!n[s],onCheckedChange:u=>a({[s]:u})}),o.jsx("span",{children:c})]},s))})]})]})}function Vb({members:n,modelFor:a}){if(n.length===0)return null;const l=n.map(a).filter(c=>!!c),s=["chat","streaming","tools","structured_output","image_input","reasoning"].filter(c=>new Set(l.map(u=>u.capabilities[c]===!0?"yes":u.capabilities[c]===!1?"no":"unknown")).size>1);return o.jsxs("div",{className:"rounded border bg-muted/20 p-2 text-xs",children:[o.jsxs("div",{className:"mb-1 font-medium",children:["Route preview ",o.jsx("span",{className:"font-normal text-muted-foreground",children:"(first available member wins)"})]}),s.length>0&&o.jsxs("div",{className:"mb-2 flex items-center gap-1 text-amber-600",children:[o.jsx(O0,{className:"h-3.5 w-3.5"})," Members differ on: ",s.join(", ")]}),o.jsx("div",{className:"space-y-1",children:n.map((c,u)=>{const f=a(c);return o.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[o.jsxs("span",{className:"w-4 text-muted-foreground",children:[u+1,"."]}),o.jsx("span",{children:(f==null?void 0:f.publicModelId)??c.modelId}),o.jsxs("span",{className:"text-muted-foreground",children:["→ ",(f==null?void 0:f.upstreamModelId)??"upstream model unknown"]})]},c.id??c.modelId)})})]})}function yk({result:n}){return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between rounded border p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[n.success?o.jsx(ci,{className:"h-4 w-4 text-emerald-600"}):o.jsx(O0,{className:"h-4 w-4 text-amber-600"}),o.jsx(Qe,{variant:n.success?"success":"warning",children:n.success?"Success":"Failed"})]}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.latencyMs," ms total"]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-sm font-medium",children:"Selected upstream"}),n.selectedModel?o.jsxs("div",{className:"rounded border bg-muted/20 p-2 font-mono text-xs",children:[n.selectedModel.publicModelId," → ",n.selectedModel.upstreamModelId,o.jsxs("span",{className:"ml-2 text-muted-foreground",children:["(",n.selectedModel.providerSlug,")"]})]}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"No member completed successfully."})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-sm font-medium",children:"Attempts"}),o.jsx("div",{className:"space-y-1",children:n.attempts.map((a,l)=>o.jsxs("div",{className:"flex items-center gap-2 rounded border p-2 text-xs",children:[o.jsxs("span",{className:"w-4 text-muted-foreground",children:[l+1,"."]}),o.jsxs("span",{className:"min-w-0 flex-1 font-mono",children:[a.publicModelId," → ",a.upstreamModelId]}),o.jsxs("span",{className:"text-muted-foreground",children:[a.latencyMs," ms"]}),o.jsx(Qe,{variant:a.success?"success":"warning",children:a.success?"Used":a.failureReason??"Skipped"})]},a.publicModelId+"-"+l))})]}),n.text&&o.jsx("pre",{className:"max-h-32 overflow-auto whitespace-pre-wrap rounded border bg-muted/20 p-2 text-xs",children:n.text})]})}function $b({members:n,label:a,modelFor:l,onChange:s,className:c}){const u=P_(Mb(Dp,{activationConstraint:{distance:4}}),Mb(Mp,{coordinateGetter:pk}));if(n.length===0)return o.jsx("p",{className:Ee("text-xs text-muted-foreground",c),children:"No members yet — add at least one."});const f=({active:p,over:g})=>{!g||p.id===g.id||s(gu(Op(n,Number(p.id),Number(g.id))))};return o.jsx(V3,{sensors:u,collisionDetection:V_,modifiers:[W3,J3],onDragEnd:f,children:o.jsx(lk,{items:n.map((p,g)=>g),strategy:ak,children:o.jsx("div",{className:Ee("space-y-1",c),children:n.map((p,g)=>o.jsx(bk,{index:g,label:a(p),model:l(p),onRemove:()=>s(gu(n.filter((v,x)=>x!==g)))},p.id??p.modelId))})})})}function bk({index:n,label:a,model:l,onRemove:s}){const{attributes:c,listeners:u,setNodeRef:f,transform:p,transition:g,isDragging:v}=fk({id:n});return o.jsxs("div",{ref:f,style:{transform:p?`translate3d(${p.x}px, ${p.y}px, 0)`:void 0,transition:g},className:Ee("flex items-center gap-2 rounded border p-2 text-sm",v&&"relative z-10 bg-muted/60 shadow-sm"),children:[o.jsx("button",{type:"button",...c,...u,"aria-label":`Reorder ${a}`,title:"Drag to change priority",className:"cursor-grab touch-none rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground active:cursor-grabbing",children:o.jsx(cR,{className:"h-4 w-4"})}),o.jsx("span",{className:"w-5 text-xs tabular-nums text-muted-foreground",children:n+1}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate font-mono text-xs",children:a}),o.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[(l==null?void 0:l.providerSlug)||"provider"," · upstream: ",(l==null?void 0:l.upstreamModelId)??"unknown"]})]}),o.jsx(Qe,{variant:l&&l.enabled&&l.providerEnabled&&l.providerHealth!=="down"&&l.providerHealth!=="circuit_open"&&!l.circuitOpen&&l.upstreamAvailable&&l.capabilities.chat!==!1?"success":"warning",children:l&&l.enabled&&l.providerEnabled&&l.providerHealth!=="down"&&l.providerHealth!=="circuit_open"&&!l.circuitOpen&&l.upstreamAvailable&&l.capabilities.chat!==!1?"Ready":"Unavailable"}),o.jsx(me,{size:"sm",variant:"outline",onClick:s,children:"Remove"})]})}function Yb({models:n,addedIds:a,onAdd:l}){const[s,c]=m.useState(""),f=(s?n.filter(p=>{const g=s.toLowerCase();return p.publicModelId.toLowerCase().includes(g)||p.displayName.toLowerCase().includes(g)}):n).filter(p=>!a.includes(p.id));return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"relative",children:[o.jsx(D0,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(Ae,{className:"pl-8",placeholder:"Search models…",value:s,onChange:p=>c(p.target.value)}),s&&o.jsx("button",{className:"absolute right-2 top-2.5 text-muted-foreground hover:text-foreground",onClick:()=>c(""),children:o.jsx(Cu,{className:"h-4 w-4"})})]}),f.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No models match."}):o.jsx("div",{className:"max-h-40 space-y-1 overflow-auto rounded border p-1",children:f.map(p=>o.jsxs("div",{className:"flex items-center justify-between rounded p-1 text-sm hover:bg-accent",children:[o.jsx("span",{className:"font-mono text-xs",children:p.publicModelId}),o.jsx(me,{size:"sm",variant:"ghost",onClick:()=>l(p.id),children:"+ Add"})]},p.id))})]})}function wk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState([]),[f,p]=m.useState(!1),[g,v]=m.useState({alias:"",targetKind:"model",targetId:"",enabled:!0}),x=async()=>{const[b,w,E]=await Promise.all([Se.get("/api/admin/aliases"),Se.get("/api/admin/models"),Se.get("/api/admin/combos")]);a(b.aliases),s(w.models),u(E.combos)};m.useEffect(()=>{x()},[]);const y=async()=>{try{await Se.post("/api/admin/aliases",g),ve.success("Alias created"),p(!1),v({alias:"",targetKind:"model",targetId:"",enabled:!0}),x()}catch(b){ve.error(b.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"Aliases",description:"Stable client-visible names for models or combos",actions:o.jsxs(Mn,{open:f,onOpenChange:p,children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New alias"]})}),o.jsxs(vn,{children:[o.jsx(xn,{children:o.jsx(yn,{children:"New alias"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Alias"}),o.jsx(Ae,{value:g.alias,onChange:b=>v({...g,alias:b.target.value}),placeholder:"coding"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Target type"}),o.jsxs(Ua,{value:g.targetKind,onValueChange:b=>v({...g,targetKind:b}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"model",children:"Model"}),o.jsx(Rt,{value:"combo",children:"Combo"})]})]})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Target"}),o.jsxs(Ua,{value:g.targetId,onValueChange:b=>v({...g,targetId:b}),children:[o.jsx(Sa,{children:o.jsx(Ba,{placeholder:"Choose target"})}),o.jsx(ja,{children:(g.targetKind==="model"?l:c).map(b=>o.jsx(Rt,{value:b.id,children:b.publicModelId},b.id))})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:g.enabled,onCheckedChange:b=>v({...g,enabled:b})}),o.jsx(we,{children:"Enabled"})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(me,{disabled:!g.alias||!g.targetId,onClick:y,children:"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All aliases"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Alias"}),o.jsx(ye,{children:"Target"}),o.jsx(ye,{children:"Type"}),o.jsx(ye,{children:"Enabled"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:5,className:"text-center text-muted-foreground",children:"No aliases yet."})}),n.map(b=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:b.alias}),o.jsx(pe,{className:"font-mono text-xs",children:b.targetName??b.targetId}),o.jsx(pe,{children:o.jsx(Qe,{variant:"outline",children:b.targetKind})}),o.jsx(pe,{children:b.enabled?"Yes":"No"}),o.jsx(pe,{className:"text-right",children:o.jsx(me,{size:"sm",variant:"outline",onClick:async()=>{await Se.del(`/api/admin/aliases/${b.id}`),ve.success("Removed"),x()},children:"Delete"})})]},b.id))]})]})})]})]})}function Sk(){const[n,a]=m.useState([]),[l,s]=m.useState([]),[c,u]=m.useState([]),[f,p]=m.useState(!1),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(null),[E,j]=m.useState({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),C=async()=>{const[A,U,k]=await Promise.all([Se.get("/api/admin/api-keys"),Se.get("/api/admin/models"),Se.get("/api/admin/combos")]);a(A.apiKeys),s(U.models),u(k.combos)};m.useEffect(()=>{C()},[]);const N=async()=>{try{if(g){await Se.patch("/api/admin/api-keys",{id:g,name:E.name,expiresAt:E.expiresAt||null,allowAllModels:E.allowAll,permissions:E.allowAll?[]:E.permissions,rpmLimit:E.rpmLimit?Number(E.rpmLimit):null,tpmLimit:E.tpmLimit?Number(E.tpmLimit):null,maxConcurrent:E.concurrency?Number(E.concurrency):null}),p(!1),v(null),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),ve.success("Key updated"),C();return}const A=await Se.post("/api/admin/api-keys",{name:E.name,expiresAt:E.expiresAt||null,allowAllModels:E.allowAll,permissions:E.allowAll?void 0:E.permissions,rpmLimit:E.rpmLimit?Number(E.rpmLimit):null,tpmLimit:E.tpmLimit?Number(E.tpmLimit):null,maxConcurrent:E.concurrency?Number(E.concurrency):null,...E.customSecret.trim()?{secret:E.customSecret.trim()}:{}});p(!1),y({secret:A.secret,name:A.name}),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""}),C()}catch(A){ve.error(A.message)}},M=async A=>{try{const k=((await Se.get(`/api/admin/api-keys/${A.id}`)).apiKey.permissions??[]).filter($=>$.targetKind==="model"||$.targetKind==="combo");v(A.id),j({name:A.name,expiresAt:A.expiresAt?A.expiresAt.slice(0,16):"",allowAll:A.allowAllModels,permissions:k,rpmLimit:A.rpmLimit!=null?String(A.rpmLimit):"",tpmLimit:A.tpmLimit!=null?String(A.tpmLimit):"",concurrency:A.concurrencyLimit!=null?String(A.concurrencyLimit):"",customSecret:""}),p(!0)}catch(U){ve.error(U.message)}},T=()=>{p(!1),v(null),j({name:"",expiresAt:"",allowAll:!0,permissions:[],rpmLimit:"",tpmLimit:"",concurrency:"",customSecret:""})},D=async(A,U)=>{try{await Se.patch("/api/admin/api-keys",{id:A,enabled:!U}),ve.success(U?"Key disabled":"Key enabled"),C()}catch(k){ve.error(k.message)}},O=async A=>{if(window.confirm("Delete this API key? This cannot be undone."))try{await Se.del(`/api/admin/api-keys/${A}`),ve.success("Key deleted"),C()}catch(U){ve.error(U.message)}};return o.jsxs("div",{children:[o.jsx($a,{title:"API Keys",description:"Gateway bearer keys for client applications",actions:o.jsxs(Mn,{open:f,onOpenChange:A=>{A?p(!0):T()},children:[o.jsx(mi,{asChild:!0,children:o.jsxs(me,{children:[o.jsx(Su,{className:"mr-1 h-4 w-4"})," New key"]})}),o.jsxs(vn,{className:"max-w-2xl",children:[o.jsx(xn,{children:o.jsx(yn,{children:g?"Edit API key":"New API key"})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Name"}),o.jsx(Ae,{value:E.name,onChange:A=>j({...E,name:A.target.value})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Expires (optional)"}),o.jsx(Ae,{type:"datetime-local",value:E.expiresAt,onChange:A=>j({...E,expiresAt:A.target.value})})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[o.jsxs("div",{children:[o.jsx(we,{children:"RPM limit"}),o.jsx(Ae,{value:E.rpmLimit,onChange:A=>j({...E,rpmLimit:A.target.value}),type:"number"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"TPM limit"}),o.jsx(Ae,{value:E.tpmLimit,onChange:A=>j({...E,tpmLimit:A.target.value}),type:"number"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Concurrency"}),o.jsx(Ae,{value:E.concurrency,onChange:A=>j({...E,concurrency:A.target.value}),type:"number"})]})]}),!g&&o.jsxs("div",{children:[o.jsx(we,{children:"Key value (optional)"}),o.jsx(Ae,{value:E.customSecret,onChange:A=>j({...E,customSecret:A.target.value}),placeholder:"Leave empty to auto-generate ld-…"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"If provided, this exact value is stored as the key. Otherwise a random ld-… key is generated."})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ca,{checked:E.allowAll,onCheckedChange:A=>j({...E,allowAll:A})}),o.jsx(we,{children:"Allow all current and future models"})]}),!E.allowAll&&o.jsxs("div",{children:[o.jsx(we,{children:"Scope"}),o.jsx("div",{className:"max-h-48 space-y-1 overflow-auto rounded border p-2",children:[...l.map(A=>({targetKind:"model",targetId:A.id,label:A.publicModelId})),...c.map(A=>({targetKind:"combo",targetId:A.id,label:A.publicModelId}))].map(A=>{const U=E.permissions.some(k=>k.targetKind===A.targetKind&&k.targetId===A.targetId);return o.jsxs("label",{className:"flex items-center gap-2 rounded p-1 text-sm hover:bg-accent",children:[o.jsx(jp,{checked:U,onCheckedChange:k=>{j($=>({...$,permissions:k?[...$.permissions,{targetKind:A.targetKind,targetId:A.targetId}]:$.permissions.filter(X=>!(X.targetKind===A.targetKind&&X.targetId===A.targetId))}))}}),o.jsx("span",{className:"font-mono text-xs",children:A.label}),o.jsx(Qe,{variant:"outline",className:"ml-1",children:A.targetKind})]},`${A.targetKind}:${A.targetId}`)})})]})]}),o.jsxs(An,{children:[o.jsx(me,{variant:"outline",onClick:T,children:"Cancel"}),o.jsx(me,{disabled:!E.name,onClick:N,children:g?"Save changes":"Create"})]})]})]})}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"All keys"}),o.jsxs(gn,{children:[n.length," total"]})]}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Name"}),o.jsx(ye,{children:"Prefix"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Scope"}),o.jsx(ye,{children:"RPM/TPM/Conc"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:6,className:"text-center text-muted-foreground",children:"No API keys yet."})}),n.map(A=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-medium",children:A.name}),o.jsxs(pe,{className:"font-mono text-xs",children:[A.keyPrefix,"…"]}),o.jsx(pe,{children:A.enabled?o.jsx(Qe,{variant:"success",children:"enabled"}):o.jsx(Qe,{variant:"destructive",children:"disabled"})}),o.jsx(pe,{children:A.allowAllModels?"all":`${A.modelScopeCount} scoped`}),o.jsx(pe,{className:"text-xs",children:[A.rpmLimit,A.tpmLimit,A.concurrencyLimit].map((U,k)=>U?["","RPM","TPM","Conc"][k+1]:null).filter(Boolean).join(" / ")||"—"}),o.jsx(pe,{className:"text-right",children:o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[A.secret&&o.jsxs(o.Fragment,{children:[o.jsx(me,{size:"sm",variant:"ghost",title:"Copy secret",onClick:()=>{navigator.clipboard.writeText(A.secret),ve.success("Copied")},children:o.jsx(Fc,{className:"h-3.5 w-3.5"})}),o.jsx(me,{size:"sm",variant:"ghost",title:"Show secret",onClick:()=>w({secret:A.secret,name:A.name}),children:o.jsx(sR,{className:"h-3.5 w-3.5"})})]}),o.jsx(me,{size:"sm",variant:"ghost",title:"Edit",onClick:()=>void M(A),children:o.jsx(hR,{className:"h-3.5 w-3.5"})}),o.jsxs(me,{size:"sm",variant:"outline",onClick:()=>D(A.id,A.enabled),children:[A.enabled?o.jsx(FE,{className:"mr-1 h-3.5 w-3.5"}):o.jsx(ci,{className:"mr-1 h-3.5 w-3.5"}),A.enabled?"Disable":"Enable"]}),o.jsx(me,{size:"sm",variant:"destructive",onClick:()=>O(A.id),children:o.jsx(ju,{className:"h-3.5 w-3.5"})})]})})]},A.id))]})]})})]}),o.jsx(Mn,{open:!!x,onOpenChange:A=>{A||y(null)},children:o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsx(yn,{children:"API key created"}),o.jsx(uu,{children:"Copy now — this secret will not be shown again."})]}),o.jsx("div",{className:"rounded border bg-muted p-3 font-mono text-xs break-all",children:x==null?void 0:x.secret}),o.jsxs(An,{children:[o.jsxs(me,{onClick:()=>{x&&(navigator.clipboard.writeText(x.secret),ve.success("Copied"))},children:[o.jsx(Fc,{className:"mr-1 h-4 w-4"})," Copy"]}),o.jsx(me,{variant:"outline",onClick:()=>y(null),children:"I have saved it"})]})]})}),o.jsx(Mn,{open:!!b,onOpenChange:A=>{A||w(null)},children:o.jsxs(vn,{children:[o.jsxs(xn,{children:[o.jsxs(yn,{children:["API key: ",b==null?void 0:b.name]}),o.jsx(uu,{children:"Full secret for this key, readable any time."})]}),o.jsx("div",{className:"rounded border bg-muted p-3 font-mono text-xs break-all",children:b==null?void 0:b.secret}),o.jsxs(An,{children:[o.jsxs(me,{onClick:()=>{b&&(navigator.clipboard.writeText(b.secret),ve.success("Copied"))},children:[o.jsx(Fc,{className:"mr-1 h-4 w-4"})," Copy"]}),o.jsx(me,{variant:"outline",onClick:()=>w(null),children:"Close"})]})]})})]})}const jk=3e3;function Ck(n,a){return!(a.success!=="all"&&n.success!==(a.success==="true")||a.protocol!=="all"&&n.protocol!==a.protocol||a.streaming!=="all"&&n.streaming!==(a.streaming==="true")||a.model&&!n.requestedModel.toLowerCase().includes(a.model.toLowerCase()))}function Ek(){const[n,a]=m.useState([]),[l,s]=m.useState(0),[c,u]=m.useState(0),[f,p]=m.useState({success:"all",protocol:"all",streaming:"all",model:""}),[g,v]=m.useState(null),[x,y]=m.useState(null),[b,w]=m.useState(0),E=50,j=m.useRef(Date.now()),C=m.useRef(new Set),N=m.useRef(f);N.current=f;const M=m.useRef(c);M.current=c;const T=m.useCallback(async()=>{const O=new URLSearchParams;O.set("limit",String(E)),O.set("offset",String(c)),f.success!=="all"&&O.set("success",f.success),f.protocol!=="all"&&O.set("protocol",f.protocol),f.streaming!=="all"&&O.set("streaming",f.streaming),f.model&&O.set("requestedModel",f.model);const A=await Se.get(`/api/admin/requests?${O.toString()}`);a(A.requests),s(A.total);for(const U of A.requests)C.current.add(U.id)},[c,f]);m.useEffect(()=>{T()},[T]),m.useEffect(()=>{w(0)},[c,f]),m.useEffect(()=>{let O=!1,A=null;const U=new Set,k=()=>{O||(A=new EventSource(`/api/admin/requests/stream?since=${j.current}`),A.addEventListener("request",$=>{if(!O)try{const X=JSON.parse($.data),te=new Date(X.createdAt).getTime();if(Number.isFinite(te)&&(j.current=Math.max(j.current,te)),C.current.has(X.id))return;C.current.add(X.id),w(G=>G+1),M.current===0&&Ck(X,N.current)&&(a(G=>G.some(ie=>ie.id===X.id)?G:[X,...G].slice(0,E)),s(G=>G+1))}catch{}}),A.onerror=()=>{A==null||A.close(),A=null,O||U.add(setTimeout(k,jk))})};return k(),()=>{O=!0,A==null||A.close();for(const $ of U)clearTimeout($);U.clear()}},[]);const D=async O=>{v(O);const A=await Se.get(`/api/admin/requests/${O}`);y(A)};return o.jsxs("div",{children:[o.jsx($a,{title:"Requests",description:`${l} matching · live updates`}),o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Ua,{value:f.success,onValueChange:O=>{u(0),p({...f,success:O})},children:[o.jsx(Sa,{className:"w-36",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"All"}),o.jsx(Rt,{value:"true",children:"Success"}),o.jsx(Rt,{value:"false",children:"Failed"})]})]}),o.jsxs(Ua,{value:f.protocol,onValueChange:O=>{u(0),p({...f,protocol:O})},children:[o.jsx(Sa,{className:"w-32",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"Any protocol"}),o.jsx(Rt,{value:"openai",children:"OpenAI"}),o.jsx(Rt,{value:"anthropic",children:"Anthropic"})]})]}),o.jsxs(Ua,{value:f.streaming,onValueChange:O=>{u(0),p({...f,streaming:O})},children:[o.jsx(Sa,{className:"w-32",children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"all",children:"Any"}),o.jsx(Rt,{value:"true",children:"Streaming"}),o.jsx(Rt,{value:"false",children:"Non-stream"})]})]}),o.jsx(Ae,{className:"max-w-xs",placeholder:"Model contains…",value:f.model,onChange:O=>{u(0),p({...f,model:O.target.value})}}),b>0&&o.jsxs(me,{size:"sm",variant:"secondary",onClick:()=>{w(0),T()},children:[b," new request",b>1?"s":""," — refresh"]})]}),o.jsx(rt,{className:"mt-3 text-base",children:"Results"})]}),o.jsxs(lt,{children:[o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Time"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Requested"}),o.jsx(ye,{children:"Final"}),o.jsx(ye,{children:"Tokens"}),o.jsx(ye,{children:"Latency"}),o.jsx(ye,{children:"Attempts"}),o.jsx(ye,{children:"Key"}),o.jsx(ye,{children:"IP"}),o.jsx(ye,{})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:10,className:"text-center text-muted-foreground",children:"No requests yet."})}),n.map(O=>o.jsxs(We,{className:"cursor-pointer",onClick:()=>D(O.id),children:[o.jsx(pe,{className:"text-xs",children:Lm(O.createdAt)}),o.jsx(pe,{children:O.success?o.jsx(Qe,{variant:"success",children:O.httpStatus}):o.jsx(Qe,{variant:"destructive",children:O.httpStatus})}),o.jsx(pe,{className:"font-mono text-xs",children:O.requestedModel}),o.jsx(pe,{className:"font-mono text-xs text-muted-foreground",children:O.finalModelPublicId??"—"}),o.jsxs(pe,{className:"text-xs",children:[Kt(O.inputTokens+O.outputTokens)," ",O.cacheReadTokens?o.jsxs("span",{className:"text-amber-600",children:["(+",O.cacheReadTokens," cache)"]}):null]}),o.jsxs(pe,{className:"text-xs",children:[Ol(O.totalLatencyMs),O.ttftMs?o.jsxs("span",{className:"text-muted-foreground",children:[" · ttft ",O.ttftMs,"ms"]}):null]}),o.jsxs(pe,{className:"text-xs",children:[O.attemptsCount,O.gatewayCacheHit?o.jsx(Qe,{variant:"secondary",className:"ml-1",children:"cache"}):null]}),o.jsx(pe,{className:"text-xs",children:O.apiKeyName??"—"}),o.jsx(pe,{className:"text-xs",children:O.clientIp}),o.jsx(pe,{className:"text-right",children:o.jsx(me,{size:"sm",variant:"ghost",children:"View"})})]},O.id))]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("span",{className:"text-xs text-muted-foreground",children:["Showing ",c+1,"–",Math.min(c+E,l)," of ",l]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(me,{size:"sm",variant:"outline",disabled:c===0,onClick:()=>u(Math.max(0,c-E)),children:"Prev"}),o.jsx(me,{size:"sm",variant:"outline",disabled:c+E>=l,onClick:()=>u(c+E),children:"Next"})]})]})]})]}),o.jsx(Mn,{open:!!g,onOpenChange:O=>{O||(v(null),y(null))},children:o.jsxs(vn,{className:"max-w-3xl",children:[o.jsx(xn,{children:o.jsxs(yn,{children:["Request ",tN(g,16)]})}),x?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Requested model"}),o.jsx("span",{className:"font-mono text-xs",children:x.request.requestedModel})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Upstream model"}),o.jsx("span",{className:"font-mono text-xs",children:x.request.finalModelUpstreamId??"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Provider"}),x.request.providerId?o.jsx(ra,{className:"text-primary underline",to:`/providers?providerId=${encodeURIComponent(x.request.providerId)}`,children:x.request.providerName??x.request.providerSlug??x.request.providerId}):"—"]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Route"}),x.request.resolvedTargetId?o.jsx(ra,{className:"text-primary underline",to:x.request.resolvedTargetKind==="combo"?"/combos":"/models",children:x.request.resolvedTargetKind??"target"}):"—"]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Status"}),x.request.success?o.jsx(Qe,{variant:"success",children:x.request.httpStatus}):o.jsx(Qe,{variant:"destructive",children:x.request.httpStatus})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Latency"}),Ol(x.request.totalLatencyMs)]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Tokens"}),"in ",Kt(x.request.inputTokens)," · out ",Kt(x.request.outputTokens)," · cache ",Kt(x.request.cacheReadTokens)]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:"Attempts"}),x.request.attemptsCount]})]}),x.request.errorType&&o.jsxs("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Error"}),o.jsxs("div",{className:"font-mono text-xs",children:[x.request.errorType,": ",x.request.errorMessage]})]}),x.request.fallbackReasons.length>0&&o.jsxs("div",{className:"rounded border border-amber-500/40 bg-amber-500/10 p-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Fallback reasons"}),o.jsx("div",{className:"text-xs",children:x.request.fallbackReasons.join(", ")})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"Safe replay curl"}),o.jsxs(me,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(x.request.reproductionCurl).then(()=>ve.success("Curl copied"))},children:[o.jsx(Fc,{className:"mr-1 h-3.5 w-3.5"})," Copy"]})]}),o.jsx("pre",{className:"max-h-36 overflow-auto whitespace-pre-wrap rounded bg-muted p-2 font-mono text-xs",children:x.request.reproductionCurl}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Replace the placeholder key before running. No stored secret is included."})]}),x.request.requestPayload&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Request content"}),o.jsx("pre",{className:"max-h-60 overflow-auto rounded bg-muted p-2 font-mono text-xs whitespace-pre-wrap",children:x.request.requestPayload})]}),x.request.responsePayload&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Response content"}),o.jsx("pre",{className:"max-h-60 overflow-auto rounded bg-muted p-2 font-mono text-xs whitespace-pre-wrap",children:x.request.responsePayload})]}),x.attempts.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Attempts"}),o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"#"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Latency"}),o.jsx(ye,{children:"Reason"})]})}),o.jsx(da,{children:x.attempts.map(O=>o.jsxs(We,{children:[o.jsx(pe,{children:O.attemptNumber}),o.jsx(pe,{children:O.providerName}),o.jsxs(pe,{children:[o.jsx("div",{className:"font-mono text-xs",children:O.modelPublicId}),o.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["upstream: ",O.upstreamModelId]})]}),o.jsx(pe,{children:O.success?o.jsx(Qe,{variant:"success",children:String(O.statusCode??"OK")}):o.jsx(Qe,{variant:"destructive",children:String(O.statusCode??"err")})}),o.jsx(pe,{className:"text-xs",children:Ol(O.latencyMs)}),o.jsx(pe,{className:"text-xs",children:O.failureReason??O.selectionReason})]},O.id))})]})]})]}):o.jsx("div",{className:"text-muted-foreground",children:"Loading…"})]})})]})}var Rk=Object.defineProperty,Zs=(n,a)=>Rk(n,"name",{value:a,configurable:!0}),_p="Tabs",[Nk,Z4]=kn(_p,[Lu]),ES=Lu(),[Tk,kp]=Nk(_p),Mk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,onValueChange:u,defaultValue:f,orientation:p="horizontal",dir:g,activationMode:v="automatic",...x}=a,y=di(g),[b,w]=yr({prop:c,onChange:u,defaultProp:f??"",caller:_p});return o.jsx(Tk,{scope:s,baseId:La(),value:b,onValueChange:w,orientation:p,dir:y,activationMode:v,children:o.jsx(Ve.div,{dir:y,"data-orientation":p,...x,ref:l})})},"Tabs")),Ak="TabsList",Dk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,loop:c=!0,...u}=a,f=kp(Ak,s),p=ES(s);return o.jsx(G1,{asChild:!0,...p,orientation:f.orientation,dir:f.dir,loop:c,children:o.jsx(Ve.div,{role:"tablist","aria-orientation":f.orientation,...u,ref:l})})},"TabsList")),Ok="TabsTrigger",_k=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,disabled:u=!1,...f}=a,p=kp(Ok,s),g=ES(s),v=zp(p.baseId,c),x=Lp(p.baseId,c),y=c===p.value;return o.jsx(K1,{asChild:!0,...g,focusable:!u,active:y,children:o.jsx(Ve.button,{type:"button",role:"tab","aria-selected":y,"aria-controls":x,"data-state":y?"active":"inactive","data-disabled":u?"":void 0,disabled:u,id:v,...f,ref:l,onMouseDown:Ne(a.onMouseDown,b=>{!u&&b.button===0&&b.ctrlKey===!1?p.onValueChange(c):b.preventDefault()}),onKeyDown:Ne(a.onKeyDown,b=>{u||b.target!==b.currentTarget||[" ","Enter"].includes(b.key)&&p.onValueChange(c)}),onFocus:Ne(a.onFocus,()=>{const b=p.activationMode!=="manual";!y&&!u&&b&&p.onValueChange(c)})})})},"TabsTrigger")),kk="TabsContent",zk=m.forwardRef(Zs(function(a,l){const{__scopeTabs:s,value:c,forceMount:u,children:f,...p}=a,g=kp(kk,s),v=zp(g.baseId,c),x=Lp(g.baseId,c),y=c===g.value,b=m.useRef(y);return m.useEffect(()=>{const w=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(w)},[]),o.jsx(Cr,{present:u||y,children:({present:w})=>o.jsx(Ve.div,{"data-state":y?"active":"inactive","data-orientation":g.orientation,role:"tabpanel","aria-labelledby":v,hidden:!w,id:x,tabIndex:0,...p,ref:l,style:{...a.style,animationDuration:b.current?"0s":void 0},children:w&&f})})},"TabsContent"));function zp(n,a){return`${n}-trigger-${a}`}Zs(zp,"makeTriggerId");function Lp(n,a){return`${n}-content-${a}`}Zs(Lp,"makeContentId");var Lk=Mk,RS=Dk,NS=_k,TS=zk;const MS=Lk,Up=m.forwardRef(({className:n,...a},l)=>o.jsx(RS,{ref:l,className:Ee("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",n),...a}));Up.displayName=RS.displayName;const mr=m.forwardRef(({className:n,...a},l)=>o.jsx(NS,{ref:l,className:Ee("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",n),...a}));mr.displayName=NS.displayName;const Os=m.forwardRef(({className:n,...a},l)=>o.jsx(TS,{ref:l,className:Ee("mt-2 ring-offset-background focus-visible:outline-none",n),...a}));Os.displayName=TS.displayName;const Uk=3e3,Bk=1600,Hk=10,Ik=3,Pk=12,qk=10*6e4,Vk={cacheReadTokens:0,promptTokens:0,gatewayCacheHits:0,fallbacks:0};function AS(n,a,l){return l==="anthropic"?n+a:n}function $k(n){return n.promptTokens>0?n.cacheReadTokens/n.promptTokens:0}function Yk(n,a){return a>0?n.fallbacks/a:0}function Gk(n,a){return a>0?n.gatewayCacheHits/a:0}function Kk(n,a,l){const s=n.totalRequests+1,c=n.successfulRequests+(l.success?1:0),u={cacheReadTokens:a.cacheReadTokens+l.cacheReadTokens,promptTokens:a.promptTokens+AS(l.inputTokens,l.cacheReadTokens,l.providerType),gatewayCacheHits:a.gatewayCacheHits+(l.gatewayCacheHit?1:0),fallbacks:a.fallbacks+(l.attemptsCount>1?1:0)};return{...n,...u,totalRequests:s,successfulRequests:c,failedRequests:n.failedRequests+(l.success?0:1),successRate:c/s,inputTokens:n.inputTokens+l.inputTokens,outputTokens:n.outputTokens+l.outputTokens,totalTokens:n.totalTokens+l.inputTokens+l.outputTokens,cacheHitRate:$k(u),gatewayCacheHitRate:Gk(u,s),fallbackRate:Yk(u,s),averageLatencyMs:(n.averageLatencyMs*n.totalRequests+l.totalLatencyMs)/s}}function Xk(n){const[a,l]=m.useState(null),[s,c]=m.useState(null),[u,f]=m.useState([]),[p,g]=m.useState([]),[v,x]=m.useState([]),[y,b]=m.useState([]),[w,E]=m.useState(!0),[j,C]=m.useState(null),N=m.useRef([]),M=m.useRef(null),T=m.useRef(Vk),D=m.useRef(new Set),O=m.useRef(Date.now()),A=m.useRef(0),U=m.useRef([]),k=m.useRef([]);return m.useEffect(()=>{let $=!1;return E(!0),C(null),D.current=new Set,O.current=Date.now(),Se.get(`/api/admin/stats?preset=${n}`).then(X=>{if(!$){l(X),c(X.summary),M.current=X.summary,T.current={cacheReadTokens:X.summary.cacheReadTokens,promptTokens:X.summary.cacheHitRate>0?Math.round(X.summary.cacheReadTokens/X.summary.cacheHitRate):X.summary.inputTokens,gatewayCacheHits:Math.round(X.summary.gatewayCacheHitRate*X.summary.totalRequests),fallbacks:Math.round(X.summary.fallbackRate*X.summary.totalRequests)},f(X.recent),g(X.providers),N.current=X.providers;for(const te of X.recent)D.current.add(te.id);E(!1)}}).catch(X=>{$||(C(X.message),E(!1))}),()=>{$=!0}},[n]),m.useEffect(()=>{let $=!1,X=null;const te=new Set,G=()=>{$||(X=new EventSource(`/api/admin/requests/stream?since=${O.current}`),X.addEventListener("request",ce=>{if(!$)try{const se=JSON.parse(ce.data),_=new Date(se.createdAt).getTime();if(Number.isFinite(_)&&(O.current=Math.max(O.current,_)),D.current.has(se.id))return;D.current.add(se.id);const H={cacheReadTokens:T.current.cacheReadTokens+se.cacheReadTokens,promptTokens:T.current.promptTokens+AS(se.inputTokens,se.cacheReadTokens,se.providerType),gatewayCacheHits:T.current.gatewayCacheHits+(se.gatewayCacheHit?1:0),fallbacks:T.current.fallbacks+(se.attemptsCount>1?1:0)};if(T.current=H,M.current&&c(Kk(M.current,H,se)),f(Q=>Q.some(J=>J.id===se.id)?Q:[se,...Q].slice(0,Hk)),se.providerId){N.current=N.current.map(z=>z.id===se.providerId?{...z,requests:z.requests+1,errorRate:z.requests+1?(z.errorRate*z.requests+(se.success?0:1))/(z.requests+1):0}:z),g(N.current);const Q=`p${++A.current}`,J={id:Q,providerId:se.providerId,success:se.success};U.current=[...U.current.slice(-(Ik*4)),J],x(U.current);const ee=setTimeout(()=>{U.current=U.current.filter(z=>z.id!==Q),x(U.current)},Bk);te.add(ee)}k.current.some(Q=>Q.id===se.id)&&(k.current=k.current.filter(Q=>Q.id!==se.id),b(k.current))}catch{}}),X.addEventListener("request_started",ce=>{if(!$)try{const se=JSON.parse(ce.data);if(!se.providerId||se.providerId==="")return;k.current=[...k.current.filter(_=>_.id!==se.requestId).slice(-(Pk-1)),{id:se.requestId,providerId:se.providerId,startedAt:Date.now(),ttftMs:se.ttftMs??0}],b(k.current)}catch{}}),X.onerror=()=>{X==null||X.close(),X=null,$||te.add(setTimeout(G,Uk))})};G();const ie=setInterval(()=>{const ce=Date.now()-qk;k.current.some(se=>se.startedAt<ce)&&(k.current=k.current.filter(se=>se.startedAt>=ce),b(k.current))},3e4);return()=>{$=!0,X==null||X.close();for(const ce of te)clearTimeout(ce);te.clear(),clearInterval(ie)}},[]),m.useEffect(()=>{const $=setInterval(()=>{Se.get("/api/admin/providers").then(X=>{const te=new Map(X.providers.map(G=>[G.id,G]));N.current=N.current.map(G=>{const ie=te.get(G.id);return ie?{...G,health:ie.health,enabled:ie.enabled}:G}),g(N.current)}).catch(()=>{})},3e4);return()=>clearInterval($)},[]),{snapshot:a,live:s??(a==null?void 0:a.summary)??Fk,recent:u,providers:p,pulses:v,activeRoutes:y,loading:w,error:j}}const Fk={totalRequests:0,successfulRequests:0,failedRequests:0,successRate:0,inputTokens:0,outputTokens:0,totalTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0,averageLatencyMs:0,p95LatencyMs:0,averageTtftMs:null,p95TtftMs:null,cacheHitRate:0,gatewayCacheHitRate:0,fallbackRate:0};function DS({data:n,className:a,strokeClass:l="stroke-primary",fillClass:s}){if(n.length===0)return o.jsx("svg",{className:Ee("h-6 w-20",a),viewBox:"0 0 80 24"});const f=Math.max(...n),p=Math.min(...n),g=f-p||1,x=n.map((y,b)=>{const w=b/(n.length-1)*78+1,E=22-(y-p)/g*20;return`${w.toFixed(1)},${E.toFixed(1)}`}).join(" ");return o.jsxs("svg",{className:Ee("h-6 w-20",a),viewBox:"0 0 80 24",preserveAspectRatio:"none",children:[s&&o.jsx("polygon",{points:`1,23 ${x} 79,23`,className:s}),o.jsx("polyline",{points:x,fill:"none",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:l})]})}function Qk(n,a,l){const s=performance.now();let c=0;const u=f=>{const p=Math.min((f-s)/a,1),g=Math.round(n*p);g!==c&&(c=g,l(g)),p<1&&requestAnimationFrame(u)};requestAnimationFrame(u)}function Zk({delta:n,inverse:a}){if(Math.abs(n)<.005)return null;const l=n>0,s=a?!l:l,c=`${(Math.abs(n)*100).toFixed(1)}%`;return o.jsxs("span",{className:Ee("ml-1.5 inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",s?"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300":"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"),children:[o.jsx("span",{className:"mr-0.5",children:l?"▲":"▼"}),c]})}function el({icon:n,label:a,value:l,format:s="number",delta:c,deltaInverse:u,sparkData:f,sparkStroke:p}){const[g,v]=m.useState(0),x=m.useRef(0);m.useEffect(()=>{const b=x.current,w=l;x.current=l,b!==w&&Qk(Math.abs(w-b),600,E=>v(b+(w>b?E:-E)))},[l]);const y=s==="percent"?Eu(g):s==="latency"?Ol(g):Kt(Math.round(g));return o.jsxs(nt,{children:[o.jsxs(at,{className:"flex flex-row items-center justify-between pb-1",children:[o.jsxs(rt,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[o.jsx(n,{className:"h-4 w-4"}),a]}),c!==void 0&&o.jsx(Zk,{delta:c,inverse:u})]}),o.jsxs(lt,{className:"flex items-end justify-between",children:[o.jsx("span",{className:"text-2xl font-semibold tabular-nums",children:y}),f&&f.length>1&&o.jsx(DS,{data:f,strokeClass:p??"stroke-primary",fillClass:"fill-primary/10"})]})]})}const OS=1e3,Gb=380,Vc=60,tl=OS/2,nl=720,Bh=62,Jk=260;function Wk(n){return n==="healthy"?"fill-emerald-400":n==="degraded"?"fill-amber-400":"fill-red-400"}function $c(n,a,l,s){const c=n+(l-n)*.45,u=n+(l-n)*.55;return`M${n},${a} C${c},${a} ${u},${s} ${l},${s}`}function e4({liveRequests:n,successRate:a,providers:l,pulses:s,activeRoutes:c}){const u=Gb/2,f=u,p=Math.max(1,l.reduce((x,y)=>x+y.requests,0)),g=new Set(c.map(x=>x.providerId)),v=g.size>0;return o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(rt,{className:"text-base",children:"Real-time Request Routing"}),o.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," healthy"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-400"})," degraded"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-red-400"})," down"]})]})]})}),o.jsx(lt,{className:"pt-0",children:o.jsx("div",{className:"relative w-full",children:o.jsxs("svg",{viewBox:`0 0 ${OS} ${Gb}`,className:"w-full h-auto",preserveAspectRatio:"xMidYMid meet",children:[o.jsx("defs",{children:o.jsxs("filter",{id:"glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[o.jsx("feGaussianBlur",{stdDeviation:"3",result:"blur"}),o.jsxs("feMerge",{children:[o.jsx("feMergeNode",{in:"blur"}),o.jsx("feMergeNode",{in:"SourceGraphic"})]})]})}),l.map(x=>{const b=60+l.indexOf(x)*Bh,w=x.requests/p,E=Math.max(1.5,Math.min(6,2+w*8)),j=g.has(x.id);return o.jsxs("g",{children:[j&&o.jsx("path",{d:$c(tl,u,nl-20,b),fill:"none",stroke:"hsl(var(--primary) / 0.25)",strokeWidth:E+6,strokeLinecap:"round"}),o.jsx("path",{d:$c(tl,u,nl-20,b),fill:"none",stroke:j?"hsl(var(--primary))":"hsl(var(--border))",strokeWidth:j?E+1:E,strokeLinecap:"round",opacity:j?.95:.6,className:j?"route-active":void 0})]},x.id)}),o.jsx("path",{d:$c(Vc+30,f,tl-30,u),fill:"none",stroke:v?"hsl(var(--primary))":"hsl(var(--border))",strokeWidth:3,strokeLinecap:"round",strokeDasharray:"6 3",opacity:v?.9:.5,className:v?"route-active":void 0}),s.map(x=>{const y=l.findIndex(j=>j.id===x.providerId);if(y===-1)return null;const b=60+y*Bh,w=$c(tl,u,nl-20,b),E=x.success?"var(--primary)":"#f87171";return o.jsxs("g",{filter:"url(#glow)",children:[o.jsx("circle",{r:5,fill:E,opacity:.9,children:o.jsx("animateMotion",{dur:"1.4s",fill:"freeze",path:w})}),o.jsx("circle",{r:9,fill:E,opacity:.25,children:o.jsx("animateMotion",{dur:"1.4s",fill:"freeze",path:w})})]},x.id)}),o.jsx("circle",{cx:Vc,cy:f,r:28,fill:"hsl(var(--card))",stroke:"hsl(var(--border))",strokeWidth:1.5}),o.jsx("text",{x:Vc,y:f-4,textAnchor:"middle",className:"fill-foreground",fontSize:12,fontWeight:600,children:Kb(n)}),o.jsx("text",{x:Vc,y:f+10,textAnchor:"middle",className:"fill-muted-foreground",fontSize:9,children:"requests"}),o.jsx("circle",{cx:tl,cy:u,r:36,fill:"hsl(var(--card))",stroke:"var(--primary)",strokeWidth:2}),o.jsx("image",{x:tl-12,y:u-16,width:24,height:24,href:"/logo.png"}),o.jsx("text",{x:tl,y:u+28,textAnchor:"middle",className:"fill-muted-foreground",fontSize:9,children:"AI Gateway"}),o.jsxs("text",{x:tl,y:u+38,textAnchor:"middle",className:"fill-emerald-500",fontSize:10,fontWeight:600,children:[(a*100).toFixed(1),"%"]}),l.map((x,y)=>{const b=60+y*Bh,w=x.requests/p,E=!x.enabled||x.requests===0;return o.jsxs("g",{opacity:E?.4:1,children:[o.jsx("rect",{x:nl-20,y:b-14,width:Jk,height:50,rx:8,fill:"hsl(var(--card))",stroke:"hsl(var(--border))",strokeWidth:1}),o.jsx("circle",{cx:nl-6,cy:b+10,r:4,className:Wk(x.health)}),o.jsx("text",{x:nl+6,y:b-2,className:"fill-foreground",fontSize:12,fontWeight:500,children:x.name}),o.jsxs("text",{x:nl+6,y:b+12,className:"fill-muted-foreground",fontSize:10,children:[x.modelCount," model",x.modelCount!==1?"s":""," · ",Kb(x.requests)," req"]}),o.jsxs("text",{x:nl+6,y:b+25,className:"fill-muted-foreground",fontSize:10,children:[(w*100).toFixed(1),"% traffic · ",x.avgLatencyMs<1e3?`${Math.round(x.avgLatencyMs)}ms`:`${(x.avgLatencyMs/1e3).toFixed(1)}s`," avg",x.errorRate>0&&o.jsxs("tspan",{className:"fill-red-500",children:[" · ",(x.errorRate*100).toFixed(0),"% err"]})]})]},x.id)})]})})})]})}function Kb(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}K`:String(n)}function t4({rows:n}){return o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Recent Requests"})}),o.jsx(lt,{children:n.length===0?o.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No requests yet — traffic will appear here live."}):o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Provider"}),o.jsx(ye,{children:"Tokens"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Time"})]})}),o.jsx(da,{children:n.map(a=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:a.requestedModel}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:a.providerName??"—"}),o.jsxs(pe,{className:"text-xs",children:[o.jsxs("span",{className:"font-mono",children:["in ",Kt(a.inputTokens)," · out ",Kt(a.outputTokens)]}),a.cacheReadTokens>0&&o.jsxs("span",{className:"ml-1 text-amber-600",children:["(+",Kt(a.cacheReadTokens)," cache)"]})]}),o.jsx(pe,{children:o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:a.success?"h-2 w-2 rounded-full bg-emerald-400":"h-2 w-2 rounded-full bg-red-400"}),o.jsx("span",{className:"text-xs",children:a.success?a.httpStatus:`${a.httpStatus} err`})]})}),o.jsx(pe,{className:"text-xs text-muted-foreground",children:nN(a.createdAt)})]},a.id))})]})})]})}const gm=34,Xb=2*Math.PI*gm;function n4(n){return n>=.95?{stroke:"#4ade80",text:"text-emerald-500"}:n>=.8?{stroke:"#fbbf24",text:"text-amber-500"}:{stroke:"#f87171",text:"text-red-500"}}function a4({successRate:n,averageLatencyMs:a,latencySpark:l}){const{stroke:s,text:c}=n4(n),u=Math.min(1,Math.max(0,n)),f=Xb*(1-u);return o.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Success Rate"})}),o.jsxs(lt,{className:"flex items-center gap-4",children:[o.jsxs("div",{className:"relative h-20 w-20",children:[o.jsxs("svg",{viewBox:"0 0 80 80",className:"h-20 w-20 -rotate-90",children:[o.jsx("circle",{cx:"40",cy:"40",r:gm,fill:"none",stroke:"hsl(var(--border))",strokeWidth:7}),o.jsx("circle",{cx:"40",cy:"40",r:gm,fill:"none",stroke:s,strokeWidth:7,strokeLinecap:"round",strokeDasharray:Xb,strokeDashoffset:f,style:{transition:"stroke-dashoffset 0.6s ease, stroke 0.4s ease"}})]}),o.jsx("span",{className:`absolute inset-0 flex items-center justify-center text-sm font-semibold tabular-nums ${c}`,children:Eu(n)})]}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Share of requests that completed successfully over the selected window. Updated in real time."})]})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Average Latency"})}),o.jsxs(lt,{className:"flex items-end justify-between",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:Ol(a)}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Live average across the selected window"})]}),o.jsx(DS,{data:l,strokeClass:"stroke-amber-500",fillClass:"fill-amber-500/10",className:"h-10 w-28"})]})]})]})}function r4(){const[n,a]=m.useState("7d"),{snapshot:l,live:s,recent:c,providers:u,pulses:f,activeRoutes:p,loading:g,error:v}=Xk(n);if(g)return o.jsx("div",{className:"text-muted-foreground",children:"Loading…"});if(v||!l)return o.jsxs("div",{className:"text-destructive",children:["Failed to load statistics: ",v??"unknown error"]});const x=s,y=l.previous,b=l.series;function w(C,N){return N>0?(C-N)/N:void 0}const E=b.map(C=>C.requests),j=b.map(C=>C.avgLatency);return o.jsxs("div",{children:[o.jsx($a,{title:"Statistics",description:"Real-time monitoring dashboard",actions:o.jsx(MS,{value:n,onValueChange:C=>void a(C),children:o.jsxs(Up,{children:[o.jsx(mr,{value:"today",children:"Today"}),o.jsx(mr,{value:"7d",children:"7 days"}),o.jsx(mr,{value:"30d",children:"30 days"})]})})}),o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsx(el,{icon:km,label:"Requests",value:x.totalRequests,delta:w(x.totalRequests,y.totalRequests),sparkData:E}),o.jsx(el,{icon:ci,label:"Success rate",format:"percent",value:x.successRate,delta:w(x.successRate,y.successRate),sparkData:E,sparkStroke:"stroke-emerald-500"}),o.jsx(el,{icon:rR,label:"Total tokens",value:x.totalTokens,delta:w(x.totalTokens,y.totalTokens),sparkData:b.map(C=>C.inputTokens+C.outputTokens)}),o.jsx(el,{icon:lR,label:"Cache hit rate",format:"percent",value:x.cacheHitRate,delta:w(x.cacheHitRate,y.cacheHitRate),sparkData:b.map(C=>C.cacheRead)}),o.jsx(el,{icon:tR,label:"Avg latency",format:"latency",value:x.averageLatencyMs,delta:w(x.averageLatencyMs,y.averageLatencyMs),deltaInverse:!0,sparkData:j,sparkStroke:"stroke-amber-500"}),o.jsx(el,{icon:R0,label:"p95 latency",format:"latency",value:x.p95LatencyMs}),o.jsx(el,{icon:bR,label:"Avg TTFT",format:"latency",value:x.averageTtftMs??0}),o.jsx(el,{icon:mR,label:"Fallback rate",format:"percent",value:x.fallbackRate,delta:w(x.fallbackRate,y.fallbackRate),deltaInverse:!0})]}),o.jsx("div",{className:"mt-6",children:o.jsx(e4,{liveRequests:x.totalRequests,successRate:x.successRate,providers:u,pulses:f,activeRoutes:p})}),o.jsxs("div",{className:"mt-6 grid gap-4 lg:grid-cols-3",children:[o.jsx("div",{className:"lg:col-span-2",children:o.jsx(t4,{rows:c})}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Top Models"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Model"}),o.jsx(ye,{children:"Req"}),o.jsx(ye,{children:"Errors"}),o.jsx(ye,{children:"Tokens"})]})}),o.jsxs(da,{children:[l.topModels.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:4,className:"text-muted-foreground text-center",children:"No data"})}),l.topModels.map(C=>o.jsxs(We,{children:[o.jsx(pe,{className:"font-mono text-xs",children:C.publicId}),o.jsx(pe,{className:"text-xs",children:Kt(C.requests)}),o.jsx(pe,{className:"text-xs",children:o.jsx("span",{className:C.errorRate>.1?"text-destructive":"text-muted-foreground",children:Eu(C.errorRate)})}),o.jsx(pe,{className:"text-xs",children:Kt(C.totalTokens)})]},C.publicId))]})]})})]}),o.jsxs(nt,{children:[o.jsx(at,{className:"pb-2",children:o.jsx(rt,{className:"text-base",children:"Top API Keys"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Key"}),o.jsx(ye,{children:"Requests"}),o.jsx(ye,{children:"Tokens"})]})}),o.jsxs(da,{children:[l.topApiKeys.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:3,className:"text-muted-foreground text-center",children:"No data"})}),l.topApiKeys.map((C,N)=>o.jsxs(We,{children:[o.jsx(pe,{className:"text-xs",children:C.name}),o.jsx(pe,{className:"text-xs",children:Kt(C.requests)}),o.jsx(pe,{className:"text-xs",children:Kt(C.totalTokens)})]},N))]})]})})]})]})]}),o.jsx("div",{className:"mt-6",children:o.jsx(a4,{successRate:x.successRate,averageLatencyMs:x.averageLatencyMs,latencySpark:j})})]})}function l4(){const[n,a]=m.useState([]),[l,s]=m.useState(0);return m.useEffect(()=>{Se.get("/api/admin/audit?limit=200").then(c=>{a(c.rows),s(c.total)})},[]),o.jsxs("div",{children:[o.jsx($a,{title:"Audit Logs",description:`${l} entries · immutable`}),o.jsxs(nt,{children:[o.jsx(at,{children:o.jsx(rt,{className:"text-base",children:"All entries"})}),o.jsx(lt,{children:o.jsxs(ca,{children:[o.jsx(ua,{children:o.jsxs(We,{children:[o.jsx(ye,{children:"Time"}),o.jsx(ye,{children:"Action"}),o.jsx(ye,{children:"Status"}),o.jsx(ye,{children:"Target"}),o.jsx(ye,{children:"IP"}),o.jsx(ye,{children:"Actor"})]})}),o.jsxs(da,{children:[n.length===0&&o.jsx(We,{children:o.jsx(pe,{colSpan:6,className:"text-center text-muted-foreground",children:"No audit events yet."})}),n.map(c=>o.jsxs(We,{children:[o.jsx(pe,{className:"text-xs",children:Lm(c.createdAt)}),o.jsx(pe,{className:"font-mono text-xs",children:c.action}),o.jsx(pe,{children:c.success?o.jsx(Qe,{variant:"success",children:"ok"}):o.jsx(Qe,{variant:"destructive",children:"fail"})}),o.jsx(pe,{className:"text-xs",children:c.targetName??c.targetId??"—"}),o.jsx(pe,{className:"text-xs",children:c.ip}),o.jsx(pe,{className:"text-xs",children:c.actor})]},c.id))]})]})})]})]})}const vm={enabled:!0,sound:!0};let ri=vm,xm=!1,Yc=null;const ym=new Set;function _S(){for(const n of ym)n()}function kS(n=!1){return xm&&!n?Promise.resolve():(!n&&Yc||(Yc=(async()=>{try{const a=await Se.get("/api/admin/settings");ri={enabled:a.settings.notificationsEnabled??vm.enabled,sound:a.settings.notificationSoundEnabled??vm.sound},xm=!0,_S()}catch{}})()),Yc)}async function Fb(n){const a={};n.enabled!==void 0&&(a.notificationsEnabled=n.enabled),n.sound!==void 0&&(a.notificationSoundEnabled=n.sound),await Se.patch("/api/admin/settings",a),ri={...ri,...n},xm=!0,_S()}function s4(n){return ym.add(n),()=>ym.delete(n)}function zS(){return m.useSyncExternalStore(s4,()=>ri,()=>ri)}const bm=m.forwardRef(({className:n,...a},l)=>o.jsx("textarea",{ref:l,className:Ee("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",n),...a}));bm.displayName="Textarea";function o4(){const[n]=BE(),[a,l]=m.useState(null),[s,c]=m.useState(null),[u,f]=m.useState({current:"",next:""}),[p,g]=m.useState(""),[v,x]=m.useState(""),[y,b]=m.useState(null),[w,E]=m.useState(!1),[j,C]=m.useState("idle"),[N,M]=m.useState(null),T=async(le=!1)=>{C("checking"),M(null);try{const Le=await Se.get(`/api/admin/update/check${le?"?force=1":""}`);b(Le),C("idle")}catch(Le){M(Le.message),C("error")}},D=async()=>{E(!0),C("installing"),M(null);try{const le=await Se.post("/api/admin/update/run");C("restarting"),ve.success(le.message||"Update started — the gateway will restart shortly.");const Le=setInterval(()=>{fetch("/health").then(Ie=>{Ie.ok&&(clearInterval(Le),window.location.reload())}).catch(()=>{})},3e3);setTimeout(()=>clearInterval(Le),12e4)}catch(le){ve.error(le.message),M(le.message),C("error")}finally{E(!1)}},[O,A]=m.useState("disabled"),[U,k]=m.useState(""),[$,X]=m.useState(""),[te,G]=m.useState(""),[ie,ce]=m.useState([]),[se,_]=m.useState(""),[H,Q]=m.useState(""),[J,ee]=m.useState(!1),[z,I]=m.useState(null),[F,re]=m.useState(""),[he,ge]=m.useState(""),[q,oe]=m.useState(""),de=async()=>{const le=await Se.get("/api/admin/settings");l(le.settings),g(le.settings.adminIpAllow??""),x(le.settings.adminIpBlock??"");const Le=await Se.get("/api/admin/settings/system");c(Le);try{const Ie=await Se.get("/api/admin/me");A(Ie.totpEnabled?"enabled":"disabled")}catch{}};if(m.useEffect(()=>{kS(!0)},[]),m.useEffect(()=>{de(),T(!0)},[]),!a)return o.jsx("div",{className:"text-muted-foreground",children:"Loading…"});const fe=async le=>{try{await Se.patch("/api/admin/settings",le),ve.success("Saved"),de()}catch(Le){ve.error(Le.message)}},Te=async()=>{try{const le=await Se.post("/api/admin/account/totp/begin");k(le.secret),X(le.qr),A("setup"),ve.info("Scan the QR code with your authenticator app")}catch(le){ve.error(le.message)}},je=async()=>{if(!te||te.length!==6){ve.error("Enter a 6-digit code");return}try{const le=await Se.post("/api/admin/account/totp/verify",{code:te});ce(le.recoveryCodes),A("showingRecovery"),ve.success("TOTP enabled successfully")}catch(le){ve.error(le.message)}},De=async()=>{if(!se){ve.error("Enter your password");return}if(!H){ve.error("Enter a TOTP code or recovery code");return}try{await Se.post("/api/admin/account/totp/disable",{password:se,totp:H}),A("disabled"),_(""),Q(""),ve.success("TOTP disabled"),de()}catch(le){ve.error(le.message)}},Fe=async()=>{ee(!0);try{const le=await Se.post("/api/admin/account/totp/recovery/regenerate",{password:se,totp:H});ce(le.recoveryCodes),A("showingRecovery"),ve.success("Recovery codes regenerated")}catch(le){ve.error(le.message)}ee(!1)},et=n.get("tab")||"logging";return o.jsxs("div",{children:[o.jsx($a,{title:"Settings",description:"Logging, security, backup, and system info"}),o.jsxs(MS,{defaultValue:et,children:[o.jsxs(Up,{children:[o.jsx(mr,{value:"logging",children:"Logging"}),o.jsx(mr,{value:"access",children:"Access Control"}),o.jsx(mr,{value:"security",children:"Security"}),o.jsx(mr,{value:"backup",children:"Backup"}),o.jsx(mr,{value:"system",children:"System"})]}),o.jsx(Os,{value:"logging",children:o.jsxs(nt,{children:[o.jsx(at,{children:o.jsx(rt,{className:"text-base",children:"Logging policy"})}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Request-content logging"}),o.jsxs(Ua,{value:a.contentLogMode,onValueChange:le=>fe({contentLogMode:le}),children:[o.jsx(Sa,{children:o.jsx(Ba,{})}),o.jsxs(ja,{children:[o.jsx(Rt,{value:"off",children:"Off"}),o.jsx(Rt,{value:"metadata",children:"Metadata only (default)"}),o.jsx(Rt,{value:"prompt",children:"Prompt (sanitized)"}),o.jsx(Rt,{value:"prompt_and_response",children:"Prompt + response (sanitized)"})]})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Retention (days)"}),o.jsx(Ae,{type:"number",min:1,max:3650,value:a.retentionDays,onChange:le=>fe({retentionDays:Number(le.target.value)})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(we,{children:"Database size limit (MB)"}),o.jsx(Ae,{type:"number",min:64,value:a.dbSizeLimitMb,onChange:le=>fe({dbSizeLimitMb:Number(le.target.value)})})]}),o.jsx("div",{className:"flex items-center gap-2 pt-2",children:o.jsx(me,{onClick:async()=>{const le=await Se.post("/api/admin/settings/cleanup");ve.success(`Deleted ${le.deletedRequests} old requests`)},children:"Run cleanup now"})})]})]})}),o.jsx(Os,{value:"access",children:o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"IP access control"}),o.jsx(gn,{children:"Allowlist / Blocklist for this admin website (not model traffic)"})]}),o.jsxs(lt,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(we,{children:"Allow only these IPs"}),o.jsx(bm,{placeholder:`192.168.1.0/24
|
|
349
349
|
10.0.0.1`,value:p,onChange:le=>g(le.target.value)}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Newlines-delimited CIDR ranges (IPv4 only). Leave empty = no allow restrictions. When you save a non-empty list, your current IP is auto-added to prevent lockout."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(we,{children:"Block these IPs"}),o.jsx(bm,{placeholder:"192.168.1.100",value:v,onChange:le=>x(le.target.value)}),o.jsx("p",{className:"text-xs text-muted-foreground",children:'Newlines-delimited CIDR ranges (IPv4 only). Blocked IPs are rejected with "Không có quyền truy cập" before any login page.'})]}),o.jsx(me,{onClick:()=>{const le={};p!==((a==null?void 0:a.adminIpAllow)??"")&&(le.adminIpAllow=p||null),v!==((a==null?void 0:a.adminIpBlock)??"")&&(le.adminIpBlock=v||null),Se.patch("/api/admin/settings",le).then(Le=>{ve.success("Saved"+(Le.addedIp?` — added your IP: ${Le.addedIp}`:"")),de(),g(""),x("")}).catch(Le=>ve.error(Le.message))},children:"Save access control"}),o.jsxs("div",{className:"rounded bg-amber-50 border border-amber-200 p-3 dark:bg-amber-950/20 dark:border-amber-800",children:[o.jsx("p",{className:"text-sm font-medium text-amber-900 dark:text-amber-200",children:"⚠️ If you enable an allow list, you cannot access the gateway unless your IP matches."}),o.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-300",children:"The server automatically adds your current IP when you save — but if you configure it from a different machine, that machine will be locked out immediately."})]})]})]})}),o.jsx(Os,{value:"security",children:o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Security"}),o.jsx(gn,{children:"Change password, 2FA, and trusted proxy configuration"})]}),o.jsxs(lt,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(we,{children:"Trusted proxy hops"}),o.jsx(Ae,{type:"number",min:0,max:8,value:a.trustProxyHops,onChange:le=>fe({trustProxyHops:Number(le.target.value)})}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"0 = never trust X-Forwarded-For (direct exposure). 1+ only when behind a single trusted reverse proxy."})]}),o.jsxs("div",{className:"space-y-2 border-t pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(we,{className:"text-base",children:"TOTP 2FA"}),O==="enabled"?o.jsx("span",{className:"rounded bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900 dark:text-green-200",children:"Enabled"}):null,O==="disabled"?o.jsx("span",{className:"rounded bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground",children:"Disabled"}):null]}),O==="disabled"&&o.jsx(me,{variant:"outline",onClick:Te,children:"Enable TOTP"}),O==="setup"&&o.jsxs("div",{className:"space-y-3 rounded border p-3",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"Scan this QR code with your authenticator app, or enter the secret manually."}),$&&o.jsx("img",{src:$,alt:"TOTP QR code",className:"h-40 w-40"}),o.jsxs("div",{className:"text-xs font-mono text-muted-foreground",children:["Secret: ",U]}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("div",{className:"flex-1",children:[o.jsx(we,{children:"Verify code"}),o.jsx(Ae,{value:te,onChange:le=>G(le.target.value),placeholder:"123456",maxLength:6})]}),o.jsx(me,{disabled:te.length<6,onClick:je,children:"Verify & enable"})]})]}),O==="showingRecovery"&&o.jsxs("div",{className:"space-y-3 rounded border border-amber-500/40 bg-amber-50 p-3 dark:bg-amber-950/20",children:[o.jsx("p",{className:"text-sm font-medium",children:"Recovery codes — save these now!"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Each code can be used once to log in without your TOTP device. They will not be shown again."}),o.jsx("div",{className:"space-y-1",children:ie.map((le,Le)=>o.jsx("div",{className:"font-mono text-xs",children:le},Le))}),o.jsx(me,{onClick:()=>{A("enabled"),ve.success("Recovery codes saved")},children:"I have saved them"})]}),O==="enabled"&&o.jsxs("div",{className:"space-y-3 rounded border p-3",children:[o.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Password"}),o.jsx(Ae,{type:"password",value:se,onChange:le=>_(le.target.value),placeholder:"Current password"})]}),o.jsxs("div",{children:[o.jsx(we,{children:"TOTP code"}),o.jsx(Ae,{value:H,onChange:le=>Q(le.target.value),placeholder:"123456",maxLength:6})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"outline",size:"sm",disabled:J||!se||H.length<6,onClick:Fe,children:"Regenerate recovery codes"}),o.jsx(me,{variant:"destructive",size:"sm",disabled:!se||H.length<6,onClick:De,children:"Disable TOTP"})]})]})]}),o.jsxs("div",{className:"space-y-2 border-t pt-4",children:[o.jsx(we,{children:"Change password"}),o.jsx(Ae,{type:"password",placeholder:"Current password",value:u.current,onChange:le=>f({...u,current:le.target.value})}),o.jsx(Ae,{type:"password",placeholder:"New password (12+ chars)",value:u.next,onChange:le=>f({...u,next:le.target.value})}),o.jsx(me,{disabled:!u.current||u.next.length<12,onClick:async()=>{try{await Se.post("/api/admin/account/password",{currentPassword:u.current,newPassword:u.next}),ve.success("Password changed"),f({current:"",next:""})}catch(le){ve.error(le.message)}},children:"Change password"})]})]})]})}),o.jsx(Os,{value:"backup",children:o.jsxs(nt,{children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Backup & restore"}),o.jsx(gn,{children:"Download a snapshot or restore from a previous backup"})]}),o.jsxs(lt,{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-2 rounded border p-3",children:[o.jsx(we,{children:"Backup passphrase (6 digits)"}),o.jsx(Ae,{inputMode:"numeric",maxLength:6,value:F,onChange:le=>re(le.target.value.replace(/\D/g,"")),placeholder:"123456"}),o.jsx(Ae,{inputMode:"numeric",maxLength:6,value:he,onChange:le=>ge(le.target.value.replace(/\D/g,"")),placeholder:"Repeat passphrase"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This passphrase encrypts the master key inside the backup. You must enter the same 6 digits when importing on a new instance. Without it, encrypted provider credentials cannot be recovered."})]}),o.jsx(me,{disabled:F.length!==6||F!==he,onClick:async()=>{try{const le=await ru("/api/admin/backup/create",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({passphrase:F})});if(!le.ok)throw new Error("Backup failed");const Le=await le.blob(),Ie=URL.createObjectURL(Le),kt=document.createElement("a");kt.href=Ie,kt.download="latedev-backup.json",kt.click(),URL.revokeObjectURL(Ie),ve.success("Backup downloaded"),re(""),ge("")}catch(le){ve.error(le.message)}},children:"Download backup"}),o.jsxs("div",{className:"space-y-2 rounded border p-3",children:[o.jsx(we,{children:"Backup passphrase for restore"}),o.jsx(Ae,{inputMode:"numeric",maxLength:6,value:q,onChange:le=>oe(le.target.value.replace(/\D/g,"")),placeholder:"123456"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Use the 6-digit passphrase entered when the backup was created. It is required to restore the master key and administrator access."})]}),o.jsxs(up,{open:z!==null,onOpenChange:le=>{le||I(null)},children:[o.jsx(vO,{asChild:!0,children:o.jsxs("div",{children:[o.jsx(we,{children:"Restore from backup file"}),o.jsx(Ae,{type:"file",accept:".json,application/json","data-testid":"restore-file",onChange:le=>{var Ie;const Le=(Ie=le.target.files)==null?void 0:Ie[0];I(Le??null)}})]})}),o.jsxs(Pu,{children:[o.jsxs(dp,{children:[o.jsx(qu,{children:"Restore backup?"}),o.jsxs(Vu,{children:["Restoring will replace the entire current database with the selected backup (",(z==null?void 0:z.name)??"file","). This cannot be undone. A snapshot of the current database is kept for rollback only if validation fails."]})]}),o.jsxs(fp,{children:[o.jsx(Yu,{children:"Cancel"}),o.jsx($u,{onClick:async()=>{var Le,Ie;const le=z;if(le)try{const kt=JSON.parse(await le.text()),St=await ru("/api/admin/backup/restore",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({backup:kt,passphrase:q})});if(!St.ok)throw new Error(((Ie=(Le=await St.json())==null?void 0:Le.error)==null?void 0:Ie.message)??"Restore failed");ve.success("Restored. Reloading…"),I(null),setTimeout(()=>location.reload(),600)}catch(kt){ve.error(kt.message)}},children:"Restore"})]})]})]})]})]})}),o.jsxs(Os,{value:"system",children:[o.jsxs(nt,{children:[o.jsx(at,{children:o.jsx(rt,{className:"text-base",children:"System"})}),o.jsxs(lt,{className:"space-y-2 text-sm",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"App version:"})," ",s==null?void 0:s.appVersion]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Data directory:"})," ",o.jsx("span",{className:"font-mono",children:s==null?void 0:s.dataDir})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Encryption:"})," ",s!=null&&s.masterKeyConfigured?"Configured":"Not configured"," (v",s==null?void 0:s.masterKeyVersion,")"]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Environment:"})," ",s==null?void 0:s.environment]}),o.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.jsx(Ca,{checked:a.gatewayCacheEnabled,onCheckedChange:le=>fe({gatewayCacheEnabled:le})}),o.jsx(we,{children:"Gateway response cache (disabled by default)"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(we,{children:"Cache TTL (s)"}),o.jsx(Ae,{type:"number",min:1,value:a.gatewayCacheDefaultTtlSeconds,onChange:le=>fe({gatewayCacheDefaultTtlSeconds:Number(le.target.value)})})]}),o.jsxs("div",{children:[o.jsx(we,{children:"Cache max size (MB)"}),o.jsx(Ae,{type:"number",min:1,value:a.gatewayCacheMaxSizeMb,onChange:le=>fe({gatewayCacheMaxSizeMb:Number(le.target.value)})})]})]}),o.jsx(me,{variant:"outline",onClick:async()=>{const le=await Se.post("/api/admin/settings/cache/clear");ve.success(`Cleared ${le.deleted} entries`)},children:"Clear gateway cache"})]})]}),o.jsx(i4,{}),o.jsxs(nt,{className:"mt-4",children:[o.jsxs(at,{children:[o.jsx(rt,{className:"text-base",children:"Updates"}),o.jsx(gn,{children:"Automatic updates from the npm registry"})]}),o.jsxs(lt,{className:"space-y-3 text-sm",children:[j==="checking"&&!y&&o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx(_s,{className:"h-4 w-4 animate-spin"})," Checking for updates…"]}),y&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Current version"}),o.jsxs("div",{className:"font-mono",children:["v",y.currentVersion]})]}),o.jsx("span",{className:"text-muted-foreground",children:"→"}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Latest version"}),o.jsx("div",{className:"font-mono",children:y.latestVersion?`v${y.latestVersion}`:"—"})]}),y.status.docker?o.jsx(Qe,{variant:"secondary",children:y.status.watchtower?"Docker + Watchtower":"Docker"}):y.latestVersion===null?o.jsx(Qe,{variant:"secondary",children:"Registry unreachable"}):y.hasUpdate?o.jsx(Qe,{variant:"success",children:"Update available"}):o.jsxs(Qe,{variant:"outline",children:[o.jsx(ci,{className:"mr-1 h-3 w-3"})," Up to date"]})]}),y.status.docker&&y.status.watchtower&&y.watchtowerReachable&&o.jsx("p",{className:"text-muted-foreground",children:"Watchtower pulls new images automatically every hour — or use Update now for an instant update."}),y.status.docker&&y.status.watchtower&&y.watchtowerReachable===!1&&o.jsxs("p",{className:"text-muted-foreground",children:["The Watchtower sidecar is configured but not running — start it with ",o.jsx("code",{className:"rounded bg-muted px-1 text-xs",children:"docker compose --profile updater up -d"}),"."]}),y.status.docker&&!y.status.watchtower&&o.jsx("p",{className:"text-muted-foreground",children:y.status.reason??"This instance runs in Docker — update by pulling the new image tag."}),!y.status.docker&&y.latestVersion===null&&o.jsxs("p",{className:"text-muted-foreground",children:["Could not reach the npm registry (offline or blocked). ",N&&o.jsx("span",{className:"text-destructive",children:N})]}),j==="installing"&&o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx(_s,{className:"h-4 w-4 animate-spin"})," Applying the update… this can take a minute."]}),j==="restarting"&&o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx(_s,{className:"h-4 w-4 animate-spin"})," Update applied — the gateway is restarting on the new version. This page reloads automatically."]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.hasUpdate&&j==="idle"&&(!y.status.docker||y.status.watchtower&&y.watchtowerReachable!==!1)&&o.jsxs(me,{disabled:w||y.status.docker&&y.watchtowerReachable===!1,onClick:D,children:[o.jsx(E0,{className:"mr-1 h-4 w-4"})," Update now"]}),y.hasUpdate&&y.changelogUrl&&o.jsx(me,{variant:"outline",asChild:!0,children:o.jsx("a",{href:y.changelogUrl,target:"_blank",rel:"noreferrer",children:"View changes"})}),j==="idle"&&o.jsx(me,{variant:"ghost",disabled:w,onClick:()=>T(!0),children:"Check again"})]})]})]})]})]})]})]})}function i4(){const n=zS();return o.jsxs(nt,{className:"mt-4",children:[o.jsx(at,{children:o.jsxs(rt,{className:"text-base flex items-center gap-2",children:[o.jsx(QE,{className:"h-4 w-4"})," Notifications"]})}),o.jsxs(lt,{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{children:"Show request notifications"}),o.jsx(Ca,{checked:n.enabled,onCheckedChange:a=>void Fb({enabled:a})})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(wR,{className:"h-3 w-3"})," Play notification sound"]}),o.jsx(Ca,{checked:n.sound,onCheckedChange:a=>void Fb({sound:a})})]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Notifications are disabled while muted. Changes apply immediately."})]})]})}function c4({items:n,onDismiss:a}){return n.length?o.jsx("div",{className:"fixed top-16 right-4 z-50 flex max-h-[calc(100vh-8rem)] w-80 flex-col gap-2 overflow-y-auto",children:n.map(l=>{const s=!l.success,c=l.success&&l.totalLatencyMs>15e3,u=Ee("rounded-md border shadow-lg transition-all",s&&"bg-destructive text-destructive-foreground border-destructive",c&&"bg-amber-500/90 text-amber-950 border-amber-600/50",!s&&!c&&"bg-card text-card-foreground border-border");return o.jsxs(ra,{to:"/requests",className:Ee("block shrink-0 p-3 hover:opacity-95",u),children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s?o.jsx(eR,{className:"h-4 w-4 shrink-0"}):l.success?o.jsx(ci,{className:"h-4 w-4 shrink-0"}):o.jsx(SR,{className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("div",{className:"min-w-0 truncate text-sm font-medium",title:l.requestedModel,children:l.requestedModel})]}),o.jsx("button",{className:"shrink-0 opacity-60 hover:opacity-100",onClick:f=>{f.preventDefault(),f.stopPropagation(),a(l.id)},"aria-label":"Dismiss",type:"button",children:o.jsx(Cu,{className:"h-3.5 w-3.5"})})]}),o.jsxs("div",{className:"mt-1 text-xs",children:[l.success?"Thành công":"Thất bại",!l.success&&l.errorType&&o.jsx("span",{className:"ml-1 inline-block rounded bg-black/15 px-1 py-0.5 align-text-bottom text-[10px]",children:l.errorType})]}),o.jsxs("div",{className:"mt-1 text-[11px] opacity-90",children:["in ",Kt(l.inputTokens)," · out ",Kt(l.outputTokens),(l.cacheReadTokens>0||l.cacheWriteTokens>0)&&o.jsxs(o.Fragment,{children:[" · cache ",l.cacheReadTokens>0&&o.jsxs("span",{children:["r",Kt(l.cacheReadTokens)]}),l.cacheReadTokens>0&&l.cacheWriteTokens>0&&"/",l.cacheWriteTokens>0&&o.jsxs("span",{children:["w",Kt(l.cacheWriteTokens)]})]})]}),o.jsxs("div",{className:"mt-1 text-[11px] opacity-90",children:[Ol(l.totalLatencyMs),l.ttftMs!=null&&l.ttftMs>=0&&o.jsxs("span",{children:[" · TTFT ",Ol(l.ttftMs)]})]})]},l.id)})}):null}const u4=5e3,d4=8,f4=3e3;let Gc=null;function h4(){try{Gc||(Gc=new Audio("/notification.mp3")),Gc.currentTime=0,Gc.play().catch(()=>{})}catch{}}function m4(){const[n,a]=m.useState([]),l=m.useRef(null),s=m.useRef(new Map),c=m.useRef(Date.now()),u=m.useRef(new Set),f=zS(),p=m.useRef(f.sound);p.current=f.sound,m.useEffect(()=>{kS()},[]);const g=f.enabled;return m.useEffect(()=>{var w;if(!g){(w=l.current)==null||w.close(),l.current=null;const E=s.current;for(const j of E.values())clearTimeout(j);E.clear(),a([]);return}let x=!1;const y=s.current,b=()=>{if(x)return;const E=new EventSource(`/api/admin/requests/stream?since=${c.current}`);l.current=E,E.addEventListener("request",j=>{if(!x)try{const C=JSON.parse(j.data),N=new Date(C.createdAt).getTime();if(Number.isFinite(N)&&(c.current=Math.max(c.current,N)),u.current.has(C.id))return;u.current.add(C.id),a(T=>T.some(D=>D.id===C.id)?T:[C,...T].slice(0,d4));const M=setTimeout(()=>{a(T=>T.filter(D=>D.id!==C.id)),y.delete(C.id)},u4);y.set(C.id,M),p.current&&h4()}catch{}}),E.onerror=()=>{E.close(),l.current=null,x||setTimeout(b,f4)}};return b(),()=>{var E;x=!0,(E=l.current)==null||E.close(),l.current=null;for(const j of y.values())clearTimeout(j);y.clear()}},[g]),{items:n,dismiss:x=>{const y=s.current.get(x);y&&(clearTimeout(y),s.current.delete(x)),a(b=>b.filter(w=>w.id!==x))}}}function p4({children:n}){const{user:a,loading:l}=_m(),s=_n();return l?o.jsx("div",{className:"flex h-screen items-center justify-center text-muted-foreground",children:"Loading…"}):a?o.jsx(o.Fragment,{children:n}):o.jsx(Ih,{to:"/login",state:{from:s},replace:!0})}function g4(){const{items:n,dismiss:a}=m4();return o.jsxs("div",{className:"flex h-screen bg-background text-foreground",children:[o.jsx(rN,{}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsx(lD,{}),o.jsx("main",{className:"flex-1 overflow-auto p-6",children:o.jsxs(g0,{children:[o.jsx(Nn,{index:!0,element:o.jsx(HD,{})}),o.jsx(Nn,{path:"/providers",element:o.jsx(h_,{})}),o.jsx(Nn,{path:"/models",element:o.jsx(R_,{})}),o.jsx(Nn,{path:"/combos",element:o.jsx(xk,{})}),o.jsx(Nn,{path:"/aliases",element:o.jsx(wk,{})}),o.jsx(Nn,{path:"/api-keys",element:o.jsx(Sk,{})}),o.jsx(Nn,{path:"/requests",element:o.jsx(Ek,{})}),o.jsx(Nn,{path:"/statistics",element:o.jsx(r4,{})}),o.jsx(Nn,{path:"/audit",element:o.jsx(l4,{})}),o.jsx(Nn,{path:"/settings/*",element:o.jsx(o4,{})})]})})]}),o.jsx(c4,{items:n,onDismiss:a})]})}function v4({children:n}){const[a,l]=m.useState(null),s=_n();return m.useEffect(()=>{Se.get("/api/admin/setup/status").then(c=>l(c.setupComplete)).catch(()=>l(!0))},[]),a===null?o.jsx("div",{className:"flex h-screen items-center justify-center text-muted-foreground",children:"Loading…"}):!a&&s.pathname!=="/setup"?o.jsx(Ih,{to:"/setup",replace:!0}):a&&s.pathname==="/setup"?o.jsx(Ih,{to:"/",replace:!0}):o.jsx(o.Fragment,{children:n})}function x4(){return o.jsx(YE,{children:o.jsx(v4,{children:o.jsxs(g0,{children:[o.jsx(Nn,{path:"/setup",element:o.jsx(UD,{})}),o.jsx(Nn,{path:"/login",element:o.jsx(LD,{})}),o.jsx(Nn,{path:"/*",element:o.jsx(p4,{children:o.jsx(g4,{})})})]})})})}const y4=zD;var b4=Object.defineProperty,Dn=(n,a)=>b4(n,"name",{value:a,configurable:!0}),[Bp,J4]=kn("Tooltip",[Ks]),w4=Ks(),S4="TooltipProvider",j4=700,Qb="tooltip.open",[C4,E4]=Bp(S4),R4=Dn(n=>{const{__scopeTooltip:a,delayDuration:l=j4,skipDelayDuration:s=300,disableHoverableContent:c=!1,children:u}=n,f=m.useRef(!0),p=m.useRef(!1),g=m.useRef(0);return m.useEffect(()=>{const v=g.current;return()=>window.clearTimeout(v)},[]),o.jsx(C4,{scope:a,isOpenDelayedRef:f,delayDuration:l,onOpen:m.useCallback(()=>{s<=0||(window.clearTimeout(g.current),f.current=!1)},[s]),onClose:m.useCallback(()=>{s<=0||(window.clearTimeout(g.current),g.current=window.setTimeout(()=>f.current=!0,s))},[s]),isPointerInTransitRef:p,onPointerInTransitChange:m.useCallback(v=>{p.current=v},[]),disableHoverableContent:c,children:u})},"TooltipProvider"),N4="Tooltip",[W4,Hp]=Bp(N4),T4="TooltipPortal",[e5,M4]=Bp(T4,{forceMount:void 0}),li="TooltipContent",A4=m.forwardRef(Dn(function(a,l){const s=M4(li,a.__scopeTooltip),{forceMount:c=s.forceMount,side:u="top",...f}=a,p=Hp(li,a.__scopeTooltip);return o.jsx(Cr,{present:c||p.open,children:p.disableHoverableContent?o.jsx(LS,{side:u,...f,ref:l}):o.jsx(D4,{side:u,...f,ref:l})})},"TooltipContent")),D4=m.forwardRef(Dn(function(a,l){const s=Hp(li,a.__scopeTooltip),c=E4(li,a.__scopeTooltip),u=m.useRef(null),f=Xe(l,u),[p,g]=m.useState(null),{trigger:v,onClose:x}=s,y=u.current,{onPointerInTransitChange:b}=c,w=m.useCallback(()=>{g(null),b(!1)},[b]),E=m.useCallback((j,C)=>{const N=j.currentTarget,M={x:j.clientX,y:j.clientY},T=US(M,N.getBoundingClientRect()),D=BS(M,T),O=HS(C.getBoundingClientRect()),A=PS([...D,...O]);g(A),b(!0)},[b]);return m.useEffect(()=>()=>w(),[w]),m.useEffect(()=>{if(v&&y){const j=Dn(N=>E(N,y),"handleTriggerLeave"),C=Dn(N=>E(N,v),"handleContentLeave");return v.addEventListener("pointerleave",j),y.addEventListener("pointerleave",C),()=>{v.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",C)}}},[v,y,E,w]),m.useEffect(()=>{if(p){const j=Dn(C=>{const N=C.target,M={x:C.clientX,y:C.clientY},T=(v==null?void 0:v.contains(N))||(y==null?void 0:y.contains(N)),D=!IS(M,p);T?w():D&&(w(),x())},"handleTrackPointerGrace");return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[v,y,p,x,w]),o.jsx(LS,{...a,ref:f})},"TooltipContentHoverable")),O4=q0("TooltipContent"),LS=m.forwardRef(Dn(function(a,l){const{__scopeTooltip:s,children:c,"aria-label":u,id:f,onEscapeKeyDown:p,onPointerDownOutside:g,...v}=a,x=Hp(li,s),y=w4(s),{onClose:b}=x;m.useEffect(()=>(document.addEventListener(Qb,b),()=>document.removeEventListener(Qb,b)),[b]),m.useEffect(()=>{if(x.trigger){const E=Dn(j=>{j.target instanceof Node&&j.target.contains(x.trigger)&&b()},"handleScroll");return window.addEventListener("scroll",E,{capture:!0}),()=>window.removeEventListener("scroll",E,{capture:!0})}},[x.trigger,b]);const{setContentId:w}=x;return Xt(()=>(w(f),()=>{w(void 0)}),[f,w]),o.jsx(Nu,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:p,onPointerDownOutside:g,onFocusOutside:E=>E.preventDefault(),onDismiss:b,children:o.jsxs(Qm,{"data-state":x.stateAttribute,role:u?void 0:"tooltip",id:u?void 0:x.contentId,...y,...v,ref:l,style:{...v.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(O4,{children:c}),u?o.jsx(RO,{id:x.contentId,role:"tooltip",children:u}):null]})})},"TooltipContentImpl"));function US(n,a){const l=Math.abs(a.top-n.y),s=Math.abs(a.bottom-n.y),c=Math.abs(a.right-n.x),u=Math.abs(a.left-n.x);switch(Math.min(l,s,c,u)){case u:return"left";case c:return"right";case l:return"top";case s:return"bottom";default:throw new Error("unreachable")}}Dn(US,"getExitSideFromRect");function BS(n,a,l=5){const s=[];switch(a){case"top":s.push({x:n.x-l,y:n.y+l},{x:n.x+l,y:n.y+l});break;case"bottom":s.push({x:n.x-l,y:n.y-l},{x:n.x+l,y:n.y-l});break;case"left":s.push({x:n.x+l,y:n.y-l},{x:n.x+l,y:n.y+l});break;case"right":s.push({x:n.x-l,y:n.y-l},{x:n.x-l,y:n.y+l});break}return s}Dn(BS,"getPaddedExitPoints");function HS(n){const{top:a,right:l,bottom:s,left:c}=n;return[{x:c,y:a},{x:l,y:a},{x:l,y:s},{x:c,y:s}]}Dn(HS,"getPointsFromRect");function IS(n,a){const{x:l,y:s}=n;let c=!1;for(let u=0,f=a.length-1;u<a.length;f=u++){const p=a[u],g=a[f],v=p.x,x=p.y,y=g.x,b=g.y;x>s!=b>s&&l<(y-v)*(s-x)/(b-x)+v&&(c=!c)}return c}Dn(IS,"isPointInPolygon");function PS(n){const a=n.slice();return a.sort((l,s)=>l.x<s.x?-1:l.x>s.x?1:l.y<s.y?-1:l.y>s.y?1:0),qS(a)}Dn(PS,"getHull");function qS(n){if(n.length<=1)return n.slice();const a=[];for(let s=0;s<n.length;s++){const c=n[s];for(;a.length>=2;){const u=a[a.length-1],f=a[a.length-2];if((u.x-f.x)*(c.y-f.y)>=(u.y-f.y)*(c.x-f.x))a.pop();else break}a.push(c)}a.pop();const l=[];for(let s=n.length-1;s>=0;s--){const c=n[s];for(;l.length>=2;){const u=l[l.length-1],f=l[l.length-2];if((u.x-f.x)*(c.y-f.y)>=(u.y-f.y)*(c.x-f.x))l.pop();else break}l.push(c)}return l.pop(),a.length===1&&l.length===1&&a[0].x===l[0].x&&a[0].y===l[0].y?a:a.concat(l)}Dn(qS,"getHullPresorted");var _4=R4,VS=A4;const k4=_4,z4=m.forwardRef(({className:n,sideOffset:a=4,...l},s)=>o.jsx(VS,{ref:s,sideOffset:a,className:Ee("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95",n),...l}));z4.displayName=VS.displayName;d2.createRoot(document.getElementById("root")).render(o.jsx(ue.StrictMode,{children:o.jsx(hN,{defaultTheme:"dark",storageKey:"latedev-theme",children:o.jsxs(k4,{children:[o.jsx(kE,{children:o.jsx(x4,{})}),o.jsx(y4,{position:"top-right"})]})})}));
|