@arcteninc/core 0.0.96 → 0.0.98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/components/ArctenAgent.d.ts +4 -1
  2. package/dist/components/ArctenAgent.d.ts.map +1 -1
  3. package/dist/components/secure-modals/EmailModal.d.ts +10 -0
  4. package/dist/components/secure-modals/EmailModal.d.ts.map +1 -0
  5. package/dist/components/secure-modals/FormModal.d.ts +20 -0
  6. package/dist/components/secure-modals/FormModal.d.ts.map +1 -0
  7. package/dist/components/secure-modals/PasswordModal.d.ts +10 -0
  8. package/dist/components/secure-modals/PasswordModal.d.ts.map +1 -0
  9. package/dist/components/secure-modals/PhoneModal.d.ts +10 -0
  10. package/dist/components/secure-modals/PhoneModal.d.ts.map +1 -0
  11. package/dist/components/secure-modals/PinModal.d.ts +11 -0
  12. package/dist/components/secure-modals/PinModal.d.ts.map +1 -0
  13. package/dist/components/secure-modals/SecureModalProvider.d.ts +13 -0
  14. package/dist/components/secure-modals/SecureModalProvider.d.ts.map +1 -0
  15. package/dist/components/secure-modals/TextModal.d.ts +11 -0
  16. package/dist/components/secure-modals/TextModal.d.ts.map +1 -0
  17. package/dist/components/secure-modals/index.d.ts +10 -0
  18. package/dist/components/secure-modals/index.d.ts.map +1 -0
  19. package/dist/components/secure-modals/types.d.ts +34 -0
  20. package/dist/components/secure-modals/types.d.ts.map +1 -0
  21. package/dist/core.css +1 -1
  22. package/dist/index.cjs +11 -11
  23. package/dist/index.mjs +5019 -3975
  24. package/dist/lib/useAgent.d.ts +1 -1
  25. package/dist/lib/useAgent.d.ts.map +1 -1
  26. package/dist/types/use-agent.d.ts +16 -0
  27. package/dist/types/use-agent.d.ts.map +1 -1
  28. package/dist/utils/form-generator.d.ts +29 -0
  29. package/dist/utils/form-generator.d.ts.map +1 -0
  30. package/dist/utils/secure-param-detector.d.ts +26 -0
  31. package/dist/utils/secure-param-detector.d.ts.map +1 -0
  32. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var ec=Object.create;var Dr=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var sc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,ic=Object.prototype.hasOwnProperty;var oc=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sc(e))!ic.call(t,r)&&r!==n&&Dr(t,r,{get:()=>e[r],enumerable:!(s=nc(e,r))||s.enumerable});return t};var ac=(t,e,n)=>(n=t!=null?ec(rc(t)):{},oc(e||!t||!t.__esModule?Dr(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),yt=require("lucide-react"),Ji=require("@ai-sdk/react"),Ln=require("ai"),Zi=require("@radix-ui/react-slot"),Qi=require("class-variance-authority"),cc=require("clsx"),lc=require("tailwind-merge"),uc=require("@radix-ui/react-tooltip"),Nr=require("@radix-ui/react-use-controllable-state"),dc=require("@radix-ui/react-collapsible"),hc=require("react-dom"),fc=require("./server.cjs");function Bs(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Ft=Bs(m),Be=Bs(uc),zs=Bs(dc);function mt(...t){return lc.twMerge(cc.clsx(t))}const Te=Qi.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Fn=Ft.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Zi.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:mt(Te({variant:e,size:n,className:t})),...r})});Fn.displayName="Button";const mc=Qi.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function ts({className:t,variant:e,asChild:n=!1,...s}){const r=n?Zi.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:mt(mc({variant:e}),t),...s})}const pc=({textAreaRef:t,triggerAutoSize:e,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ft.useState(!0);Ft.useEffect(()=>{const a=t.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[t.current,e])},to=Ft.forwardRef(({maxHeight:t=Number.MAX_SAFE_INTEGER,minHeight:e=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ft.useRef(null),[c,u]=Ft.useState("");return pc({textAreaRef:a,triggerAutoSize:c,maxHeight:t,minHeight:e}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:t,minHeight:e})),Ft.useEffect(()=>{u(r)},[o?.defaultValue,r]),d.jsx("textarea",{...o,value:r,ref:a,className:mt("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:l=>{u(l.target.value),s?.(l)}})});to.displayName="AutosizeTextarea";function gc({delayDuration:t=0,...e}){return d.jsx(Be.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function ae({...t}){return d.jsx(gc,{children:d.jsx(Be.Root,{"data-slot":"tooltip",...t})})}function ce({...t}){return d.jsx(Be.Trigger,{"data-slot":"tooltip-trigger",...t})}function le({className:t,sideOffset:e=0,children:n,...s}){return d.jsx(Be.Portal,{children:d.jsxs(Be.Content,{"data-slot":"tooltip-content",sideOffset:e,className:mt("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...s,children:[n,d.jsx(Be.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Rr({className:t,...e}){return d.jsx("kbd",{"data-slot":"kbd",className:mt("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",t),...e})}const Us=m.createContext({});function _s(t){const e=m.useRef(null);return e.current===null&&(e.current=t()),e.current}const Ws=typeof window<"u",eo=Ws?m.useLayoutEffect:m.useEffect,Wn=m.createContext(null);function Ks(t,e){t.indexOf(e)===-1&&t.push(e)}function qs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Ht=(t,e,n)=>n>e?e:n<t?t:n;function ys(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let We=()=>{},Xt=()=>{};process.env.NODE_ENV!=="production"&&(We=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(ys(e,n))},Xt=(t,e,n)=>{if(!t)throw new Error(ys(e,n))});const Yt={},no=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function so(t){return typeof t=="object"&&t!==null}const ro=t=>/^0[^.\s]+$/u.test(t);function Gs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Rt=t=>t,yc=(t,e)=>n=>e(t(n)),yn=(...t)=>t.reduce(yc),dn=(t,e,n)=>{const s=e-t;return s===0?1:(n-t)/s};class Hs{constructor(){this.subscriptions=[]}add(e){return Ks(this.subscriptions,e),()=>qs(this.subscriptions,e)}notify(e,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(e,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $t=t=>t*1e3,Nt=t=>t/1e3;function io(t,e){return e?t*(1e3/e):0}const Vr=new Set;function Xs(t,e,n){t||Vr.has(e)||(console.warn(ys(e,n)),Vr.add(e))}const oo=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,xc=1e-7,vc=12;function bc(t,e,n,s,r){let o,i,a=0;do i=e+(n-e)/2,o=oo(i,s,r)-t,o>0?n=i:e=i;while(Math.abs(o)>xc&&++a<vc);return i}function xn(t,e,n,s){if(t===e&&n===s)return Rt;const r=o=>bc(o,0,1,t,n);return o=>o===0||o===1?o:oo(r(o),e,s)}const ao=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,co=t=>e=>1-t(1-e),lo=xn(.33,1.53,.69,.99),Ys=co(lo),uo=ao(Ys),ho=t=>(t*=2)<1?.5*Ys(t):.5*(2-Math.pow(2,-10*(t-1))),Js=t=>1-Math.sin(Math.acos(t)),fo=co(Js),mo=ao(Js),wc=xn(.42,0,1,1),Tc=xn(0,0,.58,1),po=xn(.42,0,.58,1),Sc=t=>Array.isArray(t)&&typeof t[0]!="number",go=t=>Array.isArray(t)&&typeof t[0]=="number",Ir={linear:Rt,easeIn:wc,easeInOut:po,easeOut:Tc,circIn:Js,circInOut:mo,circOut:fo,backIn:Ys,backInOut:uo,backOut:lo,anticipate:ho},Ac=t=>typeof t=="string",Or=t=>{if(go(t)){Xt(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,s,r]=t;return xn(e,n,s,r)}else if(Ac(t))return Xt(Ir[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Ir[t];return t},jn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Cc(t,e){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(l){i.has(l)&&(u.schedule(l),t()),l(a)}const u={schedule:(l,h=!1,f=!1)=>{const S=f&&r?n:s;return h&&i.add(l),S.has(l)||S.add(l),l},cancel:l=>{s.delete(l),i.delete(l)},process:l=>{if(a=l,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(l))}};return u}const Pc=40;function yo(t,e){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=jn.reduce((x,M)=>(x[M]=Cc(o),x),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:S}=i,T=()=>{const x=Yt.useManualTiming?r.timestamp:performance.now();n=!1,Yt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(x-r.timestamp,Pc),1)),r.timestamp=x,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),S.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(T))},w=()=>{n=!0,s=!0,r.isProcessing||t(T)};return{schedule:jn.reduce((x,M)=>{const j=i[M];return x[M]=(E,D=!1,A=!1)=>(n||w(),j.schedule(E,D,A)),x},{}),cancel:x=>{for(let M=0;M<jn.length;M++)i[jn[M]].cancel(x)},state:r,steps:i}}const{schedule:ct,cancel:de,state:vt,steps:es}=yo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Rt,!0);let Nn;function jc(){Nn=void 0}const jt={now:()=>(Nn===void 0&&jt.set(vt.isProcessing||Yt.useManualTiming?vt.timestamp:performance.now()),Nn),set:t=>{Nn=t,queueMicrotask(jc)}},xo=t=>e=>typeof e=="string"&&e.startsWith(t),Zs=xo("--"),kc=xo("var(--"),Qs=t=>kc(t)?Mc.test(t.split("/*")[0].trim()):!1,Mc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ke={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},hn={...Ke,transform:t=>Ht(0,1,t)},kn={...Ke,default:1},rn=t=>Math.round(t*1e5)/1e5,tr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ec(t){return t==null}const Dc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,er=(t,e)=>n=>!!(typeof n=="string"&&Dc.test(n)&&n.startsWith(t)||e&&!Ec(n)&&Object.prototype.hasOwnProperty.call(n,e)),vo=(t,e,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(tr);return{[t]:parseFloat(r),[e]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Nc=t=>Ht(0,255,t),ns={...Ke,transform:t=>Math.round(Nc(t))},Ae={test:er("rgb","red"),parse:vo("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+ns.transform(t)+", "+ns.transform(e)+", "+ns.transform(n)+", "+rn(hn.transform(s))+")"};function Rc(t){let e="",n="",s="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,s+=s,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const xs={test:er("#"),parse:Rc,transform:Ae.transform},vn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),ue=vn("deg"),Wt=vn("%"),z=vn("px"),Vc=vn("vh"),Ic=vn("vw"),Lr={...Wt,parse:t=>Wt.parse(t)/100,transform:t=>Wt.transform(t*100)},Ve={test:er("hsl","hue"),parse:vo("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+Wt.transform(rn(e))+", "+Wt.transform(rn(n))+", "+rn(hn.transform(s))+")"},gt={test:t=>Ae.test(t)||xs.test(t)||Ve.test(t),parse:t=>Ae.test(t)?Ae.parse(t):Ve.test(t)?Ve.parse(t):xs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ae.transform(t):Ve.transform(t),getAnimatableNone:t=>{const e=gt.parse(t);return e.alpha=0,gt.transform(e)}},Oc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Lc(t){return isNaN(t)&&typeof t=="string"&&(t.match(tr)?.length||0)+(t.match(Oc)?.length||0)>0}const bo="number",wo="color",Fc="var",$c="var(",Fr="${}",Bc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function fn(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=e.replace(Bc,c=>(gt.test(c)?(s.color.push(o),r.push(wo),n.push(gt.parse(c))):c.startsWith($c)?(s.var.push(o),r.push(Fc),n.push(c)):(s.number.push(o),r.push(bo),n.push(parseFloat(c))),++o,Fr)).split(Fr);return{values:n,split:a,indexes:s,types:r}}function To(t){return fn(t).values}function So(t){const{split:e,types:n}=fn(t),s=e.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=e[i],r[i]!==void 0){const a=n[i];a===bo?o+=rn(r[i]):a===wo?o+=gt.transform(r[i]):o+=r[i]}return o}}const zc=t=>typeof t=="number"?0:gt.test(t)?gt.getAnimatableNone(t):t;function Uc(t){const e=To(t);return So(t)(e.map(zc))}const he={test:Lc,parse:To,createTransformer:So,getAnimatableNone:Uc};function ss(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function _c({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,e/=100,n/=100;let r=0,o=0,i=0;if(!e)r=o=i=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=ss(c,a,t+1/3),o=ss(c,a,t),i=ss(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function $n(t,e){return n=>n>0?e:t}const ut=(t,e,n)=>t+(e-t)*n,rs=(t,e,n)=>{const s=t*t,r=n*(e*e-s)+s;return r<0?0:Math.sqrt(r)},Wc=[xs,Ae,Ve],Kc=t=>Wc.find(e=>e.test(t));function $r(t){const e=Kc(t);if(We(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let n=e.parse(t);return e===Ve&&(n=_c(n)),n}const Br=(t,e)=>{const n=$r(t),s=$r(e);if(!n||!s)return $n(t,e);const r={...n};return o=>(r.red=rs(n.red,s.red,o),r.green=rs(n.green,s.green,o),r.blue=rs(n.blue,s.blue,o),r.alpha=ut(n.alpha,s.alpha,o),Ae.transform(r))},vs=new Set(["none","hidden"]);function qc(t,e){return vs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Gc(t,e){return n=>ut(t,e,n)}function nr(t){return typeof t=="number"?Gc:typeof t=="string"?Qs(t)?$n:gt.test(t)?Br:Yc:Array.isArray(t)?Ao:typeof t=="object"?gt.test(t)?Br:Hc:$n}function Ao(t,e){const n=[...t],s=n.length,r=t.map((o,i)=>nr(o)(o,e[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Hc(t,e){const n={...t,...e},s={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(s[r]=nr(t[r])(t[r],e[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Xc(t,e){const n=[],s={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const o=e.types[r],i=t.indexes[o][s[o]],a=t.values[i]??0;n[r]=a,s[o]++}return n}const Yc=(t,e)=>{const n=he.createTransformer(e),s=fn(t),r=fn(e);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?vs.has(t)&&!r.values.length||vs.has(e)&&!s.values.length?qc(t,e):yn(Ao(Xc(s,r),r.values),n):(We(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),$n(t,e))};function Co(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ut(t,e,n):nr(t)(t,e)}const Jc=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ct.update(e,n),stop:()=>de(e),now:()=>vt.isProcessing?vt.timestamp:jt.now()}},Po=(t,e,n=10)=>{let s="";const r=Math.max(Math.round(e/n),2);for(let o=0;o<r;o++)s+=Math.round(t(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},Bn=2e4;function sr(t){let e=0;const n=50;let s=t.next(e);for(;!s.done&&e<Bn;)e+=n,s=t.next(e);return e>=Bn?1/0:e}function Zc(t,e=100,n){const s=n({...t,keyframes:[0,e]}),r=Math.min(sr(s),Bn);return{type:"keyframes",ease:o=>s.next(r*o).value/e,duration:Nt(r)}}const Qc=5;function jo(t,e,n){const s=Math.max(e-Qc,0);return io(n-t(s),e-s)}const lt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},is=.001;function tl({duration:t=lt.duration,bounce:e=lt.bounce,velocity:n=lt.velocity,mass:s=lt.mass}){let r,o;We(t<=$t(lt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-e;i=Ht(lt.minDamping,lt.maxDamping,i),t=Ht(lt.minDuration,lt.maxDuration,Nt(t)),i<1?(r=u=>{const l=u*i,h=l*t,f=l-n,g=bs(u,i),S=Math.exp(-h);return is-f/g*S},o=u=>{const h=u*i*t,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*t,S=Math.exp(-h),T=bs(Math.pow(u,2),i);return(-r(u)+is>0?-1:1)*((f-g)*S)/T}):(r=u=>{const l=Math.exp(-u*t),h=(u-n)*t+1;return-is+l*h},o=u=>{const l=Math.exp(-u*t),h=(n-u)*(t*t);return l*h});const a=5/t,c=nl(r,o,a);if(t=$t(t),isNaN(c))return{stiffness:lt.stiffness,damping:lt.damping,duration:t};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:t}}}const el=12;function nl(t,e,n){let s=n;for(let r=1;r<el;r++)s=s-t(s)/e(s);return s}function bs(t,e){return t*Math.sqrt(1-e*e)}const sl=["duration","bounce"],rl=["stiffness","damping","mass"];function zr(t,e){return e.some(n=>t[n]!==void 0)}function il(t){let e={velocity:lt.velocity,stiffness:lt.stiffness,damping:lt.damping,mass:lt.mass,isResolvedFromDuration:!1,...t};if(!zr(t,rl)&&zr(t,sl))if(t.visualDuration){const n=t.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Ht(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:lt.mass,stiffness:r,damping:o}}else{const n=tl(t);e={...e,...n,mass:lt.mass},e.isResolvedFromDuration=!0}return e}function zn(t=lt.visualDuration,e=lt.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:l,duration:h,velocity:f,isResolvedFromDuration:g}=il({...n,velocity:-Nt(n.velocity||0)}),S=f||0,T=u/(2*Math.sqrt(c*l)),w=i-o,y=Nt(Math.sqrt(c/l)),v=Math.abs(w)<5;s||(s=v?lt.restSpeed.granular:lt.restSpeed.default),r||(r=v?lt.restDelta.granular:lt.restDelta.default);let x;if(T<1){const j=bs(y,T);x=E=>{const D=Math.exp(-T*y*E);return i-D*((S+T*y*w)/j*Math.sin(j*E)+w*Math.cos(j*E))}}else if(T===1)x=j=>i-Math.exp(-y*j)*(w+(S+y*w)*j);else{const j=y*Math.sqrt(T*T-1);x=E=>{const D=Math.exp(-T*y*E),A=Math.min(j*E,300);return i-D*((S+T*y*w)*Math.sinh(A)+j*w*Math.cosh(A))/j}}const M={calculatedDuration:g&&h||null,next:j=>{const E=x(j);if(g)a.done=j>=h;else{let D=j===0?S:0;T<1&&(D=j===0?$t(S):jo(x,j,E));const A=Math.abs(D)<=s,F=Math.abs(i-E)<=r;a.done=A&&F}return a.value=a.done?i:E,a},toString:()=>{const j=Math.min(sr(M),Bn),E=Po(D=>M.next(j*D).value,j,30);return j+"ms "+E},toTransition:()=>{}};return M}zn.applyToOptions=t=>{const e=Zc(t,100,zn);return t.ease=e.ease,t.duration=$t(e.duration),t.type="keyframes",t};function ws({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:l}){const h=t[0],f={done:!1,value:h},g=A=>a!==void 0&&A<a||c!==void 0&&A>c,S=A=>a===void 0?c:c===void 0||Math.abs(a-A)<Math.abs(c-A)?a:c;let T=n*e;const w=h+T,y=i===void 0?w:i(w);y!==w&&(T=y-h);const v=A=>-T*Math.exp(-A/s),x=A=>y+v(A),M=A=>{const F=v(A),I=x(A);f.done=Math.abs(F)<=u,f.value=f.done?y:I};let j,E;const D=A=>{g(f.value)&&(j=A,E=zn({keyframes:[f.value,S(f.value)],velocity:jo(x,A,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return D(0),{calculatedDuration:null,next:A=>{let F=!1;return!E&&j===void 0&&(F=!0,M(A),D(A)),j!==void 0&&A>=j?E.next(A-j):(!F&&M(A),f)}}}function ol(t,e,n){const s=[],r=n||Yt.mix||Co,o=t.length-1;for(let i=0;i<o;i++){let a=r(t[i],t[i+1]);if(e){const c=Array.isArray(e)?e[i]||Rt:e;a=yn(c,a)}s.push(a)}return s}function al(t,e,{clamp:n=!0,ease:s,mixer:r}={}){const o=t.length;if(Xt(o===e.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const i=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=ol(e,s,r),c=a.length,u=l=>{if(i&&l<t[0])return e[0];let h=0;if(c>1)for(;h<t.length-2&&!(l<t[h+1]);h++);const f=dn(t[h],t[h+1],l);return a[h](f)};return n?l=>u(Ht(t[0],t[o-1],l)):u}function cl(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const r=dn(0,e,s);t.push(ut(n,1,r))}}function ll(t){const e=[0];return cl(e,t.length-1),e}function ul(t,e){return t.map(n=>n*e)}function dl(t,e){return t.map(()=>e||po).splice(0,t.length-1)}function Ie({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const r=Sc(s)?s.map(Or):Or(s),o={done:!1,value:e[0]},i=ul(n&&n.length===e.length?n:ll(e),t),a=al(i,e,{ease:Array.isArray(r)?r:dl(e,r)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const hl=t=>t!==null;function rr(t,{repeat:e,repeatType:n="loop"},s,r=1){const o=t.filter(hl),a=r<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const fl={decay:ws,inertia:ws,tween:Ie,keyframes:Ie,spring:zn};function ko(t){typeof t.type=="string"&&(t.type=fl[t.type])}class ir{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const ml=t=>t/100;class or extends ir{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==jt.now()&&this.tick(jt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;ko(e);const{type:n=Ie,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=e;let{keyframes:a}=e;const c=n||Ie;process.env.NODE_ENV!=="production"&&c!==Ie&&Xt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Ie&&typeof a[0]!="number"&&(this.mixKeyframes=yn(ml,Co(a[0],a[1])),a=[0,100]);const u=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=sr(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:h,repeatType:f,repeatDelay:g,type:S,onUpdate:T,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-u*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let x=this.currentTime,M=s;if(h){const A=Math.min(this.currentTime,r)/a;let F=Math.floor(A),I=A%1;!I&&A>=1&&(I=1),I===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(f==="reverse"?(I=1-I,g&&(I-=g/a)):f==="mirror"&&(M=i)),x=Ht(0,1,I)*a}const j=v?{done:!1,value:l[0]}:M.next(x);o&&(j.value=o(j.value));let{done:E}=j;!v&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return D&&S!==ws&&(j.value=rr(l,this.options,w,this.speed)),T&&T(j.value),D&&this.finish(),j}then(e,n){return this.finished.then(e,n)}get duration(){return Nt(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(this.currentTime)}set time(e){e=$t(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(jt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=Nt(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=Jc,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(jt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}}function pl(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Ce=t=>t*180/Math.PI,Ts=t=>{const e=Ce(Math.atan2(t[1],t[0]));return Ss(e)},gl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ts,rotateZ:Ts,skewX:t=>Ce(Math.atan(t[1])),skewY:t=>Ce(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ss=t=>(t=t%360,t<0&&(t+=360),t),Ur=Ts,_r=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Wr=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),yl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:_r,scaleY:Wr,scale:t=>(_r(t)+Wr(t))/2,rotateX:t=>Ss(Ce(Math.atan2(t[6],t[5]))),rotateY:t=>Ss(Ce(Math.atan2(-t[2],t[0]))),rotateZ:Ur,rotate:Ur,skewX:t=>Ce(Math.atan(t[4])),skewY:t=>Ce(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function As(t){return t.includes("scale")?1:0}function Cs(t,e){if(!t||t==="none")return As(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=yl,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=gl,r=a}if(!r)return As(e);const o=s[e],i=r[1].split(",").map(vl);return typeof o=="function"?o(i):i[o]}const xl=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Cs(n,e)};function vl(t){return parseFloat(t.trim())}const qe=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ge=new Set(qe),Kr=t=>t===Ke||t===z,bl=new Set(["x","y","z"]),wl=qe.filter(t=>!bl.has(t));function Tl(t){const e=[];return wl.forEach(n=>{const s=t.getValue(n);s!==void 0&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}const Pe={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Cs(e,"x"),y:(t,{transform:e})=>Cs(e,"y")};Pe.translateX=Pe.x;Pe.translateY=Pe.y;const je=new Set;let Ps=!1,js=!1,ks=!1;function Mo(){if(js){const t=Array.from(je).filter(s=>s.needsMeasurement),e=new Set(t.map(s=>s.element)),n=new Map;e.forEach(s=>{const r=Tl(s);r.length&&(n.set(s,r),s.render())}),t.forEach(s=>s.measureInitialState()),e.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),t.forEach(s=>s.measureEndState()),t.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}js=!1,Ps=!1,je.forEach(t=>t.complete(ks)),je.clear()}function Eo(){je.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(js=!0)})}function Sl(){ks=!0,Eo(),Mo(),ks=!1}class ar{constructor(e,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(je.add(this),Ps||(Ps=!0,ct.read(Eo),ct.resolveKeyframes(Mo))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:s,motionValue:r}=this;if(e[0]===null){const o=r?.get(),i=e[e.length-1];if(o!==void 0)e[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=i),r&&o===void 0&&r.set(e[0])}pl(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),je.delete(this)}cancel(){this.state==="scheduled"&&(je.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Al=t=>t.startsWith("--");function Cl(t,e,n){Al(e)?t.style.setProperty(e,n):t.style[e]=n}const Pl=Gs(()=>window.ScrollTimeline!==void 0),jl={};function kl(t,e){const n=Gs(t);return()=>jl[e]??n()}const Do=kl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),sn=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,qr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:sn([0,.65,.55,1]),circOut:sn([.55,0,1,.45]),backIn:sn([.31,.01,.66,-.59]),backOut:sn([.33,1.53,.69,.99])};function No(t,e){if(t)return typeof t=="function"?Do()?Po(t,e):"ease-out":go(t)?sn(t):Array.isArray(t)?t.map(n=>No(n,e)||qr.easeOut):qr[t]}function Ml(t,e,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[e]:n};c&&(l.offset=c);const h=No(a,r);Array.isArray(h)&&(l.easing=h);const f={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(f.pseudoElement=u),t.animate(l,f)}function Ro(t){return typeof t=="function"&&"applyToOptions"in t}function El({type:t,...e}){return Ro(t)&&Do()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Dl extends ir{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=e,Xt(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=El(e);this.animation=Ml(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):Cl(n,s,l),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return Nt(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=$t(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&Pl()?(this.animation.timeline=e,Rt):n(this)}}const Vo={anticipate:ho,backInOut:uo,circInOut:mo};function Nl(t){return t in Vo}function Rl(t){typeof t.ease=="string"&&Nl(t.ease)&&(t.ease=Vo[t.ease])}const Gr=10;class Vl extends Dl{constructor(e){Rl(e),ko(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new or({...i,autoplay:!1}),c=$t(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Gr).value,a.sample(c).value,Gr),a.stop()}}const Hr=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(he.test(t)||t==="0")&&!t.startsWith("url("));function Il(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function Ol(t,e,n,s){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],i=Hr(r,e),a=Hr(o,e);return We(i===a,`You are trying to animate ${e} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Il(t)||(n==="spring"||Ro(n))&&s}function Ms(t){t.duration=0,t.type="keyframes"}const Ll=new Set(["opacity","clipPath","filter","transform"]),Fl=Gs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function $l(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=t;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=e.owner.getProps();return Fl()&&n&&Ll.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Bl=40;class zl extends ir{constructor({autoplay:e=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=jt.now();const f={autoplay:e,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...h},g=l?.KeyframeResolver||ar;this.keyframeResolver=new g(a,(S,T,w)=>this.onKeyframesResolved(S,T,f,!w),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=jt.now(),Ol(e,o,i,a)||((Yt.instantAnimations||!c)&&l?.(rr(e,s,n)),e[0]=e[e.length-1],Ms(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Bl?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:e},g=!u&&$l(f)?new Vl({...f,element:f.motionValue.owner.current}):new or(f);g.finished.then(()=>this.notifyFinished()).catch(Rt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Sl()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Ul=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function _l(t){const e=Ul.exec(t);if(!e)return[,];const[,n,s,r]=e;return[`--${n??s}`,r]}const Wl=4;function Io(t,e,n=1){Xt(n<=Wl,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=_l(t);if(!s)return;const o=window.getComputedStyle(e).getPropertyValue(s);if(o){const i=o.trim();return no(i)?parseFloat(i):i}return Qs(r)?Io(r,e,n+1):r}function cr(t,e){return t?.[e]??t?.default??t}const Oo=new Set(["width","height","top","left","right","bottom",...qe]),Kl={test:t=>t==="auto",parse:t=>t},Lo=t=>e=>e.test(t),Fo=[Ke,z,Wt,ue,Ic,Vc,Kl],Xr=t=>Fo.find(Lo(t));function ql(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ro(t):!0}const Gl=new Set(["brightness","contrast","saturate","opacity"]);function Hl(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[s]=n.match(tr)||[];if(!s)return t;const r=n.replace(s,"");let o=Gl.has(e)?1:0;return s!==n&&(o*=100),e+"("+o+r+")"}const Xl=/\b([a-z-]*)\(.*?\)/gu,Es={...he,getAnimatableNone:t=>{const e=t.match(Xl);return e?e.map(Hl).join(" "):t}},Yr={...Ke,transform:Math.round},Yl={rotate:ue,rotateX:ue,rotateY:ue,rotateZ:ue,scale:kn,scaleX:kn,scaleY:kn,scaleZ:kn,skew:ue,skewX:ue,skewY:ue,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:hn,originX:Lr,originY:Lr,originZ:z},lr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...Yl,zIndex:Yr,fillOpacity:hn,strokeOpacity:hn,numOctaves:Yr},Jl={...lr,color:gt,backgroundColor:gt,outlineColor:gt,fill:gt,stroke:gt,borderColor:gt,borderTopColor:gt,borderRightColor:gt,borderBottomColor:gt,borderLeftColor:gt,filter:Es,WebkitFilter:Es},$o=t=>Jl[t];function Bo(t,e){let n=$o(t);return n!==Es&&(n=he),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Zl=new Set(["auto","none","0"]);function Ql(t,e,n){let s=0,r;for(;s<t.length&&!r;){const o=t[s];typeof o=="string"&&!Zl.has(o)&&fn(o).values.length&&(r=t[s]),s++}if(r&&n)for(const o of e)t[o]=Bo(n,r)}class tu extends ar{constructor(e,n,s,r,o){super(e,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let u=e[c];if(typeof u=="string"&&(u=u.trim(),Qs(u))){const l=Io(u,n.current);l!==void 0&&(e[c]=l),c===e.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Oo.has(s)||e.length!==2)return;const[r,o]=e,i=Xr(r),a=Xr(o);if(i!==a)if(Kr(i)&&Kr(a))for(let c=0;c<e.length;c++){const u=e[c];typeof u=="string"&&(e[c]=parseFloat(u))}else Pe[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,s=[];for(let r=0;r<e.length;r++)(e[r]===null||ql(e[r]))&&s.push(r);s.length&&Ql(e,s,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:s}=this;if(!e||!e.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Pe[s](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(s,r).jump(r,!1)}measureEndState(){const{element:e,name:n,unresolvedKeyframes:s}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Pe[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{e.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function eu(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let s=document;const r=n?.[t]??s.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t)}const zo=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function Uo(t){return so(t)&&"offsetHeight"in t}const Jr=30,nu=t=>!isNaN(parseFloat(t));class su{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=jt.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=jt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=nu(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Xs(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new Hs);const s=this.events[e].add(n);return e==="change"?()=>{s(),ct.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-s}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=jt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Jr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Jr);return io(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ue(t,e){return new su(t,e)}const{schedule:ur}=yo(queueMicrotask,!1),Lt={x:!1,y:!1};function _o(){return Lt.x||Lt.y}function ru(t){return t==="x"||t==="y"?Lt[t]?null:(Lt[t]=!0,()=>{Lt[t]=!1}):Lt.x||Lt.y?null:(Lt.x=Lt.y=!0,()=>{Lt.x=Lt.y=!1})}function Wo(t,e){const n=eu(t),s=new AbortController,r={passive:!0,...e,signal:s.signal};return[n,r,()=>s.abort()]}function Zr(t){return!(t.pointerType==="touch"||_o())}function iu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{if(!Zr(a))return;const{target:c}=a,u=e(c,a);if(typeof u!="function"||!c)return;const l=h=>{Zr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Ko=(t,e)=>e?t===e?!0:Ko(t,e.parentElement):!1,dr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,ou=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function au(t){return ou.has(t.tagName)||t.tabIndex!==-1}const Rn=new WeakSet;function Qr(t){return e=>{e.key==="Enter"&&t(e)}}function os(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const cu=(t,e)=>{const n=t.currentTarget;if(!n)return;const s=Qr(()=>{if(Rn.has(n))return;os(n,"down");const r=Qr(()=>{os(n,"up")}),o=()=>os(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",s,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),e)};function ti(t){return dr(t)&&!_o()}function lu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{const c=a.currentTarget;if(!ti(a))return;Rn.add(c);const u=e(c,a),l=(g,S)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),Rn.has(c)&&Rn.delete(c),ti(g)&&typeof u=="function"&&u(g,{success:S})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Ko(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),Uo(a)&&(a.addEventListener("focus",u=>cu(u,r)),!au(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function qo(t){return so(t)&&"ownerSVGElement"in t}function uu(t){return qo(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),du=[...Fo,gt,he],hu=t=>du.find(Lo(t)),hr=m.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function ei(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fu(...t){return e=>{let n=!1;const s=t.map(r=>{const o=ei(r,e);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():ei(t[r],null)}}}}function mu(...t){return Ft.useCallback(fu(...t),t)}class pu extends Ft.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=Uo(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function gu({children:t,isPresent:e,anchorX:n,root:s}){const r=m.useId(),o=m.useRef(null),i=m.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=m.useContext(hr),c=mu(o,t?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:h,left:f,right:g}=i.current;if(e||!o.current||!u||!l)return;const S=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const T=document.createElement("style");a&&(T.nonce=a);const w=s??document.head;return w.appendChild(T),T.sheet&&T.sheet.insertRule(`
1
+ "use strict";var xl=Object.create;var Hr=Object.defineProperty;var bl=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var wl=Object.getPrototypeOf,Tl=Object.prototype.hasOwnProperty;var Sl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of vl(t))!Tl.call(e,r)&&r!==n&&Hr(e,r,{get:()=>t[r],enumerable:!(s=bl(t,r))||s.enumerable});return e};var jl=(e,t,n)=>(n=e!=null?xl(wl(e)):{},Sl(t||!e||!e.__esModule?Hr(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),f=require("react"),oe=require("lucide-react"),go=require("@ai-sdk/react"),ss=require("ai"),yo=require("@radix-ui/react-slot"),xo=require("class-variance-authority"),Cl=require("clsx"),Pl=require("tailwind-merge"),Al=require("@radix-ui/react-tooltip"),Yr=require("@radix-ui/react-use-controllable-state"),kl=require("@radix-ui/react-collapsible"),Ml=require("react-dom"),El=require("@radix-ui/react-dialog"),Nl=require("./server.cjs");function cs(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Xe=cs(f),en=cs(Al),ir=cs(kl),$t=cs(El);function ae(...e){return Pl.twMerge(Cl.clsx(e))}const Nt=xo.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),je=Xe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?yo.Slot:"button";return c.jsx(i,{ref:o,"data-slot":"button",className:ae(Nt({variant:t,size:n,className:e})),...r})});je.displayName="Button";const Dl=xo.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function xs({className:e,variant:t,asChild:n=!1,...s}){const r=n?yo.Slot:"span";return c.jsx(r,{"data-slot":"badge",className:ae(Dl({variant:t}),e),...s})}const Rl=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Xe.useState(!0);Xe.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},bo=Xe.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Xe.useRef(null),[l,u]=Xe.useState("");return Rl({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),f.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Xe.useEffect(()=>{u(r)},[o?.defaultValue,r]),c.jsx("textarea",{...o,value:r,ref:a,className:ae("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:d=>{u(d.target.value),s?.(d)}})});bo.displayName="AutosizeTextarea";function Vl({delayDuration:e=0,...t}){return c.jsx(en.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function pt({...e}){return c.jsx(Vl,{children:c.jsx(en.Root,{"data-slot":"tooltip",...e})})}function gt({...e}){return c.jsx(en.Trigger,{"data-slot":"tooltip-trigger",...e})}function yt({className:e,sideOffset:t=0,children:n,...s}){return c.jsx(en.Portal,{children:c.jsxs(en.Content,{"data-slot":"tooltip-content",sideOffset:t,className:ae("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,c.jsx(en.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Jr({className:e,...t}){return c.jsx("kbd",{"data-slot":"kbd",className:ae("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const or=f.createContext({});function ar(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const lr=typeof window<"u",vo=lr?f.useLayoutEffect:f.useEffect,us=f.createContext(null);function cr(e,t){e.indexOf(t)===-1&&e.push(t)}function ur(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const at=(e,t,n)=>n>t?t:n<e?e:n;function Os(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let rn=()=>{},lt=()=>{};process.env.NODE_ENV!=="production"&&(rn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Os(t,n))},lt=(e,t,n)=>{if(!e)throw new Error(Os(t,n))});const ct={},wo=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function To(e){return typeof e=="object"&&e!==null}const So=e=>/^0[^.\s]+$/u.test(e);function dr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Oe=e=>e,Il=(e,t)=>n=>t(e(n)),$n=(...e)=>e.reduce(Il),Nn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class hr{constructor(){this.subscriptions=[]}add(t){return cr(this.subscriptions,t),()=>ur(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const qe=e=>e*1e3,Ie=e=>e/1e3;function jo(e,t){return t?e*(1e3/t):0}const Zr=new Set;function fr(e,t,n){e||Zr.has(t)||(console.warn(Os(t,n)),Zr.add(t))}const Co=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Ol=1e-7,$l=12;function Ll(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Co(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>Ol&&++a<$l);return i}function Ln(e,t,n,s){if(e===t&&n===s)return Oe;const r=o=>Ll(o,0,1,e,n);return o=>o===0||o===1?o:Co(r(o),t,s)}const Po=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Ao=e=>t=>1-e(1-t),ko=Ln(.33,1.53,.69,.99),mr=Ao(ko),Mo=Po(mr),Eo=e=>(e*=2)<1?.5*mr(e):.5*(2-Math.pow(2,-10*(e-1))),pr=e=>1-Math.sin(Math.acos(e)),No=Ao(pr),Do=Po(pr),Fl=Ln(.42,0,1,1),Bl=Ln(0,0,.58,1),Ro=Ln(.42,0,.58,1),zl=e=>Array.isArray(e)&&typeof e[0]!="number",Vo=e=>Array.isArray(e)&&typeof e[0]=="number",Qr={linear:Oe,easeIn:Fl,easeInOut:Ro,easeOut:Bl,circIn:pr,circInOut:Do,circOut:No,backIn:mr,backInOut:Mo,backOut:ko,anticipate:Eo},Ul=e=>typeof e=="string",ei=e=>{if(Vo(e)){lt(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Ln(t,n,s,r)}else if(Ul(e))return lt(Qr[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Qr[e];return e},Kn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function _l(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(d){i.has(d)&&(u.schedule(d),e()),d(a)}const u={schedule:(d,h=!1,m=!1)=>{const v=m&&r?n:s;return h&&i.add(d),v.has(d)||v.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,u.process(d))}};return u}const Xl=40;function Io(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Kn.reduce((k,N)=>(k[N]=_l(o),k),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:d,update:h,preRender:m,render:g,postRender:v}=i,b=()=>{const k=ct.useManualTiming?r.timestamp:performance.now();n=!1,ct.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(k-r.timestamp,Xl),1)),r.timestamp=k,r.isProcessing=!0,a.process(r),l.process(r),u.process(r),d.process(r),h.process(r),m.process(r),g.process(r),v.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(b))},y=()=>{n=!0,s=!0,r.isProcessing||e(b)};return{schedule:Kn.reduce((k,N)=>{const R=i[N];return k[N]=(B,O=!1,E=!1)=>(n||y(),R.schedule(B,O,E)),k},{}),cancel:k=>{for(let N=0;N<Kn.length;N++)i[Kn[N]].cancel(k)},state:r,steps:i}}const{schedule:ue,cancel:bt,state:we,steps:bs}=Io(typeof requestAnimationFrame<"u"?requestAnimationFrame:Oe,!0);let Zn;function ql(){Zn=void 0}const ke={now:()=>(Zn===void 0&&ke.set(we.isProcessing||ct.useManualTiming?we.timestamp:performance.now()),Zn),set:e=>{Zn=e,queueMicrotask(ql)}},Oo=e=>t=>typeof t=="string"&&t.startsWith(e),gr=Oo("--"),Wl=Oo("var(--"),yr=e=>Wl(e)?Kl.test(e.split("/*")[0].trim()):!1,Kl=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,on={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Dn={...on,transform:e=>at(0,1,e)},Gn={...on,default:1},Cn=e=>Math.round(e*1e5)/1e5,xr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Gl(e){return e==null}const Hl=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,br=(e,t)=>n=>!!(typeof n=="string"&&Hl.test(n)&&n.startsWith(e)||t&&!Gl(n)&&Object.prototype.hasOwnProperty.call(n,t)),$o=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(xr);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Yl=e=>at(0,255,e),vs={...on,transform:e=>Math.round(Yl(e))},Rt={test:br("rgb","red"),parse:$o("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+vs.transform(e)+", "+vs.transform(t)+", "+vs.transform(n)+", "+Cn(Dn.transform(s))+")"};function Jl(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const $s={test:br("#"),parse:Jl,transform:Rt.transform},Fn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),xt=Fn("deg"),Je=Fn("%"),K=Fn("px"),Zl=Fn("vh"),Ql=Fn("vw"),ti={...Je,parse:e=>Je.parse(e)/100,transform:e=>Je.transform(e*100)},Gt={test:br("hsl","hue"),parse:$o("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Je.transform(Cn(t))+", "+Je.transform(Cn(n))+", "+Cn(Dn.transform(s))+")"},xe={test:e=>Rt.test(e)||$s.test(e)||Gt.test(e),parse:e=>Rt.test(e)?Rt.parse(e):Gt.test(e)?Gt.parse(e):$s.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Rt.transform(e):Gt.transform(e),getAnimatableNone:e=>{const t=xe.parse(e);return t.alpha=0,xe.transform(t)}},ec=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function tc(e){return isNaN(e)&&typeof e=="string"&&(e.match(xr)?.length||0)+(e.match(ec)?.length||0)>0}const Lo="number",Fo="color",nc="var",sc="var(",ni="${}",rc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Rn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(rc,l=>(xe.test(l)?(s.color.push(o),r.push(Fo),n.push(xe.parse(l))):l.startsWith(sc)?(s.var.push(o),r.push(nc),n.push(l)):(s.number.push(o),r.push(Lo),n.push(parseFloat(l))),++o,ni)).split(ni);return{values:n,split:a,indexes:s,types:r}}function Bo(e){return Rn(e).values}function zo(e){const{split:t,types:n}=Rn(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Lo?o+=Cn(r[i]):a===Fo?o+=xe.transform(r[i]):o+=r[i]}return o}}const ic=e=>typeof e=="number"?0:xe.test(e)?xe.getAnimatableNone(e):e;function oc(e){const t=Bo(e);return zo(e)(t.map(ic))}const vt={test:tc,parse:Bo,createTransformer:zo,getAnimatableNone:oc};function ws(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function ac({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;r=ws(l,a,e+1/3),o=ws(l,a,e),i=ws(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function rs(e,t){return n=>n>0?t:e}const fe=(e,t,n)=>e+(t-e)*n,Ts=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},lc=[$s,Rt,Gt],cc=e=>lc.find(t=>t.test(e));function si(e){const t=cc(e);if(rn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Gt&&(n=ac(n)),n}const ri=(e,t)=>{const n=si(e),s=si(t);if(!n||!s)return rs(e,t);const r={...n};return o=>(r.red=Ts(n.red,s.red,o),r.green=Ts(n.green,s.green,o),r.blue=Ts(n.blue,s.blue,o),r.alpha=fe(n.alpha,s.alpha,o),Rt.transform(r))},Ls=new Set(["none","hidden"]);function uc(e,t){return Ls.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function dc(e,t){return n=>fe(e,t,n)}function vr(e){return typeof e=="number"?dc:typeof e=="string"?yr(e)?rs:xe.test(e)?ri:mc:Array.isArray(e)?Uo:typeof e=="object"?xe.test(e)?ri:hc:rs}function Uo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>vr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function hc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=vr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function fc(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const mc=(e,t)=>{const n=vt.createTransformer(t),s=Rn(e),r=Rn(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?Ls.has(e)&&!r.values.length||Ls.has(t)&&!s.values.length?uc(e,t):$n(Uo(fc(s,r),r.values),n):(rn(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),rs(e,t))};function _o(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?fe(e,t,n):vr(e)(e,t)}const pc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ue.update(t,n),stop:()=>bt(t),now:()=>we.isProcessing?we.timestamp:ke.now()}},Xo=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},is=2e4;function wr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<is;)t+=n,s=e.next(t);return t>=is?1/0:t}function gc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(wr(s),is);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Ie(r)}}const yc=5;function qo(e,t,n){const s=Math.max(t-yc,0);return jo(n-e(s),t-s)}const he={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Ss=.001;function xc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;rn(e<=qe(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=at(he.minDamping,he.maxDamping,i),e=at(he.minDuration,he.maxDuration,Ie(e)),i<1?(r=u=>{const d=u*i,h=d*e,m=d-n,g=Fs(u,i),v=Math.exp(-h);return Ss-m/g*v},o=u=>{const h=u*i*e,m=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*e,v=Math.exp(-h),b=Fs(Math.pow(u,2),i);return(-r(u)+Ss>0?-1:1)*((m-g)*v)/b}):(r=u=>{const d=Math.exp(-u*e),h=(u-n)*e+1;return-Ss+d*h},o=u=>{const d=Math.exp(-u*e),h=(n-u)*(e*e);return d*h});const a=5/e,l=vc(r,o,a);if(e=qe(e),isNaN(l))return{stiffness:he.stiffness,damping:he.damping,duration:e};{const u=Math.pow(l,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const bc=12;function vc(e,t,n){let s=n;for(let r=1;r<bc;r++)s=s-e(s)/t(s);return s}function Fs(e,t){return e*Math.sqrt(1-t*t)}const wc=["duration","bounce"],Tc=["stiffness","damping","mass"];function ii(e,t){return t.some(n=>e[n]!==void 0)}function Sc(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!ii(e,Tc)&&ii(e,wc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*at(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=xc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function os(e=he.visualDuration,t=he.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:g}=Sc({...n,velocity:-Ie(n.velocity||0)}),v=m||0,b=u/(2*Math.sqrt(l*d)),y=i-o,x=Ie(Math.sqrt(l/d)),j=Math.abs(y)<5;s||(s=j?he.restSpeed.granular:he.restSpeed.default),r||(r=j?he.restDelta.granular:he.restDelta.default);let k;if(b<1){const R=Fs(x,b);k=B=>{const O=Math.exp(-b*x*B);return i-O*((v+b*x*y)/R*Math.sin(R*B)+y*Math.cos(R*B))}}else if(b===1)k=R=>i-Math.exp(-x*R)*(y+(v+x*y)*R);else{const R=x*Math.sqrt(b*b-1);k=B=>{const O=Math.exp(-b*x*B),E=Math.min(R*B,300);return i-O*((v+b*x*y)*Math.sinh(E)+R*y*Math.cosh(E))/R}}const N={calculatedDuration:g&&h||null,next:R=>{const B=k(R);if(g)a.done=R>=h;else{let O=R===0?v:0;b<1&&(O=R===0?qe(v):qo(k,R,B));const E=Math.abs(O)<=s,F=Math.abs(i-B)<=r;a.done=E&&F}return a.value=a.done?i:B,a},toString:()=>{const R=Math.min(wr(N),is),B=Xo(O=>N.next(R*O).value,R,30);return R+"ms "+B},toTransition:()=>{}};return N}os.applyToOptions=e=>{const t=gc(e,100,os);return e.ease=t.ease,e.duration=qe(t.duration),e.type="keyframes",e};function Bs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:u=.5,restSpeed:d}){const h=e[0],m={done:!1,value:h},g=E=>a!==void 0&&E<a||l!==void 0&&E>l,v=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let b=n*t;const y=h+b,x=i===void 0?y:i(y);x!==y&&(b=x-h);const j=E=>-b*Math.exp(-E/s),k=E=>x+j(E),N=E=>{const F=j(E),S=k(E);m.done=Math.abs(F)<=u,m.value=m.done?x:S};let R,B;const O=E=>{g(m.value)&&(R=E,B=os({keyframes:[m.value,v(m.value)],velocity:qo(k,E,m.value),damping:r,stiffness:o,restDelta:u,restSpeed:d}))};return O(0),{calculatedDuration:null,next:E=>{let F=!1;return!B&&R===void 0&&(F=!0,N(E),O(E)),R!==void 0&&E>=R?B.next(E-R):(!F&&N(E),m)}}}function jc(e,t,n){const s=[],r=n||ct.mix||_o,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const l=Array.isArray(t)?t[i]||Oe:t;a=$n(l,a)}s.push(a)}return s}function Cc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(lt(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=jc(t,s,r),l=a.length,u=d=>{if(i&&d<e[0])return t[0];let h=0;if(l>1)for(;h<e.length-2&&!(d<e[h+1]);h++);const m=Nn(e[h],e[h+1],d);return a[h](m)};return n?d=>u(at(e[0],e[o-1],d)):u}function Pc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Nn(0,t,s);e.push(fe(n,1,r))}}function Ac(e){const t=[0];return Pc(t,e.length-1),t}function kc(e,t){return e.map(n=>n*t)}function Mc(e,t){return e.map(()=>t||Ro).splice(0,e.length-1)}function Ht({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=zl(s)?s.map(ei):ei(s),o={done:!1,value:t[0]},i=kc(n&&n.length===t.length?n:Ac(t),e),a=Cc(i,t,{ease:Array.isArray(r)?r:Mc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Ec=e=>e!==null;function Tr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Ec),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Nc={decay:Bs,inertia:Bs,tween:Ht,keyframes:Ht,spring:os};function Wo(e){typeof e.type=="string"&&(e.type=Nc[e.type])}class Sr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const Dc=e=>e/100;class jr extends Sr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==ke.now()&&this.tick(ke.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;Wo(t);const{type:n=Ht,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Ht;process.env.NODE_ENV!=="production"&&l!==Ht&&lt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Ht&&typeof a[0]!="number"&&(this.mixKeyframes=$n(Dc,_o(a[0],a[1])),a=[0,100]);const u=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=wr(u));const{calculatedDuration:d}=u;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:d,repeat:h,repeatType:m,repeatDelay:g,type:v,onUpdate:b,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const x=this.currentTime-u*(this.playbackSpeed>=0?1:-1),j=this.playbackSpeed>=0?x<0:x>r;this.currentTime=Math.max(x,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let k=this.currentTime,N=s;if(h){const E=Math.min(this.currentTime,r)/a;let F=Math.floor(E),S=E%1;!S&&E>=1&&(S=1),S===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(m==="reverse"?(S=1-S,g&&(S-=g/a)):m==="mirror"&&(N=i)),k=at(0,1,S)*a}const R=j?{done:!1,value:d[0]}:N.next(k);o&&(R.value=o(R.value));let{done:B}=R;!j&&l!==null&&(B=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const O=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&B);return O&&v!==Bs&&(R.value=Tr(d,this.options,y,this.speed)),b&&b(R.value),O&&this.finish(),R}then(t,n){return this.finished.then(t,n)}get duration(){return Ie(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ie(t)}get time(){return Ie(this.currentTime)}set time(t){t=qe(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(ke.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Ie(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=pc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ke.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Rc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Vt=e=>e*180/Math.PI,zs=e=>{const t=Vt(Math.atan2(e[1],e[0]));return Us(t)},Vc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:zs,rotateZ:zs,skewX:e=>Vt(Math.atan(e[1])),skewY:e=>Vt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Us=e=>(e=e%360,e<0&&(e+=360),e),oi=zs,ai=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),li=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Ic={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ai,scaleY:li,scale:e=>(ai(e)+li(e))/2,rotateX:e=>Us(Vt(Math.atan2(e[6],e[5]))),rotateY:e=>Us(Vt(Math.atan2(-e[2],e[0]))),rotateZ:oi,rotate:oi,skewX:e=>Vt(Math.atan(e[4])),skewY:e=>Vt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function _s(e){return e.includes("scale")?1:0}function Xs(e,t){if(!e||e==="none")return _s(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=Ic,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Vc,r=a}if(!r)return _s(t);const o=s[t],i=r[1].split(",").map($c);return typeof o=="function"?o(i):i[o]}const Oc=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Xs(n,t)};function $c(e){return parseFloat(e.trim())}const an=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ln=new Set(an),ci=e=>e===on||e===K,Lc=new Set(["x","y","z"]),Fc=an.filter(e=>!Lc.has(e));function Bc(e){const t=[];return Fc.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const It={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Xs(t,"x"),y:(e,{transform:t})=>Xs(t,"y")};It.translateX=It.x;It.translateY=It.y;const Ot=new Set;let qs=!1,Ws=!1,Ks=!1;function Ko(){if(Ws){const e=Array.from(Ot).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Bc(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Ws=!1,qs=!1,Ot.forEach(e=>e.complete(Ks)),Ot.clear()}function Go(){Ot.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ws=!0)})}function zc(){Ks=!0,Go(),Ko(),Ks=!1}class Cr{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ot.add(this),qs||(qs=!0,ue.read(Go),ue.resolveKeyframes(Ko))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}Rc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ot.delete(this)}cancel(){this.state==="scheduled"&&(Ot.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Uc=e=>e.startsWith("--");function _c(e,t,n){Uc(t)?e.style.setProperty(t,n):e.style[t]=n}const Xc=dr(()=>window.ScrollTimeline!==void 0),qc={};function Wc(e,t){const n=dr(e);return()=>qc[t]??n()}const Ho=Wc(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Sn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,ui={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Sn([0,.65,.55,1]),circOut:Sn([.55,0,1,.45]),backIn:Sn([.31,.01,.66,-.59]),backOut:Sn([.33,1.53,.69,.99])};function Yo(e,t){if(e)return typeof e=="function"?Ho()?Xo(e,t):"ease-out":Vo(e)?Sn(e):Array.isArray(e)?e.map(n=>Yo(n,t)||ui.easeOut):ui[e]}function Kc(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},u=void 0){const d={[t]:n};l&&(d.offset=l);const h=Yo(a,r);Array.isArray(h)&&(d.easing=h);const m={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(m.pseudoElement=u),e.animate(d,m)}function Jo(e){return typeof e=="function"&&"applyToOptions"in e}function Gc({type:e,...t}){return Jo(e)&&Ho()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Hc extends Sr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:l}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,lt(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Gc(t);this.animation=Kc(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Tr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):_c(n,s,d),this.animation.cancel()}l?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return Ie(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ie(t)}get time(){return Ie(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=qe(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Xc()?(this.animation.timeline=t,Oe):n(this)}}const Zo={anticipate:Eo,backInOut:Mo,circInOut:Do};function Yc(e){return e in Zo}function Jc(e){typeof e.ease=="string"&&Yc(e.ease)&&(e.ease=Zo[e.ease])}const di=10;class Zc extends Hc{constructor(t){Jc(t),Wo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new jr({...i,autoplay:!1}),l=qe(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-di).value,a.sample(l).value,di),a.stop()}}const hi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(vt.test(e)||e==="0")&&!e.startsWith("url("));function Qc(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function eu(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=hi(r,t),a=hi(o,t);return rn(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Qc(e)||(n==="spring"||Jo(n))&&s}function Gs(e){e.duration=0,e.type="keyframes"}const tu=new Set(["opacity","clipPath","filter","transform"]),nu=dr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function su(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:u}=t.owner.getProps();return nu()&&n&&tu.has(n)&&(n!=="transform"||!u)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const ru=40;class iu extends Sr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:u,element:d,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ke.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:u,element:d,...h},g=d?.KeyframeResolver||Cr;this.keyframeResolver=new g(a,(v,b,y)=>this.onKeyframesResolved(v,b,m,!y),l,u,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:u,onUpdate:d}=s;this.resolvedAt=ke.now(),eu(t,o,i,a)||((ct.instantAnimations||!l)&&d?.(Tr(t,s,n)),t[0]=t[t.length-1],Gs(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>ru?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=!u&&su(m)?new Zc({...m,element:m.motionValue.owner.current}):new jr(m);g.finished.then(()=>this.notifyFinished()).catch(Oe),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),zc()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const ou=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function au(e){const t=ou.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const lu=4;function Qo(e,t,n=1){lt(n<=lu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=au(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return wo(i)?parseFloat(i):i}return yr(r)?Qo(r,t,n+1):r}function Pr(e,t){return e?.[t]??e?.default??e}const ea=new Set(["width","height","top","left","right","bottom",...an]),cu={test:e=>e==="auto",parse:e=>e},ta=e=>t=>t.test(e),na=[on,K,Je,xt,Ql,Zl,cu],fi=e=>na.find(ta(e));function uu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||So(e):!0}const du=new Set(["brightness","contrast","saturate","opacity"]);function hu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(xr)||[];if(!s)return e;const r=n.replace(s,"");let o=du.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const fu=/\b([a-z-]*)\(.*?\)/gu,Hs={...vt,getAnimatableNone:e=>{const t=e.match(fu);return t?t.map(hu).join(" "):e}},mi={...on,transform:Math.round},mu={rotate:xt,rotateX:xt,rotateY:xt,rotateZ:xt,scale:Gn,scaleX:Gn,scaleY:Gn,scaleZ:Gn,skew:xt,skewX:xt,skewY:xt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:Dn,originX:ti,originY:ti,originZ:K},Ar={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...mu,zIndex:mi,fillOpacity:Dn,strokeOpacity:Dn,numOctaves:mi},pu={...Ar,color:xe,backgroundColor:xe,outlineColor:xe,fill:xe,stroke:xe,borderColor:xe,borderTopColor:xe,borderRightColor:xe,borderBottomColor:xe,borderLeftColor:xe,filter:Hs,WebkitFilter:Hs},sa=e=>pu[e];function ra(e,t){let n=sa(e);return n!==Hs&&(n=vt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const gu=new Set(["auto","none","0"]);function yu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!gu.has(o)&&Rn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ra(n,r)}class xu extends Cr{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let u=t[l];if(typeof u=="string"&&(u=u.trim(),yr(u))){const d=Qo(u,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!ea.has(s)||t.length!==2)return;const[r,o]=t,i=fi(r),a=fi(o);if(i!==a)if(ci(i)&&ci(a))for(let l=0;l<t.length;l++){const u=t[l];typeof u=="string"&&(t[l]=parseFloat(u))}else It[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||uu(t[r]))&&s.push(r);s.length&&yu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=It[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=It[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function bu(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const ia=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function oa(e){return To(e)&&"offsetHeight"in e}const pi=30,vu=e=>!isNaN(parseFloat(e));class wu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=ke.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=ke.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=vu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&fr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new hr);const s=this.events[t].add(n);return t==="change"?()=>{s(),ue.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=ke.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>pi)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,pi);return jo(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function nn(e,t){return new wu(e,t)}const{schedule:kr}=Io(queueMicrotask,!1),_e={x:!1,y:!1};function aa(){return _e.x||_e.y}function Tu(e){return e==="x"||e==="y"?_e[e]?null:(_e[e]=!0,()=>{_e[e]=!1}):_e.x||_e.y?null:(_e.x=_e.y=!0,()=>{_e.x=_e.y=!1})}function la(e,t){const n=bu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function gi(e){return!(e.pointerType==="touch"||aa())}function Su(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{if(!gi(a))return;const{target:l}=a,u=t(l,a);if(typeof u!="function"||!l)return;const d=h=>{gi(h)&&(u(h),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ca=(e,t)=>t?e===t?!0:ca(e,t.parentElement):!1,Mr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,ju=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Cu(e){return ju.has(e.tagName)||e.tabIndex!==-1}const Qn=new WeakSet;function yi(e){return t=>{t.key==="Enter"&&e(t)}}function js(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Pu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=yi(()=>{if(Qn.has(n))return;js(n,"down");const r=yi(()=>{js(n,"up")}),o=()=>js(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function xi(e){return Mr(e)&&!aa()}function Au(e,t,n={}){const[s,r,o]=la(e,n),i=a=>{const l=a.currentTarget;if(!xi(a))return;Qn.add(l);const u=t(l,a),d=(g,v)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),Qn.has(l)&&Qn.delete(l),xi(g)&&typeof u=="function"&&u(g,{success:v})},h=g=>{d(g,l===window||l===document||n.useGlobalTarget||ca(l,g.target))},m=g=>{d(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",m,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),oa(a)&&(a.addEventListener("focus",u=>Pu(u,r)),!Cu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ua(e){return To(e)&&"ownerSVGElement"in e}function ku(e){return ua(e)&&e.tagName==="svg"}const Se=e=>!!(e&&e.getVelocity),Mu=[...na,xe,vt],Eu=e=>Mu.find(ta(e)),Er=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function bi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Nu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=bi(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():bi(e[r],null)}}}}function Du(...e){return Xe.useCallback(Nu(...e),e)}class Ru extends Xe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=oa(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Vu({children:e,isPresent:t,anchorX:n,root:s}){const r=f.useId(),o=f.useRef(null),i=f.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=f.useContext(Er),l=Du(o,e?.ref);return f.useInsertionEffect(()=>{const{width:u,height:d,top:h,left:m,right:g}=i.current;if(t||!o.current||!u||!d)return;const v=n==="left"?`left: ${m}`:`right: ${g}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const y=s??document.head;return y.appendChild(b),b.sheet&&b.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
5
- height: ${l}px !important;
6
- ${S}px !important;
5
+ height: ${d}px !important;
6
+ ${v}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{w.contains(T)&&w.removeChild(T)}},[e]),d.jsx(pu,{isPresent:e,childRef:o,sizeRef:i,children:Ft.cloneElement(t,{ref:c})})}const yu=({children:t,initial:e,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=_s(xu),l=m.useId();let h=!0,f=m.useMemo(()=>(h=!1,{id:l,initial:e,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const S of u.values())if(!S)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&h&&(f={...f}),m.useMemo(()=>{u.forEach((g,S)=>u.set(S,!1))},[n]),Ft.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(t=d.jsx(gu,{isPresent:n,anchorX:a,root:c,children:t})),d.jsx(Wn.Provider,{value:f,children:t})};function xu(){return new Map}function Go(t=!0){const e=m.useContext(Wn);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=e,o=m.useId();m.useEffect(()=>{if(t)return r(o)},[t]);const i=m.useCallback(()=>t&&s&&s(o),[o,s,t]);return!n&&s?[!1,i]:[!0]}const Mn=t=>t.key||"";function ni(t){const e=[];return m.Children.forEach(t,n=>{m.isValidElement(n)&&e.push(n)}),e}const vu=({children:t,custom:e,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=Go(i),h=m.useMemo(()=>ni(t),[t]),f=i&&!u?[]:h.map(Mn),g=m.useRef(!0),S=m.useRef(h),T=_s(()=>new Map),[w,y]=m.useState(h),[v,x]=m.useState(h);eo(()=>{g.current=!1,S.current=h;for(let E=0;E<v.length;E++){const D=Mn(v[E]);f.includes(D)?T.delete(D):T.get(D)!==!0&&T.set(D,!1)}},[v,f.length,f.join("-")]);const M=[];if(h!==w){let E=[...h];for(let D=0;D<v.length;D++){const A=v[D],F=Mn(A);f.includes(F)||(E.splice(D,0,A),M.push(A))}return o==="wait"&&M.length&&(E=M),x(ni(E)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&v.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:j}=m.useContext(Us);return d.jsx(d.Fragment,{children:v.map(E=>{const D=Mn(E),A=i&&!u?!1:h===v||f.includes(D),F=()=>{if(T.has(D))T.set(D,!0);else return;let I=!0;T.forEach(X=>{X||(I=!1)}),I&&(j?.(),x(S.current),i&&l?.(),s&&s())};return d.jsx(yu,{isPresent:A,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:A?void 0:F,anchorX:a,children:E},D)})})},fr=m.createContext({strict:!1}),si={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},_e={};for(const t in si)_e[t]={isEnabled:e=>si[t].some(n=>!!e[n])};function Ds(t){for(const e in t)_e[e]={..._e[e],...t[e]}}function bu({children:t,features:e,strict:n=!1}){const[,s]=m.useState(!as(e)),r=m.useRef(void 0);if(!as(e)){const{renderer:o,...i}=e;r.current=o,Ds(i)}return m.useEffect(()=>{as(e)&&e().then(({renderer:o,...i})=>{Ds(i),r.current=o,s(!0)})},[]),d.jsx(fr.Provider,{value:{renderer:r.current,strict:n},children:t})}function as(t){return typeof t=="function"}const wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Un(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||wu.has(t)}let Ho=t=>!Un(t);function Tu(t){typeof t=="function"&&(Ho=e=>e.startsWith("on")?!Un(e):t(e))}try{Tu(require("@emotion/is-prop-valid").default)}catch{}function Su(t,e,n){const s={};for(const r in t)r==="values"&&typeof t.values=="object"||(Ho(r)||n===!0&&Un(r)||!e&&!Un(r)||t.draggable&&r.startsWith("onDrag"))&&(s[r]=t[r]);return s}const Kn=m.createContext({});function qn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function mn(t){return typeof t=="string"||Array.isArray(t)}const mr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],pr=["initial",...mr];function Gn(t){return qn(t.animate)||pr.some(e=>mn(t[e]))}function Xo(t){return!!(Gn(t)||t.variants)}function Au(t,e){if(Gn(t)){const{initial:n,animate:s}=t;return{initial:n===!1||mn(n)?n:void 0,animate:mn(s)?s:void 0}}return t.inherit!==!1?e:{}}function Cu(t){const{initial:e,animate:n}=Au(t,m.useContext(Kn));return m.useMemo(()=>({initial:e,animate:n}),[ri(e),ri(n)])}function ri(t){return Array.isArray(t)?t.join(" "):t}const pn={};function Pu(t){for(const e in t)pn[e]=t[e],Zs(e)&&(pn[e].isCSSVariable=!0)}function Yo(t,{layout:e,layoutId:n}){return Ge.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!pn[t]||t==="opacity")}const ju={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ku=qe.length;function Mu(t,e,n){let s="",r=!0;for(let o=0;o<ku;o++){const i=qe[o],a=t[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=zo(a,lr[i]);if(!c){r=!1;const l=ju[i]||i;s+=`${l}(${u}) `}n&&(e[i]=u)}}return s=s.trim(),n?s=n(e,r?"":s):r&&(s="none"),s}function gr(t,e,n){const{style:s,vars:r,transformOrigin:o}=t;let i=!1,a=!1;for(const c in e){const u=e[c];if(Ge.has(c)){i=!0;continue}else if(Zs(c)){r[c]=u;continue}else{const l=zo(u,lr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(e.transform||(i||n?s.transform=Mu(e,t.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:l=0}=o;s.transformOrigin=`${c} ${u} ${l}`}}const yr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Jo(t,e,n){for(const s in e)!Tt(e[s])&&!Yo(s,n)&&(t[s]=e[s])}function Eu({transformTemplate:t},e){return m.useMemo(()=>{const n=yr();return gr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Du(t,e){const n=t.style||{},s={};return Jo(s,n,t),Object.assign(s,Eu(t,e)),s}function Nu(t,e){const n={},s=Du(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=s,n}const Ru={offset:"stroke-dashoffset",array:"stroke-dasharray"},Vu={offset:"strokeDashoffset",array:"strokeDasharray"};function Iu(t,e,n=1,s=0,r=!0){t.pathLength=1;const o=r?Ru:Vu;t[o.offset]=z.transform(-s);const i=z.transform(e),a=z.transform(n);t[o.array]=`${i} ${a}`}function Zo(t,{attrX:e,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(gr(t,a,u),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:f}=t;h.transform&&(f.transform=h.transform,delete h.transform),(f.transform||h.transformOrigin)&&(f.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete h.transformBox),e!==void 0&&(h.x=e),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Iu(h,r,o,i,!1)}const Qo=()=>({...yr(),attrs:{}}),ta=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Ou(t,e,n,s){const r=m.useMemo(()=>{const o=Qo();return Zo(o,e,ta(s),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Jo(o,t.style,t),r.style={...o,...r.style}}return r}const Lu=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function xr(t){return typeof t!="string"||t.includes("-")?!1:!!(Lu.indexOf(t)>-1||/[A-Z]/u.test(t))}function Fu(t,e,n,{latestValues:s},r,o=!1){const a=(xr(t)?Ou:Nu)(e,s,r,t),c=Su(e,typeof t=="string",o),u=t!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=e,h=m.useMemo(()=>Tt(l)?l.get():l,[l]);return m.createElement(t,{...u,children:h})}function ii(t){const e=[{},{}];return t?.values.forEach((n,s)=>{e[0][s]=n.get(),e[1][s]=n.getVelocity()}),e}function vr(t,e,n,s){if(typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}return e}function Vn(t){return Tt(t)?t.get():t}function $u({scrapeMotionValuesFromProps:t,createRenderState:e},n,s,r){return{latestValues:Bu(n,s,r,t),renderState:e()}}function Bu(t,e,n,s){const r={},o=s(t,{});for(const f in o)r[f]=Vn(o[f]);let{initial:i,animate:a}=t;const c=Gn(t),u=Xo(t);e&&u&&!c&&t.inherit!==!1&&(i===void 0&&(i=e.initial),a===void 0&&(a=e.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const h=l?a:i;if(h&&typeof h!="boolean"&&!qn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const S=vr(t,f[g]);if(S){const{transitionEnd:T,transition:w,...y}=S;for(const v in y){let x=y[v];if(Array.isArray(x)){const M=l?x.length-1:0;x=x[M]}x!==null&&(r[v]=x)}for(const v in T)r[v]=T[v]}}}return r}const ea=t=>(e,n)=>{const s=m.useContext(Kn),r=m.useContext(Wn),o=()=>$u(t,e,s,r);return n?o():_s(o)};function br(t,e,n){const{style:s}=t,r={};for(const o in s)(Tt(s[o])||e.style&&Tt(e.style[o])||Yo(o,t)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const zu=ea({scrapeMotionValuesFromProps:br,createRenderState:yr});function na(t,e,n){const s=br(t,e,n);for(const r in t)if(Tt(t[r])||Tt(e[r])){const o=qe.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=t[r]}return s}const Uu=ea({scrapeMotionValuesFromProps:na,createRenderState:Qo}),_u=Symbol.for("motionComponentSymbol");function Oe(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Wu(t,e,n){return m.useCallback(s=>{s&&t.onMount&&t.onMount(s),e&&(s?e.mount(s):e.unmount()),n&&(typeof n=="function"?n(s):Oe(n)&&(n.current=s))},[e])}const wr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Ku="framerAppearId",sa="data-"+wr(Ku),ra=m.createContext({});function qu(t,e,n,s,r){const{visualElement:o}=m.useContext(Kn),i=m.useContext(fr),a=m.useContext(Wn),c=m.useContext(hr).reducedMotion,u=m.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const l=u.current,h=m.useContext(ra);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Gu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[sa],S=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return eo(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),S.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!S.current&&l.animationState&&l.animationState.animateChanges(),S.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),S.current=!1),l.enteringChildren=void 0)}),l}function Gu(t,e,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:ia(t.parent)),t.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Oe(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function ia(t){if(t)return t.options.allowProjection!==!1?t.projection:ia(t.parent)}function In(t,{forwardMotionProps:e=!1}={},n,s){n&&Ds(n);const r=xr(t)?Uu:zu;function o(a,c){let u;const l={...m.useContext(hr),...a,layoutId:Hu(a)},{isStatic:h}=l,f=Cu(a),g=r(a,h);if(!h&&Ws){Xu(l,n);const S=Yu(l);u=S.MeasureLayout,f.visualElement=qu(t,g,l,s,S.ProjectionNode)}return d.jsxs(Kn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Fu(t,a,Wu(g,f.visualElement,c),g,h,e)]})}o.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const i=m.forwardRef(o);return i[_u]=t,i}function Hu({layoutId:t}){const e=m.useContext(Us).id;return e&&t!==void 0?e+"-"+t:t}function Xu(t,e){const n=m.useContext(fr).strict;if(process.env.NODE_ENV!=="production"&&e&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";t.ignoreStrict?We(!1,s,"lazy-strict-mode"):Xt(!1,s,"lazy-strict-mode")}}function Yu(t){const{drag:e,layout:n}=_e;if(!e&&!n)return{};const s={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Ju(t,e){if(typeof Proxy>"u")return In;const n=new Map,s=(o,i)=>In(o,i,t,e),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Xs(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,In(i,void 0,t,e)),n.get(i))})}function oa({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}function Zu({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Qu(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function cs(t){return t===void 0||t===1}function Ns({scale:t,scaleX:e,scaleY:n}){return!cs(t)||!cs(e)||!cs(n)}function Se(t){return Ns(t)||aa(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function aa(t){return oi(t.x)||oi(t.y)}function oi(t){return t&&t!=="0%"}function _n(t,e,n){const s=t-n,r=e*s;return n+r}function ai(t,e,n,s,r){return r!==void 0&&(t=_n(t,r,s)),_n(t,n,s)+e}function Rs(t,e=0,n=1,s,r){t.min=ai(t.min,e,n,s,r),t.max=ai(t.max,e,n,s,r)}function ca(t,{x:e,y:n}){Rs(t.x,e.translate,e.scale,e.originPoint),Rs(t.y,n.translate,n.scale,n.originPoint)}const ci=.999999999999,li=1.0000000000001;function td(t,e,n,s=!1){const r=n.length;if(!r)return;e.x=e.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Fe(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(e.x*=i.x.scale,e.y*=i.y.scale,ca(t,i)),s&&Se(o.latestValues)&&Fe(t,o.latestValues))}e.x<li&&e.x>ci&&(e.x=1),e.y<li&&e.y>ci&&(e.y=1)}function Le(t,e){t.min=t.min+e,t.max=t.max+e}function ui(t,e,n,s,r=.5){const o=ut(t.min,t.max,r);Rs(t,e,n,o,s)}function Fe(t,e){ui(t.x,e.x,e.scaleX,e.scale,e.originX),ui(t.y,e.y,e.scaleY,e.scale,e.originY)}function la(t,e){return oa(Qu(t.getBoundingClientRect(),e))}function ed(t,e,n){const s=la(t,n),{scroll:r}=e;return r&&(Le(s.x,r.offset.x),Le(s.y,r.offset.y)),s}const di=()=>({translate:0,scale:1,origin:0,originPoint:0}),$e=()=>({x:di(),y:di()}),hi=()=>({min:0,max:0}),ft=()=>({x:hi(),y:hi()}),Vs={current:null},ua={current:!1};function nd(){if(ua.current=!0,!!Ws)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Vs.current=t.matches;t.addEventListener("change",e),e()}else Vs.current=!1}const sd=new WeakMap;function rd(t,e,n){for(const s in e){const r=e[s],o=n[s];if(Tt(r))t.addValue(s,r);else if(Tt(o))t.addValue(s,Ue(r,{owner:t}));else if(o!==r)if(t.hasValue(s)){const i=t.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=t.getStaticValue(s);t.addValue(s,Ue(i!==void 0?i:r,{owner:t}))}}for(const s in n)e[s]===void 0&&t.removeValue(s);return e}const fi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class id{scrapeMotionValuesFromProps(e,n,s){return{}}constructor({parent:e,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ar,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=jt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ct.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=e,this.props=n,this.presenceContext=s,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Gn(n),this.isVariantNode=Xo(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:l,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const g=h[f];c[f]!==void 0&&Tt(g)&&g.set(c[f])}}mount(e){this.current=e,sd.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),ua.current||nd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Vs.current,process.env.NODE_ENV!=="production"&&Xs(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),de(this.notifyUpdate),de(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const s=Ge.has(e);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[e]=i,this.props.onUpdate&&ct.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in _e){const n=_e[e];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[e]&&r&&s(this.props)&&(this.features[e]=new r(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<fi.length;s++){const r=fi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=e[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=rd(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const s=this.values.get(e);n!==s&&(s&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let s=this.values.get(e);return s===void 0&&n!==void 0&&(s=Ue(n===null?void 0:n,{owner:this}),this.addValue(e,s)),s}readValue(e,n){let s=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return s!=null&&(typeof s=="string"&&(no(s)||ro(s))?s=parseFloat(s):!hu(s)&&he.test(n)&&(s=Bo(e,n)),this.setBaseTarget(e,Tt(s)?s.get():s)),Tt(s)?s.get():s}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=vr(this.props,n,this.presenceContext?.custom);o&&(s=o[e])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Tt(r)?r:this.initialValues[e]!==void 0&&s===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new Hs),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){ur.render(this.render)}}class da extends id{constructor(){super(...arguments),this.KeyframeResolver=tu}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:s}){delete n[e],delete s[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Tt(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function ha(t,{style:e,vars:n},s,r){const o=t.style;let i;for(i in e)o[i]=e[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function od(t){return window.getComputedStyle(t)}class ad extends da{constructor(){super(...arguments),this.type="html",this.renderInstance=ha}readValueFromInstance(e,n){if(Ge.has(n))return this.projection?.isProjecting?As(n):xl(e,n);{const s=od(e),r=(Zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return la(e,n)}build(e,n,s){gr(e,n,s.transformTemplate)}scrapeMotionValuesFromProps(e,n,s){return br(e,n,s)}}const fa=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function cd(t,e,n,s){ha(t,e,void 0,s);for(const r in e.attrs)t.setAttribute(fa.has(r)?r:wr(r),e.attrs[r])}class ld extends da{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Ge.has(n)){const s=$o(n);return s&&s.default||0}return n=fa.has(n)?n:wr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,s){return na(e,n,s)}build(e,n,s){Zo(e,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(e,n,s,r){cd(e,n,s,r)}mount(e){this.isSVGTag=ta(e.tagName),super.mount(e)}}const ma=(t,e)=>xr(t)?new ld(e):new ad(e,{allowProjection:t!==m.Fragment});function ze(t,e,n){const s=t.getProps();return vr(s,e,n!==void 0?n:s.custom,t)}const Is=t=>Array.isArray(t);function ud(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Ue(n))}function dd(t){return Is(t)?t[t.length-1]||0:t}function hd(t,e){const n=ze(t,e);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=dd(o[i]);ud(t,i,a)}}function fd(t){return!!(Tt(t)&&t.add)}function Os(t,e){const n=t.getValue("willChange");if(fd(n))return n.add(e);if(!n&&Yt.WillChange){const s=new Yt.WillChange("auto");t.addValue("willChange",s),s.add(e)}}function pa(t){return t.props[sa]}const md=t=>t!==null;function pd(t,{repeat:e,repeatType:n="loop"},s){const r=t.filter(md),o=e&&n!=="loop"&&e%2===1?0:r.length-1;return r[o]}const gd={type:"spring",stiffness:500,damping:25,restSpeed:10},yd=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),xd={type:"keyframes",duration:.8},vd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},bd=(t,{keyframes:e})=>e.length>2?xd:Ge.has(t)?t.startsWith("scale")?yd(e[1]):gd:vd;function wd({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const Tr=(t,e,n,s={},r,o)=>i=>{const a=cr(s,t)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-$t(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-u,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:r};wd(a)||Object.assign(l,bd(t,l)),l.duration&&(l.duration=$t(l.duration)),l.repeatDelay&&(l.repeatDelay=$t(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(Ms(l),l.delay===0&&(h=!0)),(Yt.instantAnimations||Yt.skipAnimations)&&(h=!0,Ms(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&e.get()!==void 0){const f=pd(l.keyframes,a);if(f!==void 0){ct.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new or(l):new zl(l)};function Td({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,s}function ga(t,e,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:i,...a}=e;s&&(o=s);const c=[],u=r&&t.animationState&&t.animationState.getState()[r];for(const l in a){const h=t.getValue(l,t.latestValues[l]??null),f=a[l];if(f===void 0||u&&Td(u,l))continue;const g={delay:n,...cr(o||{},l)},S=h.get();if(S!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===S&&!g.velocity)continue;let T=!1;if(window.MotionHandoffAnimation){const y=pa(t);if(y){const v=window.MotionHandoffAnimation(y,l,ct);v!==null&&(g.startTime=v,T=!0)}}Os(t,l),h.start(Tr(l,h,f,t.shouldReduceMotion&&Oo.has(l)?{type:!1}:g,t,T));const w=h.animation;w&&c.push(w)}return i&&Promise.all(c).then(()=>{ct.update(()=>{i&&hd(t,i)})}),c}function ya(t,e,n,s=0,r=1){const o=Array.from(t).sort((u,l)=>u.sortNodePosition(l)).indexOf(e),i=t.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Ls(t,e,n={}){const s=ze(t,e,n.type==="exit"?t.presenceContext?.custom:void 0);let{transition:r=t.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(ga(t,s,n)):()=>Promise.resolve(),i=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return Sd(t,e,c,u,l,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,u]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Sd(t,e,n=0,s=0,r=0,o=1,i){const a=[];for(const c of t.variantChildren)c.notify("AnimationStart",e),a.push(Ls(c,e,{...i,delay:n+(typeof s=="function"?0:s)+ya(t.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(a)}function Ad(t,e,n={}){t.notify("AnimationStart",e);let s;if(Array.isArray(e)){const r=e.map(o=>Ls(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Ls(t,e,n);else{const r=typeof e=="function"?ze(t,e,n.custom):e;s=Promise.all(ga(t,r,n))}return s.then(()=>{t.notify("AnimationComplete",e)})}function xa(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let s=0;s<n;s++)if(e[s]!==t[s])return!1;return!0}const Cd=pr.length;function va(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?va(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Cd;n++){const s=pr[n],r=t.props[s];(mn(r)||r===!1)&&(e[s]=r)}return e}const Pd=[...mr].reverse(),jd=mr.length;function kd(t){return e=>Promise.all(e.map(({animation:n,options:s})=>Ad(t,n,s)))}function Md(t){let e=kd(t),n=mi(),s=!0;const r=c=>(u,l)=>{const h=ze(t,l,c==="exit"?t.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...S}=h;u={...u,...S,...g}}return u};function o(c){e=c(t)}function i(c){const{props:u}=t,l=va(t.parent)||{},h=[],f=new Set;let g={},S=1/0;for(let w=0;w<jd;w++){const y=Pd[w],v=n[y],x=u[y]!==void 0?u[y]:l[y],M=mn(x),j=y===c?v.isActive:null;j===!1&&(S=w);let E=x===l[y]&&x!==u[y]&&M;if(E&&s&&t.manuallyAnimateOnMount&&(E=!1),v.protectedKeys={...g},!v.isActive&&j===null||!x&&!v.prevProp||qn(x)||typeof x=="boolean")continue;const D=Ed(v.prevProp,x);let A=D||y===c&&v.isActive&&!E&&M||w>S&&M,F=!1;const I=Array.isArray(x)?x:[x];let X=I.reduce(r(y),{});j===!1&&(X={});const{prevResolvedValues:Y={}}=v,q={...Y,...X},G=J=>{A=!0,f.has(J)&&(F=!0,f.delete(J)),v.needsAnimating[J]=!0;const nt=t.getValue(J);nt&&(nt.liveStyle=!1)};for(const J in q){const nt=X[J],ot=Y[J];if(g.hasOwnProperty(J))continue;let st=!1;Is(nt)&&Is(ot)?st=!xa(nt,ot):st=nt!==ot,st?nt!=null?G(J):f.add(J):nt!==void 0&&f.has(J)?G(J):v.protectedKeys[J]=!0}v.prevProp=x,v.prevResolvedValues=X,v.isActive&&(g={...g,...X}),s&&t.blockInitialAnimation&&(A=!1);const it=E&&D;A&&(!it||F)&&h.push(...I.map(J=>{const nt={type:y};if(typeof J=="string"&&s&&!it&&t.manuallyAnimateOnMount&&t.parent){const{parent:ot}=t,st=ze(ot,J);if(ot.enteringChildren&&st){const{delayChildren:Jt}=st.transition||{};nt.delay=ya(ot.enteringChildren,t,Jt)}}return{animation:J,options:nt}}))}if(f.size){const w={};if(typeof u.initial!="boolean"){const y=ze(t,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const v=t.getBaseTarget(y),x=t.getValue(y);x&&(x.liveStyle=!0),w[y]=v??null}),h.push({animation:w})}let T=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(T=!1),s=!1,T?e(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();t.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const h in n)n[h].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=mi()}}}function Ed(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!xa(e,t):!1}function we(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function mi(){return{animate:we(!0),whileInView:we(),whileHover:we(),whileTap:we(),whileDrag:we(),whileFocus:we(),exit:we()}}class fe{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Dd extends fe{constructor(e){super(e),e.animationState||(e.animationState=Md(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();qn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Nd=0;class Rd extends fe{constructor(){super(...arguments),this.id=Nd++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===s)return;const r=this.node.animationState.setActive("exit",!e);n&&!e&&r.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const ba={animation:{Feature:Dd},exit:{Feature:Rd}};function gn(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function bn(t){return{point:{x:t.pageX,y:t.pageY}}}const Vd=t=>e=>dr(e)&&t(e,bn(e));function on(t,e,n,s){return gn(t,e,Vd(n),s)}const wa=1e-4,Id=1-wa,Od=1+wa,Ta=.01,Ld=0-Ta,Fd=0+Ta;function At(t){return t.max-t.min}function $d(t,e,n){return Math.abs(t-e)<=n}function pi(t,e,n,s=.5){t.origin=s,t.originPoint=ut(e.min,e.max,t.origin),t.scale=At(n)/At(e),t.translate=ut(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Id&&t.scale<=Od||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ld&&t.translate<=Fd||isNaN(t.translate))&&(t.translate=0)}function an(t,e,n,s){pi(t.x,e.x,n.x,s?s.originX:void 0),pi(t.y,e.y,n.y,s?s.originY:void 0)}function gi(t,e,n){t.min=n.min+e.min,t.max=t.min+At(e)}function Bd(t,e,n){gi(t.x,e.x,n.x),gi(t.y,e.y,n.y)}function yi(t,e,n){t.min=e.min-n.min,t.max=t.min+At(e)}function cn(t,e,n){yi(t.x,e.x,n.x),yi(t.y,e.y,n.y)}function Dt(t){return[t("x"),t("y")]}const Sa=({current:t})=>t?t.ownerDocument.defaultView:null,xi=(t,e)=>Math.abs(t-e);function zd(t,e){const n=xi(t.x,e.x),s=xi(t.y,e.y);return Math.sqrt(n**2+s**2)}class Aa{constructor(e,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=us(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,S=zd(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!S)return;const{point:T}=f,{timestamp:w}=vt;this.history.push({...T,timestamp:w});const{onStart:y,onMove:v}=this.handlers;g||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=ls(g,this.transformPagePoint),ct.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:S,onSessionEnd:T,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=us(f.type==="pointercancel"?this.lastMoveEventInfo:ls(g,this.transformPagePoint),this.history);this.startEvent&&S&&S(f,y),T&&T(f,y)},!dr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=bn(e),c=ls(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=vt;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(e,us(c,this.history)),this.removeListeners=yn(on(this.contextWindow,"pointermove",this.handlePointerMove),on(this.contextWindow,"pointerup",this.handlePointerUp),on(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),de(this.updatePoint)}}function ls(t,e){return e?{point:e(t.point)}:t}function vi(t,e){return{x:t.x-e.x,y:t.y-e.y}}function us({point:t},e){return{point:t,delta:vi(t,Ca(e)),offset:vi(t,Ud(e)),velocity:_d(e,.1)}}function Ud(t){return t[0]}function Ca(t){return t[t.length-1]}function _d(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,s=null;const r=Ca(t);for(;n>=0&&(s=t[n],!(r.timestamp-s.timestamp>$t(e)));)n--;if(!s)return{x:0,y:0};const o=Nt(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function Wd(t,{min:e,max:n},s){return e!==void 0&&t<e?t=s?ut(e,t,s.min):Math.max(t,e):n!==void 0&&t>n&&(t=s?ut(n,t,s.max):Math.min(t,n)),t}function bi(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function Kd(t,{top:e,left:n,bottom:s,right:r}){return{x:bi(t.x,n,r),y:bi(t.y,e,s)}}function wi(t,e){let n=e.min-t.min,s=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,s]=[s,n]),{min:n,max:s}}function qd(t,e){return{x:wi(t.x,e.x),y:wi(t.y,e.y)}}function Gd(t,e){let n=.5;const s=At(t),r=At(e);return r>s?n=dn(e.min,e.max-s,t.min):s>r&&(n=dn(t.min,t.max-r,e.min)),Ht(0,1,n)}function Hd(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Fs=.35;function Xd(t=Fs){return t===!1?t=0:t===!0&&(t=Fs),{x:Ti(t,"left","right"),y:Ti(t,"top","bottom")}}function Ti(t,e,n){return{min:Si(t,e),max:Si(t,n)}}function Si(t,e){return typeof t=="number"?t:t[e]||0}const Yd=new WeakMap;class Jd{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(bn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:S,onDragStart:T}=this.getProps();if(g&&!S&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ru(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Dt(y=>{let v=this.getAxisMotionValue(y).get()||0;if(Wt.test(v)){const{projection:x}=this.visualElement;if(x&&x.layout){const M=x.layout.layoutBox[y];M&&(v=At(M)*(parseFloat(v)/100))}}this.originPoint[y]=v}),T&&ct.postRender(()=>T(h,f)),Os(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:S,onDirectionLock:T,onDrag:w}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(S&&this.currentDirection===null){this.currentDirection=Zd(y),this.currentDirection!==null&&T&&T(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(h,f)},c=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f,this.stop(h,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Dt(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new Aa(e,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:Sa(this.visualElement)})}stop(e,n){const s=e||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ct.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,s){const{drag:r}=this.getProps();if(!s||!En(e,r,this.currentDirection))return;const o=this.getAxisMotionValue(e);let i=this.originPoint[e]+s[e];this.constraints&&this.constraints[e]&&(i=Wd(i,this.constraints[e],this.elastic[e])),o.set(i)}resolveConstraints(){const{dragConstraints:e,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Oe(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&s?this.constraints=Kd(s.layoutBox,e):this.constraints=!1,this.elastic=Xd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Dt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Hd(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Oe(e))return!1;const s=e.current;Xt(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=ed(s,r.root,this.visualElement.getTransformPagePoint());let i=qd(r.layout.layoutBox,o);if(n){const a=n(Zu(i));this.hasMutatedConstraints=!!a,a&&(i=oa(a))}return i}startAnimation(e){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Dt(l=>{if(!En(l,n,this.currentDirection))return;let h=c&&c[l]||{};i&&(h={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,S={type:"inertia",velocity:s?e[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,S)});return Promise.all(u).then(a)}startAxisValueAnimation(e,n){const s=this.getAxisMotionValue(e);return Os(this.visualElement,e),s.start(Tr(e,s,0,n,this.visualElement,!1))}stopAnimation(){Dt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Dt(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(e,(s.initial?s.initial[e]:void 0)||0)}snapToCursor(e){Dt(n=>{const{drag:s}=this.getProps();if(!En(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(e[n]-ut(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Oe(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Dt(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Gd({min:c,max:c},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Dt(i=>{if(!En(i,e,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(ut(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Yd.set(this.visualElement,this);const e=this.visualElement.current,n=on(e,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Oe(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),ct.read(s);const i=gn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Dt(l=>{const h=this.getAxisMotionValue(l);h&&(this.originPoint[l]+=c[l].translate,h.set(h.get()+c[l].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=Fs,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function En(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Zd(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Qd extends fe{constructor(e){super(e),this.removeGroupControls=Rt,this.removeListeners=Rt,this.controls=new Jd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Rt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ai=t=>(e,n)=>{t&&ct.postRender(()=>t(e,n))};class th extends fe{constructor(){super(...arguments),this.removePointerDownListener=Rt}onPointerDown(e){this.session=new Aa(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Sa(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ai(e),onStart:Ai(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ct.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=on(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const On={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ci(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const nn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ci(t,e.target.x),s=Ci(t,e.target.y);return`${n}% ${s}%`}},eh={correct:(t,{treeScale:e,projectionDelta:n})=>{const s=t,r=he.parse(t);if(r.length>5)return s;const o=he.createTransformer(t),i=typeof r[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;r[0+i]/=a,r[1+i]/=c;const u=ut(a,c,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let ds=!1;class nh extends m.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=e;Pu(sh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),ds&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),On.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,ds=!0,r||e.layoutDependency!==n||n===void 0||e.isPresent!==o?i.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?i.promote():i.relegate()||ct.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ur.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=e;ds=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Pa(t){const[e,n]=Go(),s=m.useContext(Us);return d.jsx(nh,{...t,layoutGroup:s,switchLayoutGroup:m.useContext(ra),isPresent:e,safeToRemove:n})}const sh={borderRadius:{...nn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:nn,borderTopRightRadius:nn,borderBottomLeftRadius:nn,borderBottomRightRadius:nn,boxShadow:eh};function rh(t,e,n){const s=Tt(t)?t:Ue(t);return s.start(Tr("",s,e,n)),s.animation}const ih=(t,e)=>t.depth-e.depth;class oh{constructor(){this.children=[],this.isDirty=!1}add(e){Ks(this.children,e),this.isDirty=!0}remove(e){qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(ih),this.isDirty=!1,this.children.forEach(e)}}function ah(t,e){const n=jt.now(),s=({timestamp:r})=>{const o=r-n;o>=e&&(de(s),t(o-e))};return ct.setup(s,!0),()=>de(s)}const ja=["TopLeft","TopRight","BottomLeft","BottomRight"],ch=ja.length,Pi=t=>typeof t=="string"?parseFloat(t):t,ji=t=>typeof t=="number"||z.test(t);function lh(t,e,n,s,r,o){r?(t.opacity=ut(0,n.opacity??1,uh(s)),t.opacityExit=ut(e.opacity??1,0,dh(s))):o&&(t.opacity=ut(e.opacity??1,n.opacity??1,s));for(let i=0;i<ch;i++){const a=`border${ja[i]}Radius`;let c=ki(e,a),u=ki(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||ji(c)===ji(u)?(t[a]=Math.max(ut(Pi(c),Pi(u),s),0),(Wt.test(u)||Wt.test(c))&&(t[a]+="%")):t[a]=u}(e.rotate||n.rotate)&&(t.rotate=ut(e.rotate||0,n.rotate||0,s))}function ki(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const uh=ka(0,.5,fo),dh=ka(.5,.95,Rt);function ka(t,e,n){return s=>s<t?0:s>e?1:n(dn(t,e,s))}function Mi(t,e){t.min=e.min,t.max=e.max}function Et(t,e){Mi(t.x,e.x),Mi(t.y,e.y)}function Ei(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Di(t,e,n,s,r){return t-=e,t=_n(t,1/n,s),r!==void 0&&(t=_n(t,1/r,s)),t}function hh(t,e=0,n=1,s=.5,r,o=t,i=t){if(Wt.test(e)&&(e=parseFloat(e),e=ut(i.min,i.max,e/100)-i.min),typeof e!="number")return;let a=ut(o.min,o.max,s);t===o&&(a-=e),t.min=Di(t.min,e,n,a,r),t.max=Di(t.max,e,n,a,r)}function Ni(t,e,[n,s,r],o,i){hh(t,e[n],e[s],e[r],e.scale,o,i)}const fh=["x","scaleX","originX"],mh=["y","scaleY","originY"];function Ri(t,e,n,s){Ni(t.x,e,fh,n?n.x:void 0,s?s.x:void 0),Ni(t.y,e,mh,n?n.y:void 0,s?s.y:void 0)}function Vi(t){return t.translate===0&&t.scale===1}function Ma(t){return Vi(t.x)&&Vi(t.y)}function Ii(t,e){return t.min===e.min&&t.max===e.max}function ph(t,e){return Ii(t.x,e.x)&&Ii(t.y,e.y)}function Oi(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ea(t,e){return Oi(t.x,e.x)&&Oi(t.y,e.y)}function Li(t){return At(t.x)/At(t.y)}function Fi(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class gh{constructor(){this.members=[]}add(e){Ks(this.members,e),e.scheduleRender()}remove(e){if(qs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(r=>e===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(e,n){const s=this.lead;if(e!==s&&(this.prevLead=s,this.lead=e,e.show(),s)){s.instance&&s.scheduleRender(),e.scheduleRender(),e.resumeFrom=s,n&&(e.resumeFrom.preserveOpacity=!0),s.snapshot&&(e.snapshot=s.snapshot,e.snapshot.latestValues=s.animationValues||s.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:r}=e.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:s}=e;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function yh(t,e,n){let s="";const r=t.x.translate/e.x,o=t.y.translate/e.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(e.x!==1||e.y!==1)&&(s+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:u,rotate:l,rotateX:h,rotateY:f,skewX:g,skewY:S}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),h&&(s+=`rotateX(${h}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),S&&(s+=`skewY(${S}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const hs=["","X","Y","Z"],xh=1e3;let vh=0;function fs(t,e,n,s){const{latestValues:r}=e;r[t]&&(n[t]=r[t],e.setStaticValue(t,0),s&&(s[t]=0))}function Da(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=pa(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ct,!(r||o))}const{parent:s}=t;s&&!s.hasCheckedOptimisedAppear&&Da(s)}function Na({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=e?.()){this.id=vh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Th),this.nodes.forEach(Ph),this.nodes.forEach(jh),this.nodes.forEach(Sh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new oh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Hs),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const c=this.eventHandlers.get(i);c&&c.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=qo(i)&&!uu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let l,h=0;const f=()=>this.root.updateBlockedByResize=!1;ct.read(()=>{h=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=ah(f,250),On.hasAnimatedSinceResize&&(On.hasAnimatedSinceResize=!1,this.nodes.forEach(zi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:h,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const S=this.options.transition||u.getDefaultTransition()||Nh,{onLayoutAnimationStart:T,onLayoutAnimationComplete:w}=u.getProps(),y=!this.targetLayout||!Ea(this.targetLayout,g),v=!h&&f;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const x={...cr(S,"layout"),onPlay:T,onComplete:w};(u.shouldReduceMotion||this.options.layoutRoot)&&(x.delay=0,x.type=!1),this.startAnimation(x),this.setAnimationOrigin(l,v)}else h||zi(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),de(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(kh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Da(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const h=this.path[l];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach($i);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bi);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Ch),this.nodes.forEach(bh),this.nodes.forEach(wh)):this.nodes.forEach(Bi),this.clearAllSnapshots();const a=jt.now();vt.delta=Ht(0,1e3/60,a-vt.timestamp),vt.timestamp=a,vt.isProcessing=!0,es.update.process(vt),es.preRender.process(vt),es.render.process(vt),vt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ur.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ah),this.sharedNodes.forEach(Mh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ct.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ct.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!At(this.snapshot.measuredBox.x)&&!At(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ft(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const c=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Ma(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Se(this.latestValues)||l)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return i&&(c=this.removeTransform(c)),Rh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ft();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Vh))){const{scroll:u}=this.root;u&&(Le(a.x,u.offset.x),Le(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ft();if(Et(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:h}=u;u!==this.root&&l&&h.layoutScroll&&(l.wasRoot&&Et(a,i),Le(a.x,l.offset.x),Le(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=ft();Et(c,i);for(let u=0;u<this.path.length;u++){const l=this.path[u];!a&&l.options.layoutScroll&&l.scroll&&l!==l.root&&Fe(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),Se(l.latestValues)&&Fe(c,l.latestValues)}return Se(this.latestValues)&&Fe(c,this.latestValues),c}removeTransform(i){const a=ft();Et(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Se(u.latestValues))continue;Ns(u.latestValues)&&u.updateSnapshot();const l=ft(),h=u.measurePageBox();Et(l,h),Ri(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return Se(this.latestValues)&&Ri(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==vt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:l,layoutId:h}=this.options;if(!(!this.layout||!(l||h))){if(this.resolvedRelativeTargetAt=vt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ft(),this.targetWithTransforms=ft()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Bd(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Et(this.target,this.layout.layoutBox),ca(this.target,this.targetDelta)):Et(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const f=this.getClosestProjectingParent();f&&!!f.resumingFrom==!!this.resumingFrom&&!f.options.layoutScroll&&f.target&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.target,f.target),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ns(this.parent.latestValues)||aa(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let c=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===vt.timestamp&&(c=!1),c)return;const{layout:u,layoutId:l}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||l))return;Et(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;td(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ft());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ei(this.prevProjectionDelta.x,this.projectionDelta.x),Ei(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Fi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Fi(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=$e(),this.projectionDelta=$e(),this.projectionDeltaWithTransform=$e()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=$e();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ft(),g=c?c.source:void 0,S=this.layout?this.layout.source:void 0,T=g!==S,w=this.getStack(),y=!w||w.members.length<=1,v=!!(T&&!y&&this.options.crossfade===!0&&!this.path.some(Dh));this.animationProgress=0;let x;this.mixTargetDelta=M=>{const j=M/1e3;Ui(h.x,i.x,j),Ui(h.y,i.y,j),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Eh(this.relativeTarget,this.relativeTargetOrigin,f,j),x&&ph(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=ft()),Et(x,this.relativeTarget)),T&&(this.animationValues=l,lh(l,u,this.latestValues,j,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=j},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(de(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ct.update(()=>{On.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ue(0)),this.currentAnimation=rh(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(xh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:c,layout:u,latestValues:l}=i;if(!(!a||!c||!u)){if(this!==i&&this.layout&&u&&Ra(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||ft();const h=At(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=At(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Et(a,c),Fe(a,l),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new gh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:c}={}){const u=this.getStack();u&&u.promote(this,c),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:c}=i;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const u={};c.z&&fs("z",i,u,this.animationValues);for(let l=0;l<hs.length;l++)fs(`rotate${hs[l]}`,i,u,this.animationValues),fs(`skew${hs[l]}`,i,u,this.animationValues);i.render();for(const l in u)i.setStaticValue(l,u[l]),this.animationValues&&(this.animationValues[l]=u[l]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=Vn(a?.pointerEvents)||"",i.transform=c?c(this.latestValues,""):"none";return}const u=this.getLead();if(!this.projectionDelta||!this.layout||!u.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=Vn(a?.pointerEvents)||""),this.hasProjected&&!Se(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=yh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(h=c(l,h)),i.transform=h;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?l.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:l.opacityExit:i.opacity=u===this?l.opacity!==void 0?l.opacity:"":l.opacityExit!==void 0?l.opacityExit:0;for(const S in pn){if(l[S]===void 0)continue;const{correct:T,applyTo:w,isCSSVariable:y}=pn[S],v=h==="none"?l[S]:T(l[S],u);if(w){const x=w.length;for(let M=0;M<x;M++)i[w[M]]=v}else y?this.options.visualElement.renderState.vars[S]=v:i[S]=v}this.options.layoutId&&(i.pointerEvents=u===this?Vn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach($i),this.root.sharedNodes.clear()}}}function bh(t){t.updateLayout()}function wh(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:r}=t.options,o=e.source!==t.layout.source;r==="size"?Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(h);h.min=n[l].min,h.max=h.min+f}):Ra(r,e.layoutBox,n)&&Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(n[l]);h.max=h.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[l].max=t.relativeTarget[l].min+f)});const i=$e();an(i,n,e.layoutBox);const a=$e();o?an(a,t.applyTransform(s,!0),e.measuredBox):an(a,n,e.layoutBox);const c=!Ma(i);let u=!1;if(!t.resumeFrom){const l=t.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:h,layout:f}=l;if(h&&f){const g=ft();cn(g,e.layoutBox,h.layoutBox);const S=ft();cn(S,n,f.layoutBox),Ea(g,S)||(u=!0),l.options.layoutRoot&&(t.relativeTarget=S,t.relativeTargetOrigin=g,t.relativeParent=l)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Th(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Sh(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Ah(t){t.clearSnapshot()}function $i(t){t.clearMeasurements()}function Bi(t){t.isLayoutDirty=!1}function Ch(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function zi(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Ph(t){t.resolveTargetDelta()}function jh(t){t.calcProjection()}function kh(t){t.resetSkewAndRotation()}function Mh(t){t.removeLeadSnapshot()}function Ui(t,e,n){t.translate=ut(e.translate,0,n),t.scale=ut(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function _i(t,e,n,s){t.min=ut(e.min,n.min,s),t.max=ut(e.max,n.max,s)}function Eh(t,e,n,s){_i(t.x,e.x,n.x,s),_i(t.y,e.y,n.y,s)}function Dh(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Nh={duration:.45,ease:[.4,0,.1,1]},Wi=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Ki=Wi("applewebkit/")&&!Wi("chrome/")?Math.round:Rt;function qi(t){t.min=Ki(t.min),t.max=Ki(t.max)}function Rh(t){qi(t.x),qi(t.y)}function Ra(t,e,n){return t==="position"||t==="preserve-aspect"&&!$d(Li(e),Li(n),.2)}function Vh(t){return t!==t.root&&t.scroll?.wasRoot}const Ih=Na({attachResizeListener:(t,e)=>gn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ms={current:void 0},Va=Na({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ms.current){const t=new Ih({});t.mount(window),t.setOptions({layoutScroll:!0}),ms.current=t}return ms.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Oh={pan:{Feature:th},drag:{Feature:Qd,ProjectionNode:Va,MeasureLayout:Pa}};function Gi(t,e,n){const{props:s}=t;t.animationState&&s.whileHover&&t.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ct.postRender(()=>o(e,bn(e)))}class Lh extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=iu(e,(n,s)=>(Gi(this.node,s,"Start"),r=>Gi(this.node,r,"End"))))}unmount(){}}class Fh extends fe{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=yn(gn(this.node.current,"focus",()=>this.onFocus()),gn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Hi(t,e,n){const{props:s}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&s.whileTap&&t.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ct.postRender(()=>o(e,bn(e)))}class $h extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=lu(e,(n,s)=>(Hi(this.node,s,"Start"),(r,{success:o})=>Hi(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $s=new WeakMap,ps=new WeakMap,Bh=t=>{const e=$s.get(t.target);e&&e(t)},zh=t=>{t.forEach(Bh)};function Uh({root:t,...e}){const n=t||document;ps.has(n)||ps.set(n,{});const s=ps.get(n),r=JSON.stringify(e);return s[r]||(s[r]=new IntersectionObserver(zh,{root:t,...e})),s[r]}function _h(t,e,n){const s=Uh(e);return $s.set(t,n),s.observe(t),()=>{$s.delete(t),s.unobserve(t)}}const Wh={some:0,all:1};class Kh extends fe{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=e,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:Wh[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:l,onViewportLeave:h}=this.node.getProps(),f=u?l:h;f&&f(c)};return _h(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(qh(e,n))&&this.startObserver()}unmount(){}}function qh({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Ia={inView:{Feature:Kh},tap:{Feature:$h},focus:{Feature:Fh},hover:{Feature:Lh}},Gh={layout:{ProjectionNode:Va,MeasureLayout:Pa}},Hh={...ba,...Ia,...Oh,...Gh},Xh=Ju(Hh,ma),Yh={renderer:ma,...ba,...Ia};function Sr(t,e){return In(t,e)}const Jh=Sr("button"),Dn=Sr("div"),Zh=Sr("p"),_t=Symbol.for("@arcteninc/core:originalName");function Qh(t,e){return t[_t]=e,t}function tf(t,e,n,s){if(typeof t!="function")return null;const r=t[_t];if(r){const a=e[r];if(a&&!n.has(a.name))return{fn:t,meta:a}}const o=t.name;let i;if(o&&(i=e[o],i&&!n.has(i.name)))return t[_t]=i.name,{fn:t,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=e[a],i))return t[_t]=i.name,{fn:t,meta:i}}else if(i=Object.values(e).find(c=>!n.has(c.name)),i)return t[_t]=i.name,{fn:t,meta:i};return null}function Oa(t,e){let n,s;if(!e)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{y.contains(b)&&y.removeChild(b)}},[t]),c.jsx(Ru,{isPresent:t,childRef:o,sizeRef:i,children:Xe.cloneElement(e,{ref:l})})}const Iu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const u=ar(Ou),d=f.useId();let h=!0,m=f.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const v of u.values())if(!v)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&h&&(m={...m}),f.useMemo(()=>{u.forEach((g,v)=>u.set(v,!1))},[n]),Xe.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=c.jsx(Vu,{isPresent:n,anchorX:a,root:l,children:e})),c.jsx(us.Provider,{value:m,children:e})};function Ou(){return new Map}function da(e=!0){const t=f.useContext(us);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=f.useId();f.useEffect(()=>{if(e)return r(o)},[e]);const i=f.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const Hn=e=>e.key||"";function vi(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const $u=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[u,d]=da(i),h=f.useMemo(()=>vi(e),[e]),m=i&&!u?[]:h.map(Hn),g=f.useRef(!0),v=f.useRef(h),b=ar(()=>new Map),[y,x]=f.useState(h),[j,k]=f.useState(h);vo(()=>{g.current=!1,v.current=h;for(let B=0;B<j.length;B++){const O=Hn(j[B]);m.includes(O)?b.delete(O):b.get(O)!==!0&&b.set(O,!1)}},[j,m.length,m.join("-")]);const N=[];if(h!==y){let B=[...h];for(let O=0;O<j.length;O++){const E=j[O],F=Hn(E);m.includes(F)||(B.splice(O,0,E),N.push(E))}return o==="wait"&&N.length&&(B=N),k(vi(B)),x(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&j.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:R}=f.useContext(or);return c.jsx(c.Fragment,{children:j.map(B=>{const O=Hn(B),E=i&&!u?!1:h===j||m.includes(O),F=()=>{if(b.has(O))b.set(O,!0);else return;let S=!0;b.forEach(M=>{M||(S=!1)}),S&&(R?.(),k(v.current),i&&d?.(),s&&s())};return c.jsx(Iu,{isPresent:E,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:E?void 0:F,anchorX:a,children:B},O)})})},Nr=f.createContext({strict:!1}),wi={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},sn={};for(const e in wi)sn[e]={isEnabled:t=>wi[e].some(n=>!!t[n])};function Ys(e){for(const t in e)sn[t]={...sn[t],...e[t]}}function Lu({children:e,features:t,strict:n=!1}){const[,s]=f.useState(!Cs(t)),r=f.useRef(void 0);if(!Cs(t)){const{renderer:o,...i}=t;r.current=o,Ys(i)}return f.useEffect(()=>{Cs(t)&&t().then(({renderer:o,...i})=>{Ys(i),r.current=o,s(!0)})},[]),c.jsx(Nr.Provider,{value:{renderer:r.current,strict:n},children:e})}function Cs(e){return typeof e=="function"}const Fu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function as(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Fu.has(e)}let ha=e=>!as(e);function Bu(e){typeof e=="function"&&(ha=t=>t.startsWith("on")?!as(t):e(t))}try{Bu(require("@emotion/is-prop-valid").default)}catch{}function zu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(ha(r)||n===!0&&as(r)||!t&&!as(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ds=f.createContext({});function hs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Vn(e){return typeof e=="string"||Array.isArray(e)}const Dr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Rr=["initial",...Dr];function fs(e){return hs(e.animate)||Rr.some(t=>Vn(e[t]))}function fa(e){return!!(fs(e)||e.variants)}function Uu(e,t){if(fs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Vn(n)?n:void 0,animate:Vn(s)?s:void 0}}return e.inherit!==!1?t:{}}function _u(e){const{initial:t,animate:n}=Uu(e,f.useContext(ds));return f.useMemo(()=>({initial:t,animate:n}),[Ti(t),Ti(n)])}function Ti(e){return Array.isArray(e)?e.join(" "):e}const In={};function Xu(e){for(const t in e)In[t]=e[t],gr(t)&&(In[t].isCSSVariable=!0)}function ma(e,{layout:t,layoutId:n}){return ln.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!In[e]||e==="opacity")}const qu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Wu=an.length;function Ku(e,t,n){let s="",r=!0;for(let o=0;o<Wu;o++){const i=an[o],a=e[i];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(i.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const u=ia(a,Ar[i]);if(!l){r=!1;const d=qu[i]||i;s+=`${d}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Vr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const u=t[l];if(ln.has(l)){i=!0;continue}else if(gr(l)){r[l]=u;continue}else{const d=ia(u,Ar[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=Ku(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:u="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${u} ${d}`}}const Ir=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function pa(e,t,n){for(const s in t)!Se(t[s])&&!ma(s,n)&&(e[s]=t[s])}function Gu({transformTemplate:e},t){return f.useMemo(()=>{const n=Ir();return Vr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Hu(e,t){const n=e.style||{},s={};return pa(s,n,e),Object.assign(s,Gu(e,t)),s}function Yu(e,t){const n={},s=Hu(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Ju={offset:"stroke-dashoffset",array:"stroke-dasharray"},Zu={offset:"strokeDashoffset",array:"strokeDasharray"};function Qu(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?Ju:Zu;e[o.offset]=K.transform(-s);const i=K.transform(t),a=K.transform(n);e[o.array]=`${i} ${a}`}function ga(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,u,d){if(Vr(e,a,u),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:m}=e;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Qu(h,r,o,i,!1)}const ya=()=>({...Ir(),attrs:{}}),xa=e=>typeof e=="string"&&e.toLowerCase()==="svg";function ed(e,t,n,s){const r=f.useMemo(()=>{const o=ya();return ga(o,t,xa(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};pa(o,e.style,e),r.style={...o,...r.style}}return r}const td=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Or(e){return typeof e!="string"||e.includes("-")?!1:!!(td.indexOf(e)>-1||/[A-Z]/u.test(e))}function nd(e,t,n,{latestValues:s},r,o=!1){const a=(Or(e)?ed:Yu)(t,s,r,e),l=zu(t,typeof e=="string",o),u=e!==f.Fragment?{...l,...a,ref:n}:{},{children:d}=t,h=f.useMemo(()=>Se(d)?d.get():d,[d]);return f.createElement(e,{...u,children:h})}function Si(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function $r(e,t,n,s){if(typeof t=="function"){const[r,o]=Si(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Si(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function es(e){return Se(e)?e.get():e}function sd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:rd(n,s,r,e),renderState:t()}}function rd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=es(o[m]);let{initial:i,animate:a}=e;const l=fs(e),u=fa(e);t&&u&&!l&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const h=d?a:i;if(h&&typeof h!="boolean"&&!hs(h)){const m=Array.isArray(h)?h:[h];for(let g=0;g<m.length;g++){const v=$r(e,m[g]);if(v){const{transitionEnd:b,transition:y,...x}=v;for(const j in x){let k=x[j];if(Array.isArray(k)){const N=d?k.length-1:0;k=k[N]}k!==null&&(r[j]=k)}for(const j in b)r[j]=b[j]}}}return r}const ba=e=>(t,n)=>{const s=f.useContext(ds),r=f.useContext(us),o=()=>sd(e,t,s,r);return n?o():ar(o)};function Lr(e,t,n){const{style:s}=e,r={};for(const o in s)(Se(s[o])||t.style&&Se(t.style[o])||ma(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const id=ba({scrapeMotionValuesFromProps:Lr,createRenderState:Ir});function va(e,t,n){const s=Lr(e,t,n);for(const r in e)if(Se(e[r])||Se(t[r])){const o=an.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const od=ba({scrapeMotionValuesFromProps:va,createRenderState:ya}),ad=Symbol.for("motionComponentSymbol");function Yt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ld(e,t,n){return f.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Yt(n)&&(n.current=s))},[t])}const Fr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),cd="framerAppearId",wa="data-"+Fr(cd),Ta=f.createContext({});function ud(e,t,n,s,r){const{visualElement:o}=f.useContext(ds),i=f.useContext(Nr),a=f.useContext(us),l=f.useContext(Er).reducedMotion,u=f.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=u.current,h=f.useContext(Ta);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&dd(u.current,n,r,h);const m=f.useRef(!1);f.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const g=n[wa],v=f.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return vo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),v.current&&d.animationState&&d.animationState.animateChanges())}),f.useEffect(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),v.current=!1),d.enteringChildren=void 0)}),d}function dd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Sa(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Yt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:u})}function Sa(e){if(e)return e.options.allowProjection!==!1?e.projection:Sa(e.parent)}function ts(e,{forwardMotionProps:t=!1}={},n,s){n&&Ys(n);const r=Or(e)?od:id;function o(a,l){let u;const d={...f.useContext(Er),...a,layoutId:hd(a)},{isStatic:h}=d,m=_u(a),g=r(a,h);if(!h&&lr){fd(d,n);const v=md(d);u=v.MeasureLayout,m.visualElement=ud(e,g,d,s,v.ProjectionNode)}return c.jsxs(ds.Provider,{value:m,children:[u&&m.visualElement?c.jsx(u,{visualElement:m.visualElement,...d}):null,nd(e,a,ld(g,m.visualElement,l),g,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=f.forwardRef(o);return i[ad]=e,i}function hd({layoutId:e}){const t=f.useContext(or).id;return t&&e!==void 0?t+"-"+e:e}function fd(e,t){const n=f.useContext(Nr).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?rn(!1,s,"lazy-strict-mode"):lt(!1,s,"lazy-strict-mode")}}function md(e){const{drag:t,layout:n}=sn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function pd(e,t){if(typeof Proxy>"u")return ts;const n=new Map,s=(o,i)=>ts(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&fr(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,ts(i,void 0,e,t)),n.get(i))})}function ja({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function gd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function yd(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Ps(e){return e===void 0||e===1}function Js({scale:e,scaleX:t,scaleY:n}){return!Ps(e)||!Ps(t)||!Ps(n)}function Dt(e){return Js(e)||Ca(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ca(e){return ji(e.x)||ji(e.y)}function ji(e){return e&&e!=="0%"}function ls(e,t,n){const s=e-n,r=t*s;return n+r}function Ci(e,t,n,s,r){return r!==void 0&&(e=ls(e,r,s)),ls(e,n,s)+t}function Zs(e,t=0,n=1,s,r){e.min=Ci(e.min,t,n,s,r),e.max=Ci(e.max,t,n,s,r)}function Pa(e,{x:t,y:n}){Zs(e.x,t.translate,t.scale,t.originPoint),Zs(e.y,n.translate,n.scale,n.originPoint)}const Pi=.999999999999,Ai=1.0000000000001;function xd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Zt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Pa(e,i)),s&&Dt(o.latestValues)&&Zt(e,o.latestValues))}t.x<Ai&&t.x>Pi&&(t.x=1),t.y<Ai&&t.y>Pi&&(t.y=1)}function Jt(e,t){e.min=e.min+t,e.max=e.max+t}function ki(e,t,n,s,r=.5){const o=fe(e.min,e.max,r);Zs(e,t,n,o,s)}function Zt(e,t){ki(e.x,t.x,t.scaleX,t.scale,t.originX),ki(e.y,t.y,t.scaleY,t.scale,t.originY)}function Aa(e,t){return ja(yd(e.getBoundingClientRect(),t))}function bd(e,t,n){const s=Aa(e,n),{scroll:r}=t;return r&&(Jt(s.x,r.offset.x),Jt(s.y,r.offset.y)),s}const Mi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Qt=()=>({x:Mi(),y:Mi()}),Ei=()=>({min:0,max:0}),ge=()=>({x:Ei(),y:Ei()}),Qs={current:null},ka={current:!1};function vd(){if(ka.current=!0,!!lr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Qs.current=e.matches;e.addEventListener("change",t),t()}else Qs.current=!1}const wd=new WeakMap;function Td(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Se(r))e.addValue(s,r);else if(Se(o))e.addValue(s,nn(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,nn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Ni=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Sd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Cr,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=ke.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,ue.render(this.render,!1,!0))};const{latestValues:l,renderState:u}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=fs(n),this.isVariantNode=fa(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in h){const g=h[m];l[m]!==void 0&&Se(g)&&g.set(l[m])}}mount(t){this.current=t,wd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),ka.current||vd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Qs.current,process.env.NODE_ENV!=="production"&&fr(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),bt(this.notifyUpdate),bt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=ln.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ue.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in sn){const n=sn[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ge()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<Ni.length;s++){const r=Ni[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=Td(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=nn(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(wo(s)||So(s))?s=parseFloat(s):!Eu(s)&&vt.test(n)&&(s=ra(t,n)),this.setBaseTarget(t,Se(s)?s.get():s)),Se(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=$r(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Se(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new hr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){kr.render(this.render)}}class Ma extends Sd{constructor(){super(...arguments),this.KeyframeResolver=xu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Se(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Ea(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function jd(e){return window.getComputedStyle(e)}class Cd extends Ma{constructor(){super(...arguments),this.type="html",this.renderInstance=Ea}readValueFromInstance(t,n){if(ln.has(n))return this.projection?.isProjecting?_s(n):Oc(t,n);{const s=jd(t),r=(gr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Aa(t,n)}build(t,n,s){Vr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Lr(t,n,s)}}const Na=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Pd(e,t,n,s){Ea(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Na.has(r)?r:Fr(r),t.attrs[r])}class Ad extends Ma{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(ln.has(n)){const s=sa(n);return s&&s.default||0}return n=Na.has(n)?n:Fr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return va(t,n,s)}build(t,n,s){ga(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Pd(t,n,s,r)}mount(t){this.isSVGTag=xa(t.tagName),super.mount(t)}}const Da=(e,t)=>Or(e)?new Ad(t):new Cd(t,{allowProjection:e!==f.Fragment});function tn(e,t,n){const s=e.getProps();return $r(s,t,n!==void 0?n:s.custom,e)}const er=e=>Array.isArray(e);function kd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,nn(n))}function Md(e){return er(e)?e[e.length-1]||0:e}function Ed(e,t){const n=tn(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Md(o[i]);kd(e,i,a)}}function Nd(e){return!!(Se(e)&&e.add)}function tr(e,t){const n=e.getValue("willChange");if(Nd(n))return n.add(t);if(!n&&ct.WillChange){const s=new ct.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ra(e){return e.props[wa]}const Dd=e=>e!==null;function Rd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Dd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const Vd={type:"spring",stiffness:500,damping:25,restSpeed:10},Id=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Od={type:"keyframes",duration:.8},$d={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ld=(e,{keyframes:t})=>t.length>2?Od:ln.has(e)?e.startsWith("scale")?Id(t[1]):Vd:$d;function Fd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:u,...d}){return!!Object.keys(d).length}const Br=(e,t,n,s={},r,o)=>i=>{const a=Pr(s,e)||{},l=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-qe(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};Fd(a)||Object.assign(d,Ld(e,d)),d.duration&&(d.duration=qe(d.duration)),d.repeatDelay&&(d.repeatDelay=qe(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(Gs(d),d.delay===0&&(h=!0)),(ct.instantAnimations||ct.skipAnimations)&&(h=!0,Gs(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const m=Rd(d.keyframes,a);if(m!==void 0){ue.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new jr(d):new iu(d)};function Bd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Va(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const d in a){const h=e.getValue(d,e.latestValues[d]??null),m=a[d];if(m===void 0||u&&Bd(u,d))continue;const g={delay:n,...Pr(o||{},d)},v=h.get();if(v!==void 0&&!h.isAnimating&&!Array.isArray(m)&&m===v&&!g.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const x=Ra(e);if(x){const j=window.MotionHandoffAnimation(x,d,ue);j!==null&&(g.startTime=j,b=!0)}}tr(e,d),h.start(Br(d,h,m,e.shouldReduceMotion&&ea.has(d)?{type:!1}:g,e,b));const y=h.animation;y&&l.push(y)}return i&&Promise.all(l).then(()=>{ue.update(()=>{i&&Ed(e,i)})}),l}function Ia(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,d)=>u.sortNodePosition(d)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function nr(e,t,n={}){const s=tn(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(Va(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return zd(e,t,l,u,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,u]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function zd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(nr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Ia(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function Ud(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>nr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=nr(e,t,n);else{const r=typeof t=="function"?tn(e,t,n.custom):t;s=Promise.all(Va(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Oa(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const _d=Rr.length;function $a(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?$a(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<_d;n++){const s=Rr[n],r=e.props[s];(Vn(r)||r===!1)&&(t[s]=r)}return t}const Xd=[...Dr].reverse(),qd=Dr.length;function Wd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Ud(e,n,s)))}function Kd(e){let t=Wd(e),n=Di(),s=!0;const r=l=>(u,d)=>{const h=tn(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:m,transitionEnd:g,...v}=h;u={...u,...v,...g}}return u};function o(l){t=l(e)}function i(l){const{props:u}=e,d=$a(e.parent)||{},h=[],m=new Set;let g={},v=1/0;for(let y=0;y<qd;y++){const x=Xd[y],j=n[x],k=u[x]!==void 0?u[x]:d[x],N=Vn(k),R=x===l?j.isActive:null;R===!1&&(v=y);let B=k===d[x]&&k!==u[x]&&N;if(B&&s&&e.manuallyAnimateOnMount&&(B=!1),j.protectedKeys={...g},!j.isActive&&R===null||!k&&!j.prevProp||hs(k)||typeof k=="boolean")continue;const O=Gd(j.prevProp,k);let E=O||x===l&&j.isActive&&!B&&N||y>v&&N,F=!1;const S=Array.isArray(k)?k:[k];let M=S.reduce(r(x),{});R===!1&&(M={});const{prevResolvedValues:_={}}=j,D={..._,...M},W=Z=>{E=!0,m.has(Z)&&(F=!0,m.delete(Z)),j.needsAnimating[Z]=!0;const re=e.getValue(Z);re&&(re.liveStyle=!1)};for(const Z in D){const re=M[Z],H=_[Z];if(g.hasOwnProperty(Z))continue;let $e=!1;er(re)&&er(H)?$e=!Oa(re,H):$e=re!==H,$e?re!=null?W(Z):m.add(Z):re!==void 0&&m.has(Z)?W(Z):j.protectedKeys[Z]=!0}j.prevProp=k,j.prevResolvedValues=M,j.isActive&&(g={...g,...M}),s&&e.blockInitialAnimation&&(E=!1);const le=B&&O;E&&(!le||F)&&h.push(...S.map(Z=>{const re={type:x};if(typeof Z=="string"&&s&&!le&&e.manuallyAnimateOnMount&&e.parent){const{parent:H}=e,$e=tn(H,Z);if(H.enteringChildren&&$e){const{delayChildren:Ze}=$e.transition||{};re.delay=Ia(H.enteringChildren,e,Ze)}}return{animation:Z,options:re}}))}if(m.size){const y={};if(typeof u.initial!="boolean"){const x=tn(e,Array.isArray(u.initial)?u.initial[0]:u.initial);x&&x.transition&&(y.transition=x.transition)}m.forEach(x=>{const j=e.getBaseTarget(x),k=e.getValue(x);k&&(k.liveStyle=!0),y[x]=j??null}),h.push({animation:y})}let b=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(b=!1),s=!1,b?t(h):Promise.resolve()}function a(l,u){if(n[l].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(l,u)),n[l].isActive=u;const d=i(l);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Di()}}}function Gd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Oa(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Di(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class wt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Hd extends wt{constructor(t){super(t),t.animationState||(t.animationState=Kd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();hs(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Yd=0;class Jd extends wt{constructor(){super(...arguments),this.id=Yd++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const La={animation:{Feature:Hd},exit:{Feature:Jd}};function On(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Bn(e){return{point:{x:e.pageX,y:e.pageY}}}const Zd=e=>t=>Mr(t)&&e(t,Bn(t));function Pn(e,t,n,s){return On(e,t,Zd(n),s)}const Fa=1e-4,Qd=1-Fa,eh=1+Fa,Ba=.01,th=0-Ba,nh=0+Ba;function Ae(e){return e.max-e.min}function sh(e,t,n){return Math.abs(e-t)<=n}function Ri(e,t,n,s=.5){e.origin=s,e.originPoint=fe(t.min,t.max,e.origin),e.scale=Ae(n)/Ae(t),e.translate=fe(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Qd&&e.scale<=eh||isNaN(e.scale))&&(e.scale=1),(e.translate>=th&&e.translate<=nh||isNaN(e.translate))&&(e.translate=0)}function An(e,t,n,s){Ri(e.x,t.x,n.x,s?s.originX:void 0),Ri(e.y,t.y,n.y,s?s.originY:void 0)}function Vi(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function rh(e,t,n){Vi(e.x,t.x,n.x),Vi(e.y,t.y,n.y)}function Ii(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function kn(e,t,n){Ii(e.x,t.x,n.x),Ii(e.y,t.y,n.y)}function Ve(e){return[e("x"),e("y")]}const za=({current:e})=>e?e.ownerDocument.defaultView:null,Oi=(e,t)=>Math.abs(e-t);function ih(e,t){const n=Oi(e.x,t.x),s=Oi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Ua{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=ks(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=ih(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:b}=m,{timestamp:y}=we;this.history.push({...b,timestamp:y});const{onStart:x,onMove:j}=this.handlers;g||(x&&x(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,m)},this.handlePointerMove=(m,g)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=As(g,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(m,g)=>{this.end();const{onEnd:v,onSessionEnd:b,resumeAnimation:y}=this.handlers;if(this.dragSnapToOrigin&&y&&y(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=ks(m.type==="pointercancel"?this.lastMoveEventInfo:As(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(m,x),b&&b(m,x)},!Mr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Bn(t),l=As(a,this.transformPagePoint),{point:u}=l,{timestamp:d}=we;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,ks(l,this.history)),this.removeListeners=$n(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),bt(this.updatePoint)}}function As(e,t){return t?{point:t(e.point)}:e}function $i(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ks({point:e},t){return{point:e,delta:$i(e,_a(t)),offset:$i(e,oh(t)),velocity:ah(t,.1)}}function oh(e){return e[0]}function _a(e){return e[e.length-1]}function ah(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=_a(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>qe(t)));)n--;if(!s)return{x:0,y:0};const o=Ie(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function lh(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?fe(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?fe(n,e,s.max):Math.min(e,n)),e}function Li(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function ch(e,{top:t,left:n,bottom:s,right:r}){return{x:Li(e.x,n,r),y:Li(e.y,t,s)}}function Fi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function uh(e,t){return{x:Fi(e.x,t.x),y:Fi(e.y,t.y)}}function dh(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=Nn(t.min,t.max-s,e.min):s>r&&(n=Nn(e.min,e.max-r,t.min)),at(0,1,n)}function hh(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const sr=.35;function fh(e=sr){return e===!1?e=0:e===!0&&(e=sr),{x:Bi(e,"left","right"),y:Bi(e,"top","bottom")}}function Bi(e,t,n){return{min:zi(e,t),max:zi(e,n)}}function zi(e,t){return typeof e=="number"?e:e[t]||0}const mh=new WeakMap;class ph{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ge(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Bn(h).point)},i=(h,m)=>{const{drag:g,dragPropagation:v,onDragStart:b}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Tu(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ve(x=>{let j=this.getAxisMotionValue(x).get()||0;if(Je.test(j)){const{projection:k}=this.visualElement;if(k&&k.layout){const N=k.layout.layoutBox[x];N&&(j=Ae(N)*(parseFloat(j)/100))}}this.originPoint[x]=j}),b&&ue.postRender(()=>b(h,m)),tr(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},a=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:b,onDrag:y}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:x}=m;if(v&&this.currentDirection===null){this.currentDirection=gh(x),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",m.point,x),this.updateAxis("y",m.point,x),this.visualElement.render(),y&&y(h,m)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Ve(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new Ua(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:za(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ue.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!Yn(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=lh(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Yt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=ch(s.layoutBox,t):this.constraints=!1,this.elastic=fh(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ve(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=hh(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Yt(t))return!1;const s=t.current;lt(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=bd(s,r.root,this.visualElement.getTransformPagePoint());let i=uh(r.layout.layoutBox,o);if(n){const a=n(gd(i));this.hasMutatedConstraints=!!a,a&&(i=ja(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},u=Ve(d=>{if(!Yn(d,n,this.currentDirection))return;let h=l&&l[d]||{};i&&(h={min:0,max:0});const m=r?200:1e6,g=r?40:1e7,v={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(d,v)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return tr(this.visualElement,t),s.start(Br(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ve(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ve(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Ve(n=>{const{drag:s}=this.getProps();if(!Yn(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-fe(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Yt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ve(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=dh({min:l,max:l},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Ve(i=>{if(!Yn(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:u}=this.constraints[i];a.set(fe(l,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;mh.set(this.visualElement,this);const t=this.visualElement.current,n=Pn(t,"pointerdown",l=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Yt(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),ue.read(s);const i=On(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ve(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=l[d].translate,h.set(h.get()+l[d].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=sr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Yn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function gh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class yh extends wt{constructor(t){super(t),this.removeGroupControls=Oe,this.removeListeners=Oe,this.controls=new ph(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Oe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ui=e=>(t,n)=>{e&&ue.postRender(()=>e(t,n))};class xh extends wt{constructor(){super(...arguments),this.removePointerDownListener=Oe}onPointerDown(t){this.session=new Ua(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:za(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ui(t),onStart:Ui(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ue.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Pn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const ns={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function _i(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Tn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(K.test(e))e=parseFloat(e);else return e;const n=_i(e,t.target.x),s=_i(e,t.target.y);return`${n}% ${s}%`}},bh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=vt.parse(e);if(r.length>5)return s;const o=vt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=l;const u=fe(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let Ms=!1;class vh extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;Xu(wh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Ms&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),ns.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Ms=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ue.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),kr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Ms=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Xa(e){const[t,n]=da(),s=f.useContext(or);return c.jsx(vh,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Ta),isPresent:t,safeToRemove:n})}const wh={borderRadius:{...Tn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Tn,borderTopRightRadius:Tn,borderBottomLeftRadius:Tn,borderBottomRightRadius:Tn,boxShadow:bh};function Th(e,t,n){const s=Se(e)?e:nn(e);return s.start(Br("",s,t,n)),s.animation}const Sh=(e,t)=>e.depth-t.depth;class jh{constructor(){this.children=[],this.isDirty=!1}add(t){cr(this.children,t),this.isDirty=!0}remove(t){ur(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Sh),this.isDirty=!1,this.children.forEach(t)}}function Ch(e,t){const n=ke.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(bt(s),e(o-t))};return ue.setup(s,!0),()=>bt(s)}const qa=["TopLeft","TopRight","BottomLeft","BottomRight"],Ph=qa.length,Xi=e=>typeof e=="string"?parseFloat(e):e,qi=e=>typeof e=="number"||K.test(e);function Ah(e,t,n,s,r,o){r?(e.opacity=fe(0,n.opacity??1,kh(s)),e.opacityExit=fe(t.opacity??1,0,Mh(s))):o&&(e.opacity=fe(t.opacity??1,n.opacity??1,s));for(let i=0;i<Ph;i++){const a=`border${qa[i]}Radius`;let l=Wi(t,a),u=Wi(n,a);if(l===void 0&&u===void 0)continue;l||(l=0),u||(u=0),l===0||u===0||qi(l)===qi(u)?(e[a]=Math.max(fe(Xi(l),Xi(u),s),0),(Je.test(u)||Je.test(l))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=fe(t.rotate||0,n.rotate||0,s))}function Wi(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const kh=Wa(0,.5,No),Mh=Wa(.5,.95,Oe);function Wa(e,t,n){return s=>s<e?0:s>t?1:n(Nn(e,t,s))}function Ki(e,t){e.min=t.min,e.max=t.max}function Re(e,t){Ki(e.x,t.x),Ki(e.y,t.y)}function Gi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Hi(e,t,n,s,r){return e-=t,e=ls(e,1/n,s),r!==void 0&&(e=ls(e,1/r,s)),e}function Eh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Je.test(t)&&(t=parseFloat(t),t=fe(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=fe(o.min,o.max,s);e===o&&(a-=t),e.min=Hi(e.min,t,n,a,r),e.max=Hi(e.max,t,n,a,r)}function Yi(e,t,[n,s,r],o,i){Eh(e,t[n],t[s],t[r],t.scale,o,i)}const Nh=["x","scaleX","originX"],Dh=["y","scaleY","originY"];function Ji(e,t,n,s){Yi(e.x,t,Nh,n?n.x:void 0,s?s.x:void 0),Yi(e.y,t,Dh,n?n.y:void 0,s?s.y:void 0)}function Zi(e){return e.translate===0&&e.scale===1}function Ka(e){return Zi(e.x)&&Zi(e.y)}function Qi(e,t){return e.min===t.min&&e.max===t.max}function Rh(e,t){return Qi(e.x,t.x)&&Qi(e.y,t.y)}function eo(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Ga(e,t){return eo(e.x,t.x)&&eo(e.y,t.y)}function to(e){return Ae(e.x)/Ae(e.y)}function no(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Vh{constructor(){this.members=[]}add(t){cr(this.members,t),t.scheduleRender()}remove(t){if(ur(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Ih(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:g,skewY:v}=n;u&&(s=`perspective(${u}px) ${s}`),d&&(s+=`rotate(${d}deg) `),h&&(s+=`rotateX(${h}deg) `),m&&(s+=`rotateY(${m}deg) `),g&&(s+=`skewX(${g}deg) `),v&&(s+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Es=["","X","Y","Z"],Oh=1e3;let $h=0;function Ns(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Ha(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Ra(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Ha(s)}function Ya({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=$h++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Bh),this.nodes.forEach(Xh),this.nodes.forEach(qh),this.nodes.forEach(zh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new jh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new hr),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const l=this.eventHandlers.get(i);l&&l.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=ua(i)&&!ku(i),this.instance=i;const{layoutId:a,layout:l,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let d,h=0;const m=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{h=window.innerWidth}),e(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,d&&d(),d=Ch(m,250),ns.hasAnimatedSinceResize&&(ns.hasAnimatedSinceResize=!1,this.nodes.forEach(io)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||u.getDefaultTransition()||Yh,{onLayoutAnimationStart:b,onLayoutAnimationComplete:y}=u.getProps(),x=!this.targetLayout||!Ga(this.targetLayout,g),j=!h&&m;if(this.options.layoutRoot||this.resumeFrom||j||h&&(x||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Pr(v,"layout"),onPlay:b,onComplete:y};(u.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,j)}else h||io(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),bt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Wh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Ha(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const h=this.path[d];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(so);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(ro);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(_h),this.nodes.forEach(Lh),this.nodes.forEach(Fh)):this.nodes.forEach(ro),this.clearAllSnapshots();const a=ke.now();we.delta=at(0,1e3/60,a-we.timestamp),we.timestamp=a,we.isProcessing=!0,bs.update.process(we),bs.preRender.process(we),bs.render.process(we),we.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,kr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Uh),this.sharedNodes.forEach(Kh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ae(this.snapshot.measuredBox.x)&&!Ae(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ge(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Ka(this.projectionDelta),l=this.getTransformTemplate(),u=l?l(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Dt(this.latestValues)||d)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),Jh(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ge();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Zh))){const{scroll:u}=this.root;u&&(Jt(a.x,u.offset.x),Jt(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ge();if(Re(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Re(a,i),Jt(a.x,d.offset.x),Jt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ge();Re(l,i);for(let u=0;u<this.path.length;u++){const d=this.path[u];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Zt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Dt(d.latestValues)&&Zt(l,d.latestValues)}return Dt(this.latestValues)&&Zt(l,this.latestValues),l}removeTransform(i){const a=ge();Re(a,i);for(let l=0;l<this.path.length;l++){const u=this.path[l];if(!u.instance||!Dt(u.latestValues))continue;Js(u.latestValues)&&u.updateSnapshot();const d=ge(),h=u.measurePageBox();Re(d,h),Ji(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return Dt(this.latestValues)&&Ji(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==we.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(i||l&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:h}=this.options;if(!(!this.layout||!(d||h))){if(this.resolvedRelativeTargetAt=we.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ge(),this.relativeTargetOrigin=ge(),kn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Re(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ge(),this.targetWithTransforms=ge()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),rh(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Re(this.target,this.layout.layoutBox),Pa(this.target,this.targetDelta)):Re(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ge(),this.relativeTargetOrigin=ge(),kn(this.relativeTargetOrigin,this.target,m.target),Re(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Js(this.parent.latestValues)||Ca(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let l=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===we.timestamp&&(l=!1),l)return;const{layout:u,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||d))return;Re(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,m=this.treeScale.y;xd(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ge());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Gi(this.prevProjectionDelta.x,this.projectionDelta.x),Gi(this.prevProjectionDelta.y,this.projectionDelta.y)),An(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==m||!no(this.projectionDelta.x,this.prevProjectionDelta.x)||!no(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Qt(),this.projectionDelta=Qt(),this.projectionDeltaWithTransform=Qt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,u=l?l.latestValues:{},d={...this.latestValues},h=Qt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ge(),g=l?l.source:void 0,v=this.layout?this.layout.source:void 0,b=g!==v,y=this.getStack(),x=!y||y.members.length<=1,j=!!(b&&!x&&this.options.crossfade===!0&&!this.path.some(Hh));this.animationProgress=0;let k;this.mixTargetDelta=N=>{const R=N/1e3;oo(h.x,i.x,R),oo(h.y,i.y,R),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(kn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Gh(this.relativeTarget,this.relativeTargetOrigin,m,R),k&&Rh(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ge()),Re(k,this.relativeTarget)),b&&(this.animationValues=d,Ah(d,u,this.latestValues,R,j,x)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(bt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{ns.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=nn(0)),this.currentAnimation=Th(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Oh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:u,latestValues:d}=i;if(!(!a||!l||!u)){if(this!==i&&this.layout&&u&&Ja(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||ge();const h=Ae(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+h;const m=Ae(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Re(a,l),Zt(a,d),An(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new Vh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:l}={}){const u=this.getStack();u&&u.promote(this,l),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:l}=i;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const u={};l.z&&Ns("z",i,u,this.animationValues);for(let d=0;d<Es.length;d++)Ns(`rotate${Es[d]}`,i,u,this.animationValues),Ns(`skew${Es[d]}`,i,u,this.animationValues);i.render();for(const d in u)i.setStaticValue(d,u[d]),this.animationValues&&(this.animationValues[d]=u[d]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=es(a?.pointerEvents)||"",i.transform=l?l(this.latestValues,""):"none";return}const u=this.getLead();if(!this.projectionDelta||!this.layout||!u.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=es(a?.pointerEvents)||""),this.hasProjected&&!Dt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=Ih(this.projectionDeltaWithTransform,this.treeScale,d);l&&(h=l(d,h)),i.transform=h;const{x:m,y:g}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=u===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const v in In){if(d[v]===void 0)continue;const{correct:b,applyTo:y,isCSSVariable:x}=In[v],j=h==="none"?d[v]:b(d[v],u);if(y){const k=y.length;for(let N=0;N<k;N++)i[y[N]]=j}else x?this.options.visualElement.renderState.vars[v]=j:i[v]=j}this.options.layoutId&&(i.pointerEvents=u===this?es(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(so),this.root.sharedNodes.clear()}}}function Lh(e){e.updateLayout()}function Fh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Ve(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(h);h.min=n[d].min,h.max=h.min+m}):Ja(r,t.layoutBox,n)&&Ve(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(n[d]);h.max=h.min+m,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+m)});const i=Qt();An(i,n,t.layoutBox);const a=Qt();o?An(a,e.applyTransform(s,!0),t.measuredBox):An(a,n,t.layoutBox);const l=!Ka(i);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:m}=d;if(h&&m){const g=ge();kn(g,t.layoutBox,h.layoutBox);const v=ge();kn(v,n,m.layoutBox),Ga(g,v)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=v,e.relativeTargetOrigin=g,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Bh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function zh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Uh(e){e.clearSnapshot()}function so(e){e.clearMeasurements()}function ro(e){e.isLayoutDirty=!1}function _h(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function io(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Xh(e){e.resolveTargetDelta()}function qh(e){e.calcProjection()}function Wh(e){e.resetSkewAndRotation()}function Kh(e){e.removeLeadSnapshot()}function oo(e,t,n){e.translate=fe(t.translate,0,n),e.scale=fe(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function ao(e,t,n,s){e.min=fe(t.min,n.min,s),e.max=fe(t.max,n.max,s)}function Gh(e,t,n,s){ao(e.x,t.x,n.x,s),ao(e.y,t.y,n.y,s)}function Hh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const Yh={duration:.45,ease:[.4,0,.1,1]},lo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),co=lo("applewebkit/")&&!lo("chrome/")?Math.round:Oe;function uo(e){e.min=co(e.min),e.max=co(e.max)}function Jh(e){uo(e.x),uo(e.y)}function Ja(e,t,n){return e==="position"||e==="preserve-aspect"&&!sh(to(t),to(n),.2)}function Zh(e){return e!==e.root&&e.scroll?.wasRoot}const Qh=Ya({attachResizeListener:(e,t)=>On(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Ds={current:void 0},Za=Ya({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Ds.current){const e=new Qh({});e.mount(window),e.setOptions({layoutScroll:!0}),Ds.current=e}return Ds.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),ef={pan:{Feature:xh},drag:{Feature:yh,ProjectionNode:Za,MeasureLayout:Xa}};function ho(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ue.postRender(()=>o(t,Bn(t)))}class tf extends wt{mount(){const{current:t}=this.node;t&&(this.unmount=Su(t,(n,s)=>(ho(this.node,s,"Start"),r=>ho(this.node,r,"End"))))}unmount(){}}class nf extends wt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=$n(On(this.node.current,"focus",()=>this.onFocus()),On(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fo(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ue.postRender(()=>o(t,Bn(t)))}class sf extends wt{mount(){const{current:t}=this.node;t&&(this.unmount=Au(t,(n,s)=>(fo(this.node,s,"Start"),(r,{success:o})=>fo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const rr=new WeakMap,Rs=new WeakMap,rf=e=>{const t=rr.get(e.target);t&&t(e)},of=e=>{e.forEach(rf)};function af({root:e,...t}){const n=e||document;Rs.has(n)||Rs.set(n,{});const s=Rs.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(of,{root:e,...t})),s[r]}function lf(e,t,n){const s=af(t);return rr.set(e,n),s.observe(e),()=>{rr.delete(e),s.unobserve(e)}}const cf={some:0,all:1};class uf extends wt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:cf[r]},a=l=>{const{isIntersecting:u}=l;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),m=u?d:h;m&&m(l)};return lf(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(df(t,n))&&this.startObserver()}unmount(){}}function df({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Qa={inView:{Feature:uf},tap:{Feature:sf},focus:{Feature:nf},hover:{Feature:tf}},hf={layout:{ProjectionNode:Za,MeasureLayout:Xa}},ff={...La,...Qa,...ef,...hf},mf=pd(ff,Da),pf={renderer:Da,...La,...Qa};function zr(e,t){return ts(e,t)}const gf=zr("button"),Jn=zr("div"),yf=zr("p"),Ye=Symbol.for("@arcteninc/core:originalName");function xf(e,t){return e[Ye]=t,e}function bf(e,t,n,s){if(typeof e!="function")return null;const r=e[Ye];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Ye]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Ye]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Ye]=i.name,{fn:e,meta:i};return null}function el(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
10
10
 
11
11
  Please:
12
12
  1. Run "arcten-extract-types ." before build (add to package.json scripts)
@@ -15,10 +15,10 @@ Please:
15
15
  3. Pass it to useAgent/ArctenAgent:
16
16
  useAgent({ tools: [...], toolMetadata: toolMetadata })
17
17
  (Pass the full object for better minification support, or toolMetadata.functions for backward compatibility)
18
- `);if("functions"in e&&typeof e.functions=="object"){const o=e;n=o.functions,s=o.toolOrder}else n=e,s=void 0;const r=new Set;return t.map(o=>{const i=tf(o,n,r,s);if(!i){const a=o.name,u=o[_t]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${u}". This tool will be excluded.
19
- To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function ef({toolName:t,description:e,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return d.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:d.jsx("span",{className:"text-sm font-medium text-foreground",children:t})}),o&&d.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),d.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d.jsxs(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(yt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(yt.X,{className:"h-3 w-3"})})]})]})})}function nf({toolName:t,args:e,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(t==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];t==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return d.jsxs("div",{className:"my-1",children:[d.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${c?"cursor-pointer hover:bg-muted/80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(yt.ChevronDown,{className:"h-3 w-3"}):d.jsx(yt.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(yt.X,{className:"h-3 w-3"}):s?d.jsx(yt.Zap,{className:"h-3 w-3"}):d.jsx(yt.Check,{className:"h-3 w-3"}),d.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),r&&c&&d.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:d.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function sf({...t}){return d.jsx(zs.Root,{"data-slot":"collapsible",...t})}function rf({...t}){return d.jsx(zs.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function of({...t}){return d.jsx(zs.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const af=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),Ar=m.memo(({className:t,...e})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(af,{className:mt("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);Ar.displayName="Response";const cf=Object.freeze(Object.defineProperty({__proto__:null,Response:Ar},Symbol.toStringTag,{value:"Module"})),lf=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=Xh.create(e),i=m.useMemo(()=>(t?.length??0)*r,[t,r]);return d.jsx(o,{animate:{backgroundPosition:"0% center"},className:mt("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:t})},uf=m.memo(lf),La=m.createContext(null),df=()=>{const t=m.useContext(La);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},hf=1e3,ff=1e3,Fa=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Nr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Nr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[S,T]=m.useState(null);m.useEffect(()=>{e?S===null&&T(Date.now()):S!==null&&(h(Math.ceil((Date.now()-S)/ff)),T(null))},[e,S,h]),m.useEffect(()=>{if(s&&!e&&c&&!f){const y=setTimeout(()=>{u(!1),g(!0)},hf);return()=>clearTimeout(y)}},[e,c,s,u,f]);const w=y=>{u(y)};return d.jsx(La.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(sf,{className:mt("not-prose mb-4",t),onOpenChange:w,open:c,...a,children:i})})}),mf=(t,e)=>t||e===0?d.jsx(uf,{duration:1,children:"Thinking..."}):e===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",e," seconds"]}),$a=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=df();return d.jsx(rf,{className:mt("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??d.jsxs(d.Fragment,{children:[d.jsx(yt.BrainIcon,{className:"size-4"}),mf(s,o),d.jsx(yt.ChevronDownIcon,{className:mt("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ba=m.memo(({className:t,children:e,...n})=>d.jsx(of,{className:mt("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",t),...n,children:d.jsx(Ar,{className:"grid gap-2",children:e})}));Fa.displayName="Reasoning";$a.displayName="ReasoningTrigger";Ba.displayName="ReasoningContent";function Xi(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function pf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=Xi(s.domain);return d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs("button",{className:mt("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[d.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),d.jsx("span",{className:"leading-none",children:s.domain})]})}),d.jsx(le,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",t.length]}),t.map(o=>{const i=o.title||o.domain;return d.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:mt("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[d.jsx("img",{src:Xi(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const c=a.target;c.style.display="none"}}),d.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function gf({text:t,citations:e,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=m.useRef(null),[l,h]=m.useState([]);m.useEffect(()=>{if(!a||!u.current||e.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const w=u.current;let y,v=!1;const x=new WeakSet,M=()=>{if(!u.current||v)return;v=!0;const E=u.current,D=/\[(\d+)\]/g,A=document.createTreeWalker(E,NodeFilter.SHOW_TEXT,null),F=[];let I;for(;I=A.nextNode();)if(I.nodeType===Node.TEXT_NODE&&!x.has(I)){const Y=I,q=Y.textContent||"";let G=Y.parentElement,it=!1;for(;G&&G!==E;){if(G.tagName==="A"||G.tagName==="CODE"||G.tagName==="PRE"){it=!0;break}G=G.parentElement}if(!it){const J=Array.from(q.matchAll(D)).filter(nt=>{if(!nt[1])return!1;const ot=parseInt(nt[1],10);return n.has(ot)});J.length>0&&F.push({node:Y,matches:J})}}if(F.length===0){v=!1;return}const X=[];F.forEach(({node:Y,matches:q})=>{x.add(Y);const G=Y.textContent||"",it=document.createDocumentFragment();let _=0;q.forEach(J=>{if(!J[1])return;J.index!==void 0&&J.index>_&&it.appendChild(document.createTextNode(G.slice(_,J.index)));const nt=document.createElement("span");nt.className="inline-flex items-center citation-button-container";const ot=parseInt(J[1],10);nt.setAttribute("data-citation",J[1]),it.appendChild(nt),X.push({element:nt,citationNum:ot}),_=(J.index||0)+J[0].length}),_<G.length&&it.appendChild(document.createTextNode(G.slice(_))),Y.parentNode&&Y.parentNode.replaceChild(it,Y)}),X.length>0&&h(Y=>{const q=new Set(Y.map(_=>_.element)),G=Y.filter(_=>_.element.isConnected),it=X.filter(_=>!q.has(_.element));return[...G,...it]}),v=!1},j=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(M,100)});return j.observe(w,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(M,200),()=>{j.disconnect(),clearTimeout(y)}},[t,e,n,a]);const f=s&&s.length>0||n&&n.size>0||r;function g(w){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(w)}&sz=16`}function S(w){try{return new URL(w).hostname.replace(/^www\./,"")}catch{return w}}const T=a&&c&&f?d.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[d.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),d.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((w,y)=>{const v=w.title||w.baseUrl,x=S(w.url),M=g(x);return d.jsxs("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:mt("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[d.jsx("img",{src:M,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:j=>{const E=j.target;E.style.display="none"}}),d.jsx("span",{className:"leading-none",children:v})]},`group-${y}`)}):Array.from(n.entries()).sort(([w],[y])=>w-y).map(([w,y])=>{const v=S(y),x=g(v);return d.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:mt("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[d.jsx("img",{src:x,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:M=>{const j=M.target;j.style.display="none"}}),d.jsx("span",{className:"leading-none",children:y})]},w)})})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:u,children:d.jsx(o,{children:t})}),a&&l.filter(({element:w})=>w.isConnected).map(({element:w,citationNum:y},v)=>{if(!e.find(j=>j.number===y))return null;const M=Array.from(new Map(e.map(j=>{const E=j.url.replace(/\/+$/,""),D=s?.find(A=>A.url.replace(/\/+$/,"")===E);return[E,{number:j.number,url:j.url,domain:S(j.url),title:D?.title}]})).values());return hc.createPortal(d.jsx(pf,{sources:M,citationNumber:y},`citation-${y}-${w}`),w,`citation-${y}-${v}`)}),T]})}function yf(t){try{const e=new URL(t),n=`${e.protocol}//${e.host}${e.pathname}`,s=e.hash?e.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const e=t.indexOf("#");return e!==-1?{baseUrl:t.substring(0,e),anchor:t.substring(e+1)}:{baseUrl:t}}}function xf(t){try{const e=new URL(t),s=e.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return e.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||e.hostname}catch{const e=t.indexOf("#"),n=e!==-1?t.substring(0,e):t,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function Yi(t){let e=t.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=e.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const A=s[1],F=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let I;for(;(I=F.exec(A))!==null;)if(I[1]&&I[2]){const X=parseInt(I[1],10),Y=I[2].replace(/[.,;:!?]+$/,""),q=Y.replace(/\/+$/,"");if(a.has(q)||a.set(q,Y),i.has(q)||i.set(q,[]),i.get(q).push(X),!c.has(q))c.set(q,X);else{const G=c.get(q);X<G&&c.set(q,X)}}for(const[X,Y]of i.entries()){const q=c.get(X);for(const G of Y)G!==q&&u.set(G,q)}for(const[X,Y]of c.entries()){const q=a.get(X)||X;r.set(Y,q),o.push({number:Y,url:q})}}let l,h=e;s&&s[0]&&(l=s[0],h=e.replace(n,""));const f=[];let g=0;const S=/```[\s\S]*?```|`[^`]+`/g;let T;for(;(T=S.exec(h))!==null;)T.index>g&&f.push({type:"text",content:h.slice(g,T.index),start:g,end:T.index}),f.push({type:"code",content:T[0],start:T.index,end:T.index+T[0].length}),g=T.index+T[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const w=f.map(A=>{if(A.type==="code")return A.content;let F=A.content;return F=F.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(X,Y,q)=>{const G=parseInt(Y,10),it=q.replace(/\/+$/,""),_=u.get(G)||G;return c.has(it)||(c.set(it,_),r.has(_)||(r.set(_,q),o.push({number:_,url:q}))),`[${_}]`}),F=F.replace(/\[(\d+)\]/g,(X,Y)=>{const q=parseInt(Y,10);return`[${u.get(q)||q}]`}),F}),y=[];for(const[A,F]of c.entries()){const I=a.get(A)||A,{baseUrl:X,anchor:Y}=yf(I),q=xf(I);y.push({url:I,baseUrl:X,numbers:[F],anchor:Y,title:q})}y.sort((A,F)=>(A.numbers[0]||0)-(F.numbers[0]||0));const v=new Map;let x=1;for(const A of y){const F=A.numbers[0];v.set(F,x),A.numbers=[x],x++}const M=new Map;for(const[A,F]of r.entries()){const I=v.get(A);I&&M.set(I,F)}const j=o.map(A=>{const F=v.get(A.number);return F?{number:F,url:A.url}:A}).filter(A=>v.has(A.number)),E=Array.from(v.entries()).sort((A,F)=>F[0]-A[0]);let D=w.join("");for(const[A,F]of E){const I=new RegExp(`\\[${A}\\](?!\\d)`,"g");D=D.replace(I,`[${F}]`)}return{processedText:D,citations:j.sort((A,F)=>A.number-F.number),citationMap:M,groupedCitations:y,referencesText:l}}function ln(t){if(typeof t=="string")try{const e=JSON.parse(t);return ln(e)}catch{return t}if(Array.isArray(t))return t.map(ln);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=ln(s);return e}return t}function gs(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return ln(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?ln(t):{}}function vf({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:h=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:S="/api/arcten/token",apiBaseUrl:T="https://api.arcten.com",user:w,state:y,onStateChange:v,allowStateEdits:x=!0,sources:M,ragConfig:j,showCitations:E=!0}){const D=m.useMemo(()=>j!==void 0?j:M&&M.length>0?{enabled:!0,organizationId:M[0],autoExecute:!0,filters:void 0}:{enabled:!1},[M,j]),[A,F]=m.useState(null),I=m.useRef(null),[X,Y]=m.useState(null),[q,G]=m.useState(null),it=m.useRef(null),_=y!==void 0,[J,nt]=m.useState({}),ot=m.useRef({});_&&y?ot.current=y:_||(ot.current=J);const[st,Jt]=m.useState(!1),[ke,xt]=m.useState(null),Zt=m.useRef(!1),[Bt,Me]=m.useState(u),[zt,Qt]=m.useState(i),[te,Ee]=m.useState(600),[ee,Vt]=m.useState(!1),[tt,It]=m.useState(!1),[Ct,kt]=m.useState(!1),[bt,De]=m.useState({x:100,y:100}),[He,me]=m.useState(!1),[Ne,wn]=m.useState({x:0,y:0}),[Tn,Ut]=m.useState(!1),Xe=m.useRef(null),ne=m.useRef(null),[se,Ye]=m.useState(""),[pe,Je]=m.useState(null),[Hn,Xn]=m.useState("Thinking..."),[Ze,Kt]=m.useState(new Set),[Yn,Jn]=m.useState(""),[C,P]=m.useState([]),[V,O]=m.useState(!1),[W,Q]=m.useState([]),[H,wt]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[dt,Pt]=m.useState(!1),[at,rt]=m.useState(!1),[Re,ge]=m.useState([]),Cr=m.useCallback(async(p,b=3)=>{if(!H||!I.current)return;const k=async()=>{const R=`${T.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,$=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:H,updates:p},format:"json"})});if(!$.ok){if($.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const Z=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${$.status} ${Z}`)}};for(let N=0;N<b;N++)try{await k(),xt(null);return}catch(R){if(N===b-1){const Z=R instanceof Error?R:new Error(String(R));throw xt(Z),console.error("Failed to sync state to Convex after retries:",R),Z}await new Promise(Z=>setTimeout(Z,Math.pow(2,N)*100))}},[H,T,I]),Qe=m.useMemo(()=>function(){return ot.current},[]),tn=m.useMemo(()=>async function(b){const k={...ot.current,...b};ot.current=k,_||nt(k),v&&v(k);try{await Cr(b)}catch(N){throw N}},[Cr,v,_]);m.useEffect(()=>{_&&y&&(ot.current=y)},[_,y]);const ye=m.useMemo(()=>D?.enabled?async function(b,k=20,N){if(M&&M.length>1){const Z=M.map(U=>fetch(`${T}/search`,{method:"POST",headers:{"Content-Type":"application/json",...I.current?{Authorization:`Bearer ${I.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(k,100),organizationId:U,...Object.keys($).length>0?{filters:$}:{}})}).then(B=>B.ok?B.json():null)),K=await Promise.all(Z),et=[];for(const U of K)U?.candidates&&et.push(...U.candidates);et.sort((U,B)=>{const pt=U.scores?.rerank||U.scores?.dense||0;return(B.scores?.rerank||B.scores?.dense||0)-pt});const L=et.slice(0,k).map((U,B)=>{const pt=U.citation||U.url;return{rank:B+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:pt,title:U.title||"Untitled",snippet:U.snippet,score:U.scores?.rerank||U.scores?.dense||0,metadata:{site:U.metadata?.site,lang:U.metadata?.lang,contentType:U.metadata?.content_type}}});return{success:!0,query:b,total:et.length,results:L,summary:`Found ${et.length} relevant results across ${M.length} source(s) for "${b}". Top result: ${L[0]?.title||"N/A"}`}}const R=D.organizationId&&D.organizationId!=="default"?D.organizationId:void 0,$={...D.filters,...N};try{const Z={q:b,k:Math.min(k,100)};R&&(Z.organizationId=R),Object.keys($).length>0&&(Z.filters=$);const K={"Content-Type":"application/json"};I.current&&(K.Authorization=`Bearer ${I.current}`);const et=await fetch(`${T}/search`,{method:"POST",headers:K,body:JSON.stringify(Z)});if(!et.ok){const B=await et.text();return{success:!1,error:`Search failed: ${et.status} ${B}`}}const L=await et.json(),U=L.candidates.map((B,pt)=>{const ht=B.citation||B.url;return{rank:pt+1,doc_id:B.doc_id,block_id:B.block_id,url:B.url,citation:ht,title:B.title||"Untitled",snippet:B.snippet,score:B.scores?.rerank||B.scores?.dense||0,metadata:{site:B.metadata?.site,lang:B.metadata?.lang,contentType:B.metadata?.content_type}}});return{success:!0,query:L.query,total:L.total,results:U,summary:`Found ${L.total} relevant results for "${b}". Top result: ${U[0]?.title||"N/A"}`}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Unknown error occurred"}}}:null,[j,T,I]),xe=m.useMemo(()=>D?.enabled?async function(b,k){const N=D.organizationId&&D.organizationId!=="default"?D.organizationId:M&&M.length>0?M[0]:void 0;try{const R={"Content-Type":"application/json"};I.current&&(R.Authorization=`Bearer ${I.current}`);const $=await fetch(`${T}/fetch`,{method:"POST",headers:R,body:JSON.stringify({doc_id:b,block_ids:k,...N?{organizationId:N}:{}})});if(!$.ok){const K=await $.text();return{success:!1,error:`Fetch failed: ${$.status} ${K}`}}const Z=await $.json();return{success:!0,blocks:Z.blocks||[],fullContent:Z.fullContent||"",pageUrl:Z.pageUrl||"",pageTitle:Z.pageTitle||"",summary:`Fetched ${Z.blocks?.length||0} blocks from ${Z.pageTitle||b}`}}catch(R){return{success:!1,error:R instanceof Error?R.message:"Unknown error occurred"}}}:null,[j,T,I]),ve=m.useMemo(()=>{const p=[...l,...h,Qe];return(!_||x)&&p.push(tn),D?.enabled&&(ye&&p.push(ye),xe&&p.push(xe)),p},[l,h,Qe,tn,ye,xe,_,x,D]),Zn=m.useMemo(()=>Oa(ve,f),[ve,f]),qt=m.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!_||x)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const b=[];return D?.enabled&&b.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Zn,...p,...b]},[Zn,_,x,D]),Pr=m.useMemo(()=>new Set(qt.map(p=>p.name)),[qt]),Sn=m.useMemo(()=>qt.filter(p=>p.name==="getState"?!0:p.name==="setState"?!_||x:Pr.has(p.name)),[qt,Pr,_,x]),An=m.useMemo(()=>{const p=new Map,b=new Map(Zn.map(k=>[k.name,k]));return p.set("getState",Qe),(!_||x)&&p.set("setState",tn),D?.enabled&&(ye&&p.set("searchDocs",ye),xe&&p.set("fetchDocContent",xe)),ve.forEach(k=>{if(k===Qe||k===tn||k===ye||k===xe)return;const N=k[_t];if(N){const $=b.get(N);if($){p.set($.name,k);return}}const R=qt.find($=>$.name===k.name);R&&p.set(R.name,k)}),p},[ve,qt,Qe,tn,ye,xe,_,x,D]),en=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),D?.enabled&&D.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(qt.map(k=>[k.name,k]));return h.forEach(k=>{const N=k[_t];if(N&&b.has(N))p.add(N);else{const R=qt.find($=>$.name===k.name);R&&p.add(R.name)}}),p},[h,qt,D]),jr=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];m.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&Me(JSON.parse(p));const b=localStorage.getItem("arcten-sidebar-width");b&&Qt(parseInt(b));const k=localStorage.getItem("arcten-sidebar-height");k&&Ee(parseInt(k));const N=localStorage.getItem("arcten-sidebar-detached");N&&It(JSON.parse(N));const R=localStorage.getItem("arcten-sidebar-position");if(R){const Z=JSON.parse(R),K=50,et=Math.max(K-i,Math.min(Z.x,window.innerWidth-K)),L=Math.max(0,Math.min(Z.y,window.innerHeight-K));De({x:et,y:L})}const $=localStorage.getItem("arcten-sidebar-minimized");$&&kt(JSON.parse($)),Ut(!0)}},[]);const re=m.useMemo(()=>w,[w?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!b.ok)throw new Error("Failed to fetch token");const k=await b.json();F(k.clientToken),I.current=k.clientToken,G(k.expiresAt),Y(null)}catch(b){Y(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{it.current&&clearTimeout(it.current)}),[S,re]),m.useEffect(()=>{if(!q)return;it.current&&clearTimeout(it.current);const p=Math.floor(Date.now()/1e3),b=q-p,N=Math.max(0,b-5);return it.current=setTimeout(async()=>{try{const R=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!R.ok)throw new Error("Failed to refresh token");const $=await R.json();F($.clientToken),I.current=$.clientToken,G($.expiresAt),Y(null)}catch(R){console.error("Token refresh failed:",R),Y(R instanceof Error?R.message:"Failed to refresh token")}},N*1e3),()=>{it.current&&clearTimeout(it.current)}},[q,S,re]),m.useEffect(()=>{(async()=>{if(ve.length!==0)try{const b=ve.map(N=>({name:N.name,code:N.toString()})),k=await fetch(`${T}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(k.ok){const N=await k.json();P(N.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[ve]),m.useEffect(()=>{Promise.resolve().then(()=>cf).then(p=>{Je(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Jn(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Qn=m.useCallback(async()=>{if(!(!re?.id||!A)){rt(!0);try{const b=await(await fetch(`${T}/conversations`,{headers:{Authorization:`Bearer ${A}`}})).json();Q(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{rt(!1)}}},[re?.id,A,T]);m.useEffect(()=>{re?.id&&A&&Qn()},[re?.id,A,Qn]);function za(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Ua(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1);const b=_?y||{}:{};ot.current=b,_||nt(b),v&&v(b),Zt.current=!1}async function _a(p){if(A)try{await fetch(`${T}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${A}`}}),Q(W.filter(b=>b._id!==p)),p===H&&Ua()}catch(b){console.error("Failed to delete conversation:",b)}}async function Wa(p){wt(p.chatId),Pt(!1),rt(!0);try{const b=await fetch(`${T}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${I.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const N=(await b.json()).messages||[];Pn(N),ge(N)}catch(b){console.error("Failed to load conversation messages:",b);const k=p.messages||[];Pn(k),ge(k)}finally{rt(!1)}}const Ka=async(p,b={})=>{const k=b.headers?new Headers(b.headers):new Headers;return k.delete("user-agent"),k.delete("User-Agent"),fetch(p,{...b,headers:k})},{messages:Gt,sendMessage:qa,status:Ot,error:kr,stop:Cn,addToolResult:be,setMessages:Pn}=Ji.useChat({id:H||void 0,transport:new Ln.DefaultChatTransport({api:`${T}/chat`,fetch:Ka,headers:()=>{const p={};return I.current&&(p.Authorization=`Bearer ${I.current}`),p},body:()=>({tools:Sn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:Yn,state:ot.current})}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Gt[Gt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(k=>k.type?.startsWith("tool-")&&k.state==="input-available"&&typeof k.toolCallId=="string"&&k.input!==void 0)||[];for(const k of b){const N=k,R=N.type?.replace("tool-","")||"",$=N.toolCallId;if(en.has(R)){if(Ze.has($))continue;Kt(K=>K.has($)?K:new Set(K).add($)),(async()=>{try{const K=An.get(R);if(!K){console.warn(`[ArctenAgent] Tool ${R} not found in toolsMap. Available tools:`,Array.from(An.keys())),be({toolCallId:$,tool:R,output:`Error: Tool ${R} not found`}),Kt(B=>{const pt=new Set(B);return pt.delete($),pt});return}const et=gs(N.input),L=Sn.find(B=>B.name===R);let U;if(L&&L.jsonSchema?.properties){const pt=Object.keys(L.jsonSchema.properties).map(ht=>et[ht]);console.log(`[ArctenAgent] Executing safe tool ${R} with args:`,pt),U=await K(...pt)}else if(R==="getState")U=K();else if(R==="setState"){const B=et.updates||et;U=await K(B)}else U=await K(...Object.values(et));console.log(`[ArctenAgent] Tool ${R} completed, result:`,U),be({toolCallId:$,tool:R,output:U}),Kt(B=>{const pt=new Set(B);return pt.delete($),pt})}catch(K){console.error(`[ArctenAgent] Error executing safe tool ${R}:`,K),be({toolCallId:$,tool:R,output:`Error: ${K instanceof Error?K.message:String(K)}`}),Kt(et=>{const L=new Set(et);return L.delete($),L})}})()}}},[Gt,en,An,Sn,be]),m.useEffect(()=>{if(!H||!I.current)return;(async()=>{Jt(!0),xt(null);try{const k=`${T.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,N=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:H},format:"json"})});if(!N.ok){if(N.status===404||N.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${N.status}), using empty state`);const L=_?y||{}:{};ot.current=L,_||nt(L),v&&v(L),Zt.current=!0,Jt(!1);return}const et=await N.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${N.status} ${et}`)}const $=(await N.json())?.value||{},Z=!Zt.current;let K;Z?(K={..._?y||{}:{},...$},Zt.current=!0):K=$,ot.current=K,_||nt(K),v&&v(K)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const N=b instanceof Error?b:new Error(String(b));if(xt(N),!Zt.current){const R=_?y||{}:{};ot.current=R,_||nt(R),v&&v(R),Zt.current=!0}}finally{Jt(!1)}})()},[H,T,_,y,v]),m.useEffect(()=>{Bt&&ne.current&&ne.current.focus()},[Bt,Gt]);function Ga(){Me(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ha(){Me(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Bt]),m.useEffect(()=>{Xe.current&&Xe.current.scrollIntoView({behavior:"smooth"})},[Gt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Ot==="streaming"||Ot==="submitted")&&(b.preventDefault(),Cn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ot,Cn]);function Xa(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1)}function Mr(p){if(p.preventDefault(),!se.trim())return;(Ot==="streaming"||Ot==="submitted")&&Cn();const b=jr[Math.floor(Math.random()*jr.length)]||"Thinking...";Xn(b),qa({text:se}),Ye("")}function Ya(p){const b=p.target.value;Ye(b)}m.useEffect(()=>{if(!ee)return;function p(k){if(tt){const N=k.clientX-bt.x,R=k.clientY-bt.y;N>=a&&N<=c&&Qt(N),R>=400&&R<=1e3&&Ee(R)}else{const N=window.innerWidth-k.clientX;N>=a&&N<=c&&Qt(N)}}function b(){Vt(!1),localStorage.setItem("arcten-sidebar-width",zt.toString()),localStorage.setItem("arcten-sidebar-height",te.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ee,zt,te,tt,bt,a,c]);function Ja(p){p.preventDefault(),Vt(!0)}function Za(){It(!0),kt(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qa(){It(!1),kt(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Er(){kt(!Ct),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ct))}function tc(p){tt&&(me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y}))}return m.useEffect(()=>{if(!tt)return;function p(){De(b=>{const N=window.innerWidth-50,R=window.innerHeight-50,$=50-zt,Z=0,K=Math.max($,Math.min(b.x,N)),et=Math.max(Z,Math.min(b.y,R));if(K!==b.x||et!==b.y){const L={x:K,y:et};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(L)),L}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[tt,zt]),m.useEffect(()=>{if(!He)return;function p(k){const N=k.clientX-Ne.x,R=k.clientY-Ne.y,$=50,Z=window.innerWidth-$,K=window.innerHeight-$,et=$-zt,L=0,U=Math.max(et,Math.min(N,Z)),B=Math.max(L,Math.min(R,K));De({x:U,y:B})}function b(){me(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(bt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[He,Ne,bt,zt]),Tn?X?d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",X]})}):A?d.jsx(bu,{features:Yh,children:d.jsx(Dn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:tt?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:tt?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
- ${tt?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
- ${Bt?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
22
- ${tt?"border border-border":"border-l border-border"}
23
- ${Bt?"":"w-[30px]"}
24
- `,style:Bt?tt?{width:`${zt}px`,height:Ct?"auto":`${te}px`,left:`${bt.x}px`,top:`${bt.y}px`}:{width:`${zt}px`}:void 0,onClick:Bt?void 0:Ga,children:Bt?d.jsxs(d.Fragment,{children:[!tt&&d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Ja,children:d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),tt&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Vt(!0)}}),d.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y})},children:d.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),d.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Vt(!0)}})]}),d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${tt?"cursor-move":""}`,onMouseDown:tt?tc:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${tt&&Ct?"cursor-pointer":""}`,onClick:tt&&Ct?p=>{p.stopPropagation(),Er()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Xa,"aria-label":"New chat",children:d.jsx(yt.Plus,{className:"h-4 w-4"})})}),d.jsx(le,{children:"Start a new conversation"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:tt?Qa:Za,"aria-label":tt?"Dock sidebar":"Float sidebar",children:tt?d.jsx(yt.Dock,{className:"h-4 w-4"}):d.jsx(yt.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(le,{children:tt?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:tt?Er:Ha,"aria-label":tt?Ct?"Maximize":"Minimize":"Close sidebar",children:tt?Ct?d.jsx(yt.Maximize2,{className:"h-4 w-4"}):d.jsx(yt.Minimize2,{className:"h-4 w-4"}):d.jsx(yt.X,{className:"h-4 w-4"})})}),d.jsx(le,{children:tt?Ct?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ct&&d.jsxs(d.Fragment,{children:[w&&W.length>0&&d.jsxs("div",{className:`border-b border-border ${dt?"flex flex-col flex-1":""}`,children:[d.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[d.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),d.jsx(Fn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{dt||Qn(),Pt(!dt)},children:dt?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${dt?"flex-1 overflow-y-auto":""}`,children:W.slice(0,dt?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs(Jh,{type:"button",className:mt(Te({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>Wa(p),children:[d.jsx("span",{className:"text-xs truncate",children:p.title}),d.jsx("div",{className:"ml-2 flex items-center",children:d.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:za(p.updatedAt)})})]}),d.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:b=>{b.stopPropagation(),_a(p._id)},"aria-label":"Delete conversation",children:d.jsx(yt.X,{className:"h-3 w-3"})})]},p._id))})]}),d.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[d.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Gt.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&d.jsx("div",{className:"mb-6",children:o}),d.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),C.length>0&&d.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:d.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(V?C:C.slice(0,10)).map(p=>d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ye(p.sampleUsage),ne.current?.focus()},children:p.friendlyName})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium",children:p.description}),d.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[d.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&d.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),C.length>10&&!V&&d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!0),children:["+",C.length-10," more"]})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),d.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:C.slice(10).map(p=>d.jsxs("div",{children:[d.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),d.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),d.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),V&&C.length>10&&d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[Gt.map(p=>{const k=p.parts.filter(L=>L.type==="text").map(L=>L.text).join("");let N=p.parts;p.role==="assistant"&&p.parts.some(U=>U.timestamp)&&(N=[...p.parts].sort((U,B)=>{const pt=U.timestamp||0,ht=B.timestamp||0;return pt-ht}));let R=[],$=new Map,Z=[],K,et=!0;if(p.role==="assistant"){const L=N.filter(ht=>ht.type==="text"&&ht.text),U=[],B=[];L.forEach(ht=>{const{citations:ie,citationMap:St,groupedCitations:Mt,referencesText:oe}=Yi(ht.text);R.push(...ie),U.push(St),Mt&&B.push(...Mt),oe&&(K=oe)}),U.forEach(ht=>{ht.forEach((ie,St)=>{$.has(St)||$.set(St,ie)})}),Z=Array.from(new Map(B.map(ht=>[ht.url,ht])).values()).sort((ht,ie)=>(ht.numbers[0]||0)-(ie.numbers[0]||0)),et=!(Ot==="streaming"&&p.id===Gt.at(-1)?.id)}return d.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:d.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?d.jsx(Zh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:k}):d.jsx("div",{className:"space-y-2",children:N.map((L,U)=>{if(L.type?.startsWith("tool-")){const B=L.type?.replace("tool-","")||"",pt=Sn.find(St=>St.name===B),ht=L.state==="input-available",ie=L.state==="output-available";if(ht&&en.has(B),ht){if(en.has(B))return null;const St=gs(L.input);return d.jsx(Dn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(ef,{toolName:B,description:pt?.description||"",args:St,onApprove:async()=>{if(Ze.has(L.toolCallId))return;Kt(oe=>new Set(oe).add(L.toolCallId));const Mt=An.get(B);if(Mt)try{const oe=await Mt(...Object.values(St));be({toolCallId:L.toolCallId,tool:B,output:oe})}catch(oe){be({toolCallId:L.toolCallId,tool:B,output:`Error: ${oe}`})}},onDeny:async()=>{Ze.has(L.toolCallId)||(Kt(Mt=>new Set(Mt).add(L.toolCallId)),be({toolCallId:L.toolCallId,tool:B,output:"User denied tool execution"}))}})},`${L.toolCallId}-${U}`)}else if(ie){const St=L.output==="User denied tool execution",Mt=gs(L.input);return d.jsx(nf,{toolName:B,args:Mt,isDenied:St,isSafe:en.has(B)},`${L.toolCallId}-${U}`)}return null}if(L.type==="text"&&L.text&&pe){const{processedText:B}=Yi(L.text),St=!N.slice(U+1).some(Mt=>Mt.type==="text"&&Mt.text)&&et&&$.size>0;return d.jsx(gf,{text:B,citations:R,citationMap:$,groupedCitations:St?Z:void 0,referencesText:St?K:void 0,ResponseComponent:pe,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:E,showReferences:St},`${p.id}-${U}`)}return L.type==="reasoning"&&L.text?d.jsxs(Fa,{className:"w-full",isStreaming:Ot==="streaming"&&U===p.parts.length-1&&p.id===Gt.at(-1)?.id,children:[d.jsx($a,{}),d.jsx(Ba,{children:L.text})]},`${p.id}-${U}`):null})})})},p.id)}),d.jsx("div",{ref:Xe})]})}),kr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",kr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(vu,{mode:"wait",children:(Ot==="streaming"||Ot==="submitted")&&d.jsxs(Dn,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[d.jsx(Dn,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),d.jsx("p",{className:"text-xs text-muted-foreground",children:Hn})]})}),d.jsxs("form",{onSubmit:Mr,className:"relative",children:[d.jsx(to,{ref:ne,value:se,onChange:Ya,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Mr(p))}}),Ot==="streaming"||Ot==="submitted"?d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Cn,children:d.jsx(yt.Square,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Escape"})," to stop"]})]}):d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"submit",className:mt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!se.trim(),children:d.jsx(yt.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Enter"})," to send"]})]})]})]})]}),d.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[d.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),d.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),d.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[d.jsx(yt.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),d.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function un(t){if(typeof t=="string")try{const e=JSON.parse(t);return un(e)}catch{return t}if(Array.isArray(t))return t.map(un);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=un(s);return e}return t}function bf(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return un(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?un(t):{}}function wf({apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:e="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:h,onStateChange:f,allowStateEdits:g=!0,onToolCall:S,onFinish:T,sources:w,ragConfig:y,ragFilters:v}={}){const x=m.useMemo(()=>y!==void 0?y:v?{enabled:!0,filters:v}:w&&w.length>0?{enabled:!0,organizationId:w[0],autoExecute:!0,filters:void 0}:{enabled:!1},[w,y,v]),[M,j]=m.useState(n||null),E=m.useRef(n||null),[D,A]=m.useState(null),[F,I]=m.useState(null),X=m.useRef(null),[Y,q]=m.useState([]),[G,it]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[_,J]=m.useState(!1),[nt,ot]=m.useState(new Set),st=h!==void 0,[Jt,ke]=m.useState({}),xt=m.useRef({}),Zt=st?h||{}:Jt;st&&h?xt.current=h:st||(xt.current=Jt);const[Bt,Me]=m.useState(!1),[zt,Qt]=m.useState(null),te=m.useRef(!1),Ee=m.useCallback(async(C,P=3)=>{if(!G||!E.current)return;const V=async()=>{const W=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:G,updates:C},format:"json"})});if(!Q.ok){if(Q.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const H=await Q.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${Q.status} ${H}`)}};for(let O=0;O<P;O++)try{await V(),Qt(null);return}catch(W){if(O===P-1){const H=W instanceof Error?W:new Error(String(W));throw Qt(H),console.error("Failed to sync state to Convex after retries:",W),H}await new Promise(H=>setTimeout(H,Math.pow(2,O)*100))}},[G,t,E]),ee=m.useMemo(()=>function(){return xt.current},[]),Vt=m.useMemo(()=>async function(P){const V={...xt.current,...P};xt.current=V,st||ke(V),f&&f(V);try{await Ee(P)}catch(O){throw O}},[Ee,f,st]);m.useEffect(()=>{st&&h&&(xt.current=h)},[st,h]);const tt=m.useMemo(()=>x?.enabled?async function(P,V=20,O){const W={...x.filters,...O};if(w&&w.length>1){const H=w.map(at=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...E.current?{Authorization:`Bearer ${E.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(V,100),organizationId:at,...Object.keys(W).length>0?{filters:W}:{}})}).then(rt=>rt.ok?rt.json():null)),wt=await Promise.all(H),dt=[];for(const at of wt)at?.candidates&&dt.push(...at.candidates);dt.sort((at,rt)=>{const Re=at.scores?.rerank||at.scores?.dense||0;return(rt.scores?.rerank||rt.scores?.dense||0)-Re});const Pt=dt.slice(0,V).map((at,rt)=>{const Re=at.citation||at.url;return{rank:rt+1,doc_id:at.doc_id,block_id:at.block_id,url:at.url,citation:Re,title:at.title||"Untitled",snippet:at.snippet,score:at.scores?.rerank||at.scores?.dense||0,metadata:{site:at.metadata?.site,lang:at.metadata?.lang,contentType:at.metadata?.content_type}}});return{success:!0,query:P,total:dt.length,results:Pt,summary:`Found ${dt.length} relevant results across ${w.length} source(s) for "${P}". Top result: ${Pt[0]?.title||"N/A"}`}}const Q=x.organizationId&&x.organizationId!=="default"?x.organizationId:w&&w.length>0?w[0]:void 0;try{const H={q:P,k:Math.min(V,100)};Q&&(H.organizationId=Q),Object.keys(W).length>0&&(H.filters=W);const wt={"Content-Type":"application/json"};E.current&&(wt.Authorization=`Bearer ${E.current}`);const dt=await fetch(`${t}/search`,{method:"POST",headers:wt,body:JSON.stringify(H)});if(!dt.ok){const rt=await dt.text();return{success:!1,error:`Search failed: ${dt.status} ${rt}`}}const Pt=await dt.json(),at=Pt.candidates.map((rt,Re)=>{const ge=rt.citation||rt.url;return{rank:Re+1,doc_id:rt.doc_id,block_id:rt.block_id,url:rt.url,citation:ge,title:rt.title||"Untitled",snippet:rt.snippet,score:rt.scores?.rerank||rt.scores?.dense||0,metadata:{site:rt.metadata?.site,lang:rt.metadata?.lang,contentType:rt.metadata?.content_type}}});return{success:!0,query:Pt.query,total:Pt.total,results:at,summary:`Found ${Pt.total} relevant results for "${P}". Top result: ${at[0]?.title||"N/A"}`}}catch(H){return{success:!1,error:H instanceof Error?H.message:"Unknown error occurred"}}}:null,[x,t,E]),It=m.useMemo(()=>x?.enabled?async function(P,V){const O=x.organizationId&&x.organizationId!=="default"?x.organizationId:w&&w.length>0?w[0]:void 0;try{const W={"Content-Type":"application/json"};E.current&&(W.Authorization=`Bearer ${E.current}`);const Q=await fetch(`${t}/fetch`,{method:"POST",headers:W,body:JSON.stringify({doc_id:P,block_ids:V,...O?{organizationId:O}:{}})});if(!Q.ok){const wt=await Q.text();return{success:!1,error:`Fetch failed: ${Q.status} ${wt}`}}const H=await Q.json();return{success:!0,blocks:H.blocks||[],fullContent:H.fullContent||"",pageUrl:H.pageUrl||"",pageTitle:H.pageTitle||"",summary:`Fetched ${H.blocks?.length||0} blocks from ${H.pageTitle||P}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[x,t,E]),Ct=m.useMemo(()=>{const C=[...o,...i,ee];return(!st||g)&&C.push(Vt),x?.enabled&&(tt&&C.push(tt),It&&C.push(It)),C},[o,i,ee,Vt,tt,It,x,st,g]),kt=m.useMemo(()=>Oa(Ct,a),[Ct,a]),bt=m.useMemo(()=>{const C=new Map,P=new Map(kt.map(V=>[V.name,V]));return C.set("getState",ee),(!st||g)&&C.set("setState",Vt),x?.enabled&&(tt&&C.set("searchDocs",tt),It&&C.set("fetchDocContent",It)),Ct.forEach(V=>{if(V===ee||V===Vt||V===tt||V===It)return;const O=V[_t];if(O){const Q=P.get(O);if(Q){C.set(Q.name,V);return}}const W=kt.find(Q=>Q.name===V.name);W&&C.set(W.name,V)}),C},[Ct,kt,ee,Vt,tt,It,x,st,g]),De=m.useMemo(()=>new Set(kt.map(C=>C.name)),[kt]),He=m.useMemo(()=>{const C=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!st||g)&&C.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const P=[];return x?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...kt,...C,...P]},[kt,x,st,g]),me=m.useMemo(()=>He.filter(C=>C.name==="getState"?!0:C.name==="setState"?!st||g:x?.enabled&&(C.name==="searchDocs"||C.name==="fetchDocContent")?!0:De.has(C.name)),[He,De,st,g,x]),Ne=m.useMemo(()=>{const C=new Set;return C.add("getState"),C.add("setState"),x?.enabled&&x.autoExecute!==!1&&(C.add("searchDocs"),C.add("fetchDocContent")),i.forEach(P=>{for(const[V,O]of bt.entries())if(O===P){C.add(V);break}}),C},[i,bt,x]);m.useEffect(()=>s||n?void 0:((async()=>{try{const P=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!P.ok)throw new Error("Failed to fetch token");const V=await P.json();j(V.clientToken),E.current=V.clientToken,I(V.expiresAt),A(null)}catch(P){console.error("[useAgent] Token fetch failed:",P),A(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{X.current&&clearTimeout(X.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!F||s||n)return;X.current&&clearTimeout(X.current);const C=Math.floor(Date.now()/1e3),P=F-C,O=Math.max(0,P-5);return X.current=setTimeout(async()=>{try{const W=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!W.ok)throw new Error("Failed to refresh token");const Q=await W.json();j(Q.clientToken),E.current=Q.clientToken,I(Q.expiresAt),A(null)}catch(W){console.error("[useAgent] Token refresh failed:",W),A(W instanceof Error?W.message:"Failed to refresh token")}},O*1e3),()=>{X.current&&clearTimeout(X.current)}},[F,e,JSON.stringify(r),s,n]);const wn=async(C,P={})=>{const V=P.headers?new Headers(P.headers):new Headers;V.delete("user-agent"),V.delete("User-Agent"),console.log("[useAgent] Making request to:",C),console.log("[useAgent] Method:",P.method||"GET"),console.log("[useAgent] Has Authorization header:",V.has("Authorization")),console.log("[useAgent] Client token available:",!!E.current);try{const O=await fetch(C,{...P,headers:V});if(!O.ok){console.error("[useAgent] Request failed:",O.status,O.statusText);const W=await O.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",W)}return O}catch(O){throw console.error("[useAgent] Fetch error:",O),O}},Tn=`${t}/chat`;console.log("[useAgent] Chat API URL:",Tn);const{messages:Ut,sendMessage:Xe,status:ne,error:se,stop:Ye,addToolResult:pe,setMessages:Je}=Ji.useChat({id:G||void 0,messages:u,transport:new Ln.DefaultChatTransport({api:Tn,fetch:wn,headers:()=>{const C={};return E.current?(C.Authorization=`Bearer ${E.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),C},body:()=>{const C=me.map(O=>({name:O.name,description:O.description,inputSchema:O.jsonSchema})),P=C.filter(O=>O.name==="getState"||O.name==="setState").map(O=>O.name),V=C.filter(O=>O.name==="searchDocs"||O.name==="fetchDocContent").map(O=>O.name);return P.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",P),V.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",V):x?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:C,systemPrompt:c,state:xt.current,...v&&{ragFilters:v}}}}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ut.forEach(C=>{C.role==="assistant"&&C.parts.forEach(P=>{if(!P.type?.startsWith("tool-")||P.state!=="input-available")return;const V=P.type.replace("tool-",""),O=P.toolCallId;if(nt.has(O))return;ot(Q=>new Set(Q).add(O));const W=bf(P.input);if(Ne.has(V)){const Q=bt.get(V);Q?(async()=>{try{const H=me.find(dt=>dt.name===V);let wt;if(H&&H.jsonSchema?.properties){const Pt=Object.keys(H.jsonSchema.properties).map(at=>W[at]);wt=await Q(...Pt)}else if(V==="getState")wt=Q();else if(V==="setState"){const dt=W.updates||W;wt=await Q(dt)}else wt=await Q(...Object.values(W));pe({toolCallId:O,tool:V,output:wt})}catch(H){console.error(`[useAgent] Error executing tool ${V}:`,H),pe({toolCallId:O,tool:V,output:`Error: ${H}`})}})():console.warn(`[useAgent] Tool ${V} not found in toolsMap`)}else S&&S({toolCall:{toolCallId:O,toolName:V,args:W}})})})},[Ut,Ne,bt,S,pe,nt,Vt,me]),m.useEffect(()=>{if(ne==="ready"&&Ut.length>0&&T){const C=Ut[Ut.length-1];C&&C.role==="assistant"&&T({message:C,messages:Ut,isAbort:!1,isDisconnect:!1,isError:!!se})}},[ne,Ut,se,T]);async function Hn(){if(!(!r?.id||!M)){J(!0);try{const P=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${M}`}})).json();q(P.conversations||[])}catch(C){console.error("Failed to fetch conversations:",C)}finally{J(!1)}}}m.useEffect(()=>{r?.id&&M&&Hn()},[JSON.stringify(r),M,t]),m.useEffect(()=>{if(!G||!E.current)return;(async()=>{Me(!0),Qt(null);try{const P=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:G},format:"json"})});if(!P.ok){const W=await P.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${P.status} ${W}`)}const O=(await P.json())?.value||{};xt.current=O,st||ke(O),f&&f(O),te.current=!0}catch(P){console.error("Failed to fetch state:",P);const V=P instanceof Error?P:new Error(String(P));Qt(V),te.current||(xt.current={},st?f&&f({}):(ke({}),f&&f({})),te.current=!0)}finally{Me(!1)}})()},[G,t,st,f]);async function Xn(C){it(C),J(!0);try{const P=await fetch(`${t}/conversations/${C}/messages`,{headers:{Authorization:`Bearer ${E.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const O=(await P.json()).messages||[];Je(O)}catch(P){console.error("Failed to load conversation messages:",P)}finally{J(!1)}}async function Ze(C){if(M)try{await fetch(`${t}/conversations/${C}`,{method:"DELETE",headers:{Authorization:`Bearer ${M}`}}),q(Y.filter(P=>P._id!==C)),C===G&&Kt()}catch(P){console.error("Failed to delete conversation:",P)}}function Kt(){const C=crypto.randomUUID();it(C),Je([]),ot(new Set),xt.current={},st?f&&f({}):(ke({}),f&&f({})),te.current=!1}function Yn(C){pe(C)}async function Jn(C){const P={...xt.current,...C};xt.current=P,st||ke(P),f&&f(P);try{await Ee(C)}catch(V){throw V}}return{id:G,messages:Ut,status:ne,error:se,sendMessage:Xe,stop:Ye,addToolOutput:Yn,setMessages:Je,conversations:Y,loadConversation:Xn,deleteConversation:Ze,startNewConversation:Kt,isLoadingConversations:_,clientToken:M,tokenError:D,state:Zt,setState:Jn,isStateLoading:Bt,stateError:zt}}exports.verifyToken=fc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=_t;exports.ArctenAgent=vf;exports.preserveToolName=Qh;exports.useAgent=wf;
18
+ `);if("functions"in t&&typeof t.functions=="object"){const o=t;n=o.functions,s=o.toolOrder}else n=t,s=void 0;const r=new Set;return e.map(o=>{const i=bf(o,n,r,s);if(!i){const a=o.name,u=o[Ye]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${u}". This tool will be excluded.
19
+ To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function vf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return c.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:c.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&c.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[c.jsxs(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[c.jsx(oe.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),c.jsx(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:c.jsx(oe.X,{className:"h-3 w-3"})})]})]})})}function wf({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=f.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([u])=>!i.includes(u))),l=Object.keys(a).length>0;return c.jsxs("div",{className:"my-1",children:[c.jsxs("button",{onClick:()=>l&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${l?"cursor-pointer hover:bg-muted/80":""}`,children:[l&&c.jsx("span",{className:"transition-transform duration-200",children:r?c.jsx(oe.ChevronDown,{className:"h-3 w-3"}):c.jsx(oe.ChevronRight,{className:"h-3 w-3"})}),n?c.jsx(oe.X,{className:"h-3 w-3"}):s?c.jsx(oe.Zap,{className:"h-3 w-3"}):c.jsx(oe.Check,{className:"h-3 w-3"}),c.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&c.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:c.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,d])=>c.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[c.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),c.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},u))})})]})}function Tf({...e}){return c.jsx(ir.Root,{"data-slot":"collapsible",...e})}function Sf({...e}){return c.jsx(ir.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function jf({...e}){return c.jsx(ir.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Cf=f.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Ur=f.memo(({className:e,...t})=>typeof window>"u"?null:c.jsx(f.Suspense,{fallback:null,children:c.jsx(Cf,{className:ae("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Ur.displayName="Response";const Pf=Object.freeze(Object.defineProperty({__proto__:null,Response:Ur},Symbol.toStringTag,{value:"Module"})),Af=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=mf.create(t),i=f.useMemo(()=>(e?.length??0)*r,[e,r]);return c.jsx(o,{animate:{backgroundPosition:"0% center"},className:ae("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},kf=f.memo(Af),tl=f.createContext(null),Mf=()=>{const e=f.useContext(tl);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Ef=1e3,Nf=1e3,nl=f.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,u]=Yr.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,h]=Yr.useControllableState({prop:o,defaultProp:0}),[m,g]=f.useState(!1),[v,b]=f.useState(null);f.useEffect(()=>{t?v===null&&b(Date.now()):v!==null&&(h(Math.ceil((Date.now()-v)/Nf)),b(null))},[t,v,h]),f.useEffect(()=>{if(s&&!t&&l&&!m){const x=setTimeout(()=>{u(!1),g(!0)},Ef);return()=>clearTimeout(x)}},[t,l,s,u,m]);const y=x=>{u(x)};return c.jsx(tl.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:u,duration:d},children:c.jsx(Tf,{className:ae("not-prose mb-4",e),onOpenChange:y,open:l,...a,children:i})})}),Df=(e,t)=>e||t===0?c.jsx(kf,{duration:1,children:"Thinking..."}):t===void 0?c.jsx("p",{children:"Thought for a few seconds"}):c.jsxs("p",{children:["Thought for ",t," seconds"]}),sl=f.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Mf();return c.jsx(Sf,{className:ae("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??c.jsxs(c.Fragment,{children:[c.jsx(oe.BrainIcon,{className:"size-4"}),Df(s,o),c.jsx(oe.ChevronDownIcon,{className:ae("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),rl=f.memo(({className:e,children:t,...n})=>c.jsx(jf,{className:ae("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:c.jsx(Ur,{className:"grid gap-2",children:t})}));nl.displayName="Reasoning";sl.displayName="ReasoningTrigger";rl.displayName="ReasoningContent";function mo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Rf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=mo(s.domain);return c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsxs("button",{className:ae("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[c.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),c.jsx("span",{className:"leading-none",children:s.domain})]})}),c.jsx(yt,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>{const i=o.title||o.domain;return c.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ae("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[c.jsx("img",{src:mo(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),c.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function Vf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!0}){const u=f.useRef(null),[d,h]=f.useState([]);f.useEffect(()=>{if(!a||!u.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const y=u.current;let x,j=!1;const k=new WeakSet,N=()=>{if(!u.current||j)return;j=!0;const B=u.current,O=/\[(\d+)\]/g,E=document.createTreeWalker(B,NodeFilter.SHOW_TEXT,null),F=[];let S;for(;S=E.nextNode();)if(S.nodeType===Node.TEXT_NODE&&!k.has(S)){const _=S,D=_.textContent||"";let W=_.parentElement,le=!1;for(;W&&W!==B;){if(W.tagName==="A"||W.tagName==="CODE"||W.tagName==="PRE"){le=!0;break}W=W.parentElement}if(!le){const Z=Array.from(D.matchAll(O)).filter(re=>{if(!re[1])return!1;const H=parseInt(re[1],10);return n.has(H)});Z.length>0&&F.push({node:_,matches:Z})}}if(F.length===0){j=!1;return}const M=[];F.forEach(({node:_,matches:D})=>{k.add(_);const W=_.textContent||"",le=document.createDocumentFragment();let se=0;D.forEach(Z=>{if(!Z[1])return;Z.index!==void 0&&Z.index>se&&le.appendChild(document.createTextNode(W.slice(se,Z.index)));const re=document.createElement("span");re.className="inline-flex items-center citation-button-container";const H=parseInt(Z[1],10);re.setAttribute("data-citation",Z[1]),le.appendChild(re),M.push({element:re,citationNum:H}),se=(Z.index||0)+Z[0].length}),se<W.length&&le.appendChild(document.createTextNode(W.slice(se))),_.parentNode&&_.parentNode.replaceChild(le,_)}),M.length>0&&h(_=>{const D=new Set(_.map(se=>se.element)),W=_.filter(se=>se.element.isConnected),le=M.filter(se=>!D.has(se.element));return[...W,...le]}),j=!1},R=new MutationObserver(()=>{clearTimeout(x),x=setTimeout(N,100)});return R.observe(y,{childList:!0,subtree:!0,characterData:!0}),x=setTimeout(N,200),()=>{R.disconnect(),clearTimeout(x)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function g(y){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(y)}&sz=16`}function v(y){try{return new URL(y).hostname.replace(/^www\./,"")}catch{return y}}const b=a&&l&&m?c.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[c.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((y,x)=>{const j=y.title||y.baseUrl,k=v(y.url),N=g(k);return c.jsxs("a",{href:y.url,target:"_blank",rel:"noopener noreferrer",className:ae("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[c.jsx("img",{src:N,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:R=>{const B=R.target;B.style.display="none"}}),c.jsx("span",{className:"leading-none",children:j})]},`group-${x}`)}):Array.from(n.entries()).sort(([y],[x])=>y-x).map(([y,x])=>{const j=v(x),k=g(j);return c.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:ae("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[c.jsx("img",{src:k,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:N=>{const R=N.target;R.style.display="none"}}),c.jsx("span",{className:"leading-none",children:x})]},y)})})]}):null;return c.jsxs("div",{className:i,children:[c.jsx("div",{ref:u,children:c.jsx(o,{children:e})}),a&&d.filter(({element:y})=>y.isConnected).map(({element:y,citationNum:x},j)=>{if(!t.find(R=>R.number===x))return null;const N=Array.from(new Map(t.map(R=>{const B=R.url.replace(/\/+$/,""),O=s?.find(E=>E.url.replace(/\/+$/,"")===B);return[B,{number:R.number,url:R.url,domain:v(R.url),title:O?.title}]})).values());return Ml.createPortal(c.jsx(Rf,{sources:N,citationNumber:x},`citation-${x}-${y}`),y,`citation-${x}-${j}`)}),b]})}function cn({...e}){return c.jsx($t.Root,{"data-slot":"dialog",...e})}function If({...e}){return c.jsx($t.Portal,{"data-slot":"dialog-portal",...e})}function Of({className:e,...t}){return c.jsx($t.Overlay,{"data-slot":"dialog-overlay",className:ae("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function un({className:e,children:t,showCloseButton:n=!0,...s}){return c.jsxs(If,{"data-slot":"dialog-portal",children:[c.jsx(Of,{}),c.jsxs($t.Content,{"data-slot":"dialog-content",className:ae("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...s,children:[t,n&&c.jsxs($t.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(oe.XIcon,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function dn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:ae("flex flex-col gap-2 text-center sm:text-left",e),...t})}function hn({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:ae("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function fn({className:e,...t}){return c.jsx($t.Title,{"data-slot":"dialog-title",className:ae("text-lg leading-none font-semibold",e),...t})}function mn({className:e,...t}){return c.jsx($t.Description,{"data-slot":"dialog-description",className:ae("text-muted-foreground text-sm",e),...t})}function pn({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:ae("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-white px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...n})}function $f({isOpen:e,title:t="Password Required",description:n="Please enter your password to continue",placeholder:s="Enter password...",onComplete:r}){const[o,i]=f.useState(""),[a,l]=f.useState(!1),[u,d]=f.useState(!1),h=async g=>{if(g.preventDefault(),!!o.trim()){d(!0);try{r(o)}finally{d(!1)}}},m=()=>{i(""),r(null)};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(dn,{children:[c.jsx(fn,{children:t}),c.jsx(mn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsxs("div",{className:"relative",children:[c.jsx(pn,{type:a?"text":"password",value:o,onChange:g=>i(g.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:u}),c.jsx("button",{type:"button",onClick:()=>l(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:u,children:a?c.jsx(oe.EyeOff,{className:"h-4 w-4"}):c.jsx(oe.Eye,{className:"h-4 w-4"})})]})}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||u,children:u?"Submitting...":"Submit"})]})]})})})}function Lf({isOpen:e,title:t="Email Required",description:n="Please enter your email address",placeholder:s="Enter email address...",onComplete:r}){const[o,i]=f.useState(""),[a,l]=f.useState(!0),[u,d]=f.useState(!1),h=b=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b),m=b=>{i(b),b.trim()?l(h(b)):l(!0)},g=async b=>{if(b.preventDefault(),!o.trim()||!h(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:g,children:[c.jsxs(dn,{children:[c.jsxs(fn,{className:"flex items-center gap-2",children:[c.jsx(oe.Mail,{className:"h-5 w-5"}),t]}),c.jsx(mn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(pn,{type:"email",value:o,onChange:b=>m(b.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:v,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Ff({isOpen:e,title:t="Phone Number Required",description:n="Please enter your phone number",placeholder:s="Enter phone number...",onComplete:r}){const[o,i]=f.useState(""),[a,l]=f.useState(!0),[u,d]=f.useState(!1),h=y=>{const x=y.replace(/\D/g,"");return x.length<=3?x:x.length<=6?`(${x.slice(0,3)}) ${x.slice(3)}`:`(${x.slice(0,3)}) ${x.slice(3,6)}-${x.slice(6,10)}`},m=y=>y.replace(/\D/g,"").length===10,g=y=>{const x=h(y);i(x),x.trim()?l(m(x)):l(!0)},v=async y=>{if(y.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const x=o.replace(/\D/g,"");r(x)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:v,children:[c.jsxs(dn,{children:[c.jsxs(fn,{className:"flex items-center gap-2",children:[c.jsx(oe.Phone,{className:"h-5 w-5"}),t]}),c.jsx(mn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(pn,{type:"tel",value:o,onChange:y=>g(y.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:u}),!a&&c.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:b,disabled:u,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!o.trim()||!a||u,children:u?"Submitting...":"Submit"})]})]})})})}function Bf({isOpen:e,title:t="PIN Required",description:n="Please enter your PIN",placeholder:s="Enter PIN...",length:r=4,onComplete:o}){const[i,a]=f.useState(""),[l,u]=f.useState(!1),d=g=>{const v=g.replace(/\D/g,"");a(v.slice(0,r))},h=async g=>{if(g.preventDefault(),i.length===r){u(!0);try{o(i)}finally{u(!1)}}},m=()=>{a(""),o(null)};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:h,children:[c.jsxs(dn,{children:[c.jsxs(fn,{className:"flex items-center gap-2",children:[c.jsx(oe.Shield,{className:"h-5 w-5"}),t]}),c.jsx(mn,{children:n})]}),c.jsxs("div",{className:"py-4",children:[c.jsx(pn,{type:"password",value:i,onChange:g=>d(g.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:l}),c.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function Vs({isOpen:e,title:t="Secure Input Required",description:n="Please enter the requested information",placeholder:s="Enter value...",type:r="password",onComplete:o}){const[i,a]=f.useState(""),[l,u]=f.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){u(!0);try{o(i)}finally{u(!1)}}},h=()=>{a(""),o(null)};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,children:c.jsxs("form",{onSubmit:d,children:[c.jsxs(dn,{children:[c.jsxs(fn,{className:"flex items-center gap-2",children:[c.jsx(oe.Lock,{className:"h-5 w-5"}),t]}),c.jsx(mn,{children:n})]}),c.jsx("div",{className:"py-4",children:c.jsx(pn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:h,disabled:l,children:"Cancel"}),c.jsx(je,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function zf({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=f.useState(()=>{const S={};return s.forEach(M=>{S[M.name]=M.value||""}),S}),[u,d]=f.useState({}),[h,m]=f.useState({}),[g,v]=f.useState(!1),b=S=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)?null:"Please enter a valid email address",y=S=>S.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",x=(S,M=4)=>S.length===M?null:`PIN must be ${M} digits`,j=S=>{const M=S.replace(/\D/g,"");return M.length<=3?M:M.length<=6?`(${M.slice(0,3)}) ${M.slice(3)}`:`(${M.slice(0,3)}) ${M.slice(3,6)}-${M.slice(6,10)}`},k=(S,M,_)=>{let D=M,W=null;switch(_.type){case"phone":D=j(M),D.trim()&&(W=y(D));break;case"email":M.trim()&&(W=b(M));break;case"pin":D=M.replace(/\D/g,"").slice(0,6),D.trim()&&(W=x(D));break}!W&&_.validation&&D.trim()&&(W=_.validation(D)),l(le=>({...le,[S]:D})),d(le=>({...le,[S]:W||""}))},N=()=>{const S={};let M=!0;return s.forEach(_=>{const D=a[_.name]||"";let W=null;if(_.required&&!D.trim())W=`${_.label} is required`;else if(D.trim()){switch(_.type){case"email":W=b(D);break;case"phone":W=y(D);break;case"pin":W=x(D);break}!W&&_.validation&&(W=_.validation(D))}W&&(S[_.name]=W,M=!1)}),d(S),M},R=async S=>{if(S.preventDefault(),!!N()){v(!0);try{const M={};s.forEach(_=>{const D=a[_.name]?.trim();D&&(_.type==="phone"?M[_.name]=D.replace(/\D/g,""):M[_.name]=D)}),r(M)}finally{v(!1)}}},B=()=>{l({}),d({}),m({}),r(null)},O=S=>{m(M=>({...M,[S]:!M[S]}))},E=S=>{switch(S.type){case"password":return h[S.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},F=S=>{if(S.placeholder)return S.placeholder;switch(S.type){case"email":return"Enter email address...";case"phone":return"Enter phone number...";case"password":return"Enter password...";case"pin":return"Enter PIN...";case"ssn":return"XXX-XX-XXXX";case"creditCard":return"XXXX XXXX XXXX XXXX";default:return`Enter ${S.label.toLowerCase()}...`}};return c.jsx(cn,{open:e,children:c.jsx(un,{showCloseButton:!1,className:"max-w-md",children:c.jsxs("form",{onSubmit:R,children:[c.jsxs(dn,{children:[c.jsx(fn,{children:t}),n&&c.jsx(mn,{children:n})]}),c.jsx("div",{className:"py-4 space-y-4",children:s.map(S=>c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-medium mb-1",children:[S.label,S.required&&c.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),c.jsxs("div",{className:"relative",children:[c.jsx(pn,{type:E(S),value:a[S.name]||"",onChange:M=>k(S.name,M.target.value,S),placeholder:F(S),className:u[S.name]?"border-red-500":"",disabled:g,autoFocus:S===s[0],maxLength:S.type==="pin"?6:S.type==="phone"?14:void 0}),S.type==="password"&&c.jsx("button",{type:"button",onClick:()=>O(S.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:g,children:h[S.name]?c.jsx(oe.EyeOff,{className:"h-4 w-4"}):c.jsx(oe.Eye,{className:"h-4 w-4"})})]}),u[S.name]&&c.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[c.jsx(oe.AlertCircle,{className:"h-3 w-3"}),u[S.name]]})]},S.name))}),c.jsxs(hn,{children:[c.jsx(je,{type:"button",variant:"ghost",onClick:B,disabled:g,children:i}),c.jsx(je,{type:"submit",disabled:g,children:g?"Submitting...":o})]})]})})})}const il=f.createContext(void 0);function Uf(){const e=f.useContext(il);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function _f({children:e}){const[t,n]=f.useState(null),[s,r]=f.useState(null),[o,i]=f.useState(null),[a,l]=f.useState(null),u=v=>new Promise(b=>{n(v),i(()=>b)}),d=v=>new Promise(b=>{r(v),l(()=>b)}),h=v=>{o&&(o(v),i(null)),n(null)},m=v=>{a&&(a(v),l(null)),r(null)},g=()=>{if(s){const b=s.fields.map(y=>({name:y.name,type:y.type==="text"?"text":y.type==="password"?"password":y.type==="email"?"email":y.type==="phone"?"phone":y.type==="pin"?"pin":y.type==="ssn"?"ssn":y.type==="creditCard"?"creditCard":"text",label:y.label,placeholder:y.placeholder,required:y.required!==!1,value:y.value}));return c.jsx(zf,{isOpen:!0,title:s.title,description:s.description,fields:b,onComplete:m})}if(!t)return null;const v={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:h};switch(t.type){case"password":return c.jsx($f,{...v});case"email":return c.jsx(Lf,{...v});case"phone":return c.jsx(Ff,{...v});case"pin":return c.jsx(Bf,{...v});case"ssn":return c.jsx(Vs,{...v,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return c.jsx(Vs,{...v,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return c.jsx(Vs,{...v})}};return c.jsxs(il.Provider,{value:{showSecureModal:u,showSecureForm:d},children:[e,g()]})}function Xf(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function qf(e){try{const t=new URL(e),s=t.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return t.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||t.hostname}catch{const t=e.indexOf("#"),n=t!==-1?e.substring(0,t):e,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function po(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,l=new Map,u=new Map;if(s&&s[1]){const E=s[1],F=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let S;for(;(S=F.exec(E))!==null;)if(S[1]&&S[2]){const M=parseInt(S[1],10),_=S[2].replace(/[.,;:!?]+$/,""),D=_.replace(/\/+$/,"");if(a.has(D)||a.set(D,_),i.has(D)||i.set(D,[]),i.get(D).push(M),!l.has(D))l.set(D,M);else{const W=l.get(D);M<W&&l.set(D,M)}}for(const[M,_]of i.entries()){const D=l.get(M);for(const W of _)W!==D&&u.set(W,D)}for(const[M,_]of l.entries()){const D=a.get(M)||M;r.set(_,D),o.push({number:_,url:D})}}let d,h=t;s&&s[0]&&(d=s[0],h=t.replace(n,""));const m=[];let g=0;const v=/```[\s\S]*?```|`[^`]+`/g;let b;for(;(b=v.exec(h))!==null;)b.index>g&&m.push({type:"text",content:h.slice(g,b.index),start:g,end:b.index}),m.push({type:"code",content:b[0],start:b.index,end:b.index+b[0].length}),g=b.index+b[0].length;g<h.length&&m.push({type:"text",content:h.slice(g),start:g,end:h.length});const y=m.map(E=>{if(E.type==="code")return E.content;let F=E.content;return F=F.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(M,_,D)=>{const W=parseInt(_,10),le=D.replace(/\/+$/,""),se=u.get(W)||W;return l.has(le)||(l.set(le,se),r.has(se)||(r.set(se,D),o.push({number:se,url:D}))),`[${se}]`}),F=F.replace(/\[(\d+)\]/g,(M,_)=>{const D=parseInt(_,10);return`[${u.get(D)||D}]`}),F}),x=[];for(const[E,F]of l.entries()){const S=a.get(E)||E,{baseUrl:M,anchor:_}=Xf(S),D=qf(S);x.push({url:S,baseUrl:M,numbers:[F],anchor:_,title:D})}x.sort((E,F)=>(E.numbers[0]||0)-(F.numbers[0]||0));const j=new Map;let k=1;for(const E of x){const F=E.numbers[0];j.set(F,k),E.numbers=[k],k++}const N=new Map;for(const[E,F]of r.entries()){const S=j.get(E);S&&N.set(S,F)}const R=o.map(E=>{const F=j.get(E.number);return F?{number:F,url:E.url}:E}).filter(E=>j.has(E.number)),B=Array.from(j.entries()).sort((E,F)=>F[0]-E[0]);let O=y.join("");for(const[E,F]of B){const S=new RegExp(`\\[${E}\\](?!\\d)`,"g");O=O.replace(S,`[${F}]`)}return{processedText:O,citations:R.sort((E,F)=>E.number-F.number),citationMap:N,groupedCitations:x,referencesText:d}}function Mn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Mn(t)}catch{return e}if(Array.isArray(e))return e.map(Mn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Mn(s);return t}return e}function Is(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Mn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Mn(e):{}}function Wf({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:l=800,initiallyExpanded:u=!1,tools:d=[],safeTools:h=[],toolMetadata:m,systemPrompt:g="",tokenEndpoint:v="/api/arcten/token",apiBaseUrl:b="https://api.arcten.com",user:y,state:x,onStateChange:j,allowStateEdits:k=!0,sources:N,ragConfig:R,showCitations:B=!0,sensitiveParams:O,autoDetectSensitive:E=!1}){const{showSecureModal:F}=Uf(),S=f.useMemo(()=>R!==void 0?R:N&&N.length>0?{enabled:!0,organizationId:N[0],autoExecute:!0,filters:void 0}:{enabled:!1},[N,R]),[M,_]=f.useState(null),D=f.useRef(null),[W,le]=f.useState(null),[se,Z]=f.useState(null),re=f.useRef(null),H=x!==void 0,[$e,Ze]=f.useState({}),Te=f.useRef({});H&&x?Te.current=x:H||(Te.current=$e);const[ms,Lt]=f.useState(!1),[_r,Tt]=f.useState(null),Qe=f.useRef(!1),[Le,gn]=f.useState(u),[Fe,Ft]=f.useState(i),[Bt,de]=f.useState(600),[yn,We]=f.useState(!1),[J,xn]=f.useState(!1),[Be,St]=f.useState(!1),[Me,ut]=f.useState({x:100,y:100}),[jt,Ct]=f.useState(!1),[et,tt]=f.useState({x:0,y:0}),[zn,ps]=f.useState(!1),bn=f.useRef(null),zt=f.useRef(null),[Pt,Ut]=f.useState(""),[Ke,nt]=f.useState(null),[_t,st]=f.useState("Thinking..."),[rt,it]=f.useState(new Set),[Un,Xt]=f.useState(""),[Ge,gs]=f.useState([]),[qt,ze]=f.useState(!1),[vn,Wt]=f.useState([]),[Ne,wn]=f.useState(()=>typeof window<"u"?crypto.randomUUID():null),[Ce,dt]=f.useState(!1),[Xr,Kt]=f.useState(!1),[qr,At]=f.useState([]),_n=f.useCallback(async(p,C=3)=>{if(!Ne||!D.current)return;const I=async()=>{const L=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Ne,updates:p},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const te=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${te}`)}};for(let $=0;$<C;$++)try{await I(),Tt(null);return}catch(L){if($===C-1){const te=L instanceof Error?L:new Error(String(L));throw Tt(te),console.error("Failed to sync state to Convex after retries:",L),te}await new Promise(te=>setTimeout(te,Math.pow(2,$)*100))}},[Ne,b,D]),kt=f.useMemo(()=>function(){return Te.current},[]),w=f.useMemo(()=>async function(C){const I={...Te.current,...C};Te.current=I,H||Ze(I),j&&j(I);try{await _n(C)}catch($){throw $}},[_n,j,H]);f.useEffect(()=>{H&&x&&(Te.current=x)},[H,x]);const P=f.useMemo(()=>S?.enabled?async function(C,I=20,$){if(N&&N.length>1){const te=N.map(G=>fetch(`${b}/search`,{method:"POST",headers:{"Content-Type":"application/json",...D.current?{Authorization:`Bearer ${D.current}`}:{}},body:JSON.stringify({q:C,k:Math.min(I,100),organizationId:G,...Object.keys(U).length>0?{filters:U}:{}})}).then(q=>q.ok?q.json():null)),Y=await Promise.all(te),ie=[];for(const G of Y)G?.candidates&&ie.push(...G.candidates);ie.sort((G,q)=>{const ye=G.scores?.rerank||G.scores?.dense||0;return(q.scores?.rerank||q.scores?.dense||0)-ye});const z=ie.slice(0,I).map((G,q)=>{const ye=G.citation||G.url;return{rank:q+1,doc_id:G.doc_id,block_id:G.block_id,url:G.url,citation:ye,title:G.title||"Untitled",snippet:G.snippet,score:G.scores?.rerank||G.scores?.dense||0,metadata:{site:G.metadata?.site,lang:G.metadata?.lang,contentType:G.metadata?.content_type}}});return{success:!0,query:C,total:ie.length,results:z,summary:`Found ${ie.length} relevant results across ${N.length} source(s) for "${C}". Top result: ${z[0]?.title||"N/A"}`}}const L=S.organizationId&&S.organizationId!=="default"?S.organizationId:void 0,U={...S.filters,...$};try{const te={q:C,k:Math.min(I,100)};L&&(te.organizationId=L),Object.keys(U).length>0&&(te.filters=U);const Y={"Content-Type":"application/json"};D.current&&(Y.Authorization=`Bearer ${D.current}`);const ie=await fetch(`${b}/search`,{method:"POST",headers:Y,body:JSON.stringify(te)});if(!ie.ok){const q=await ie.text();return{success:!1,error:`Search failed: ${ie.status} ${q}`}}const z=await ie.json(),G=z.candidates.map((q,ye)=>{const me=q.citation||q.url;return{rank:ye+1,doc_id:q.doc_id,block_id:q.block_id,url:q.url,citation:me,title:q.title||"Untitled",snippet:q.snippet,score:q.scores?.rerank||q.scores?.dense||0,metadata:{site:q.metadata?.site,lang:q.metadata?.lang,contentType:q.metadata?.content_type}}});return{success:!0,query:z.query,total:z.total,results:G,summary:`Found ${z.total} relevant results for "${C}". Top result: ${G[0]?.title||"N/A"}`}}catch(te){return{success:!1,error:te instanceof Error?te.message:"Unknown error occurred"}}}:null,[R,b,D]),T=f.useMemo(()=>S?.enabled?async function(C,I){const $=S.organizationId&&S.organizationId!=="default"?S.organizationId:N&&N.length>0?N[0]:void 0;try{const L={"Content-Type":"application/json"};D.current&&(L.Authorization=`Bearer ${D.current}`);const U=await fetch(`${b}/fetch`,{method:"POST",headers:L,body:JSON.stringify({doc_id:C,block_ids:I,...$?{organizationId:$}:{}})});if(!U.ok){const Y=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${Y}`}}const te=await U.json();return{success:!0,blocks:te.blocks||[],fullContent:te.fullContent||"",pageUrl:te.pageUrl||"",pageTitle:te.pageTitle||"",summary:`Fetched ${te.blocks?.length||0} blocks from ${te.pageTitle||C}`}}catch(L){return{success:!1,error:L instanceof Error?L.message:"Unknown error occurred"}}}:null,[R,b,D]),A=f.useMemo(()=>{const p=[...d,...h,kt];return(!H||k)&&p.push(w),S?.enabled&&(P&&p.push(P),T&&p.push(T)),p},[d,h,kt,w,P,T,H,k,S]),V=f.useMemo(()=>el(A,m),[A,m]),X=f.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!H||k)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const C=[];return S?.enabled&&C.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...V,...p,...C]},[V,H,k,S]),Q=f.useMemo(()=>new Set(X.map(p=>p.name)),[X]),ce=f.useMemo(()=>X.filter(p=>p.name==="getState"?!0:p.name==="setState"?!H||k:Q.has(p.name)),[X,Q,H,k]),pe=f.useMemo(()=>{const p=new Map,C=new Map(V.map(I=>[I.name,I]));return p.set("getState",kt),(!H||k)&&p.set("setState",w),S?.enabled&&(P&&p.set("searchDocs",P),T&&p.set("fetchDocContent",T)),A.forEach(I=>{if(I===kt||I===w||I===P||I===T)return;const $=I[Ye];if($){const U=C.get($);if(U){p.set(U.name,I);return}}const L=X.find(U=>U.name===I.name);L&&p.set(L.name,I)}),p},[A,X,kt,w,P,T,H,k,S]),be=f.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),S?.enabled&&S.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const C=new Map(X.map(I=>[I.name,I]));return h.forEach(I=>{const $=I[Ye];if($&&C.has($))p.add($);else{const L=X.find(U=>U.name===I.name);L&&p.add(L.name)}}),p},[h,X,S]),ne=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];f.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&gn(JSON.parse(p));const C=localStorage.getItem("arcten-sidebar-width");C&&Ft(parseInt(C));const I=localStorage.getItem("arcten-sidebar-height");I&&de(parseInt(I));const $=localStorage.getItem("arcten-sidebar-detached");$&&xn(JSON.parse($));const L=localStorage.getItem("arcten-sidebar-position");if(L){const te=JSON.parse(L),Y=50,ie=Math.max(Y-i,Math.min(te.x,window.innerWidth-Y)),z=Math.max(0,Math.min(te.y,window.innerHeight-Y));ut({x:ie,y:z})}const U=localStorage.getItem("arcten-sidebar-minimized");U&&St(JSON.parse(U)),ps(!0)}},[]);const ee=f.useMemo(()=>y,[y?.id]);f.useEffect(()=>((async()=>{try{const C=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:ee})});if(!C.ok)throw new Error("Failed to fetch token");const I=await C.json();_(I.clientToken),D.current=I.clientToken,Z(I.expiresAt),le(null)}catch(C){le(C instanceof Error?C.message:"Failed to fetch token")}})(),()=>{re.current&&clearTimeout(re.current)}),[v,ee]),f.useEffect(()=>{if(!se)return;re.current&&clearTimeout(re.current);const p=Math.floor(Date.now()/1e3),C=se-p,$=Math.max(0,C-5);return re.current=setTimeout(async()=>{try{const L=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:ee})});if(!L.ok)throw new Error("Failed to refresh token");const U=await L.json();_(U.clientToken),D.current=U.clientToken,Z(U.expiresAt),le(null)}catch(L){console.error("Token refresh failed:",L),le(L instanceof Error?L.message:"Failed to refresh token")}},$*1e3),()=>{re.current&&clearTimeout(re.current)}},[se,v,ee]),f.useEffect(()=>{(async()=>{if(A.length!==0)try{const C=A.map($=>({name:$.name,code:$.toString()})),I=await fetch(`${b}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:C})});if(I.ok){const $=await I.json();gs($.tools)}}catch(C){console.error("Failed to fetch tool descriptions:",C)}})()},[A]),f.useEffect(()=>{Promise.resolve().then(()=>Pf).then(p=>{nt(()=>p.Response)})},[]),f.useEffect(()=>{const p=()=>{Xt(window.location.pathname)};p(),window.addEventListener("popstate",p);const C=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(C)}},[]);const Ee=f.useCallback(async()=>{if(!(!ee?.id||!M)){Kt(!0);try{const C=await(await fetch(`${b}/conversations`,{headers:{Authorization:`Bearer ${M}`}})).json();Wt(C.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{Kt(!1)}}},[ee?.id,M,b]);f.useEffect(()=>{ee?.id&&M&&Ee()},[ee?.id,M,Ee]);function ve(p){const C=Math.floor((Date.now()-p)/1e3);return C<60?"now":C<3600?`${Math.floor(C/60)}m`:C<86400?`${Math.floor(C/3600)}h`:`${Math.floor(C/86400)}d`}function ht(){const p=crypto.randomUUID();wn(p),Wn([]),At([]),dt(!1);const C=H?x||{}:{};Te.current=C,H||Ze(C),j&&j(C),Qe.current=!1}async function He(p){if(M)try{await fetch(`${b}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${M}`}}),Wt(vn.filter(C=>C._id!==p)),p===Ne&&ht()}catch(C){console.error("Failed to delete conversation:",C)}}async function ys(p){wn(p.chatId),dt(!1),Kt(!0);try{const C=await fetch(`${b}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${D.current}`}});if(!C.ok)throw new Error(`Failed to fetch messages: ${C.statusText}`);const $=(await C.json()).messages||[];Wn($),At($)}catch(C){console.error("Failed to load conversation messages:",C);const I=p.messages||[];Wn(I),At(I)}finally{Kt(!1)}}const Xn=async(p,C={})=>{const I=C.headers?new Headers(C.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(p,{...C,headers:I})},{messages:ot,sendMessage:cl,status:Ue,error:Wr,stop:qn,addToolResult:Mt,setMessages:Wn}=go.useChat({id:Ne||void 0,transport:new ss.DefaultChatTransport({api:`${b}/chat`,fetch:Xn,headers:()=>{const p={};return D.current&&(p.Authorization=`Bearer ${D.current}`),p},body:()=>({tools:ce.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),systemPrompt:g,currentRoute:Un,state:Te.current})}),sendAutomaticallyWhen:ss.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{const p=ot[ot.length-1];if(!p||p.role!=="assistant")return;const C=p.parts?.filter(I=>I.type?.startsWith("tool-")&&I.state==="input-available"&&typeof I.toolCallId=="string"&&I.input!==void 0)||[];for(const I of C){const $=I,L=$.type?.replace("tool-","")||"",U=$.toolCallId;if(be.has(L)){if(rt.has(U))continue;it(Y=>Y.has(U)?Y:new Set(Y).add(U)),(async()=>{try{const Y=pe.get(L);if(!Y){console.warn(`[ArctenAgent] Tool ${L} not found in toolsMap. Available tools:`,Array.from(pe.keys())),Mt({toolCallId:U,tool:L,output:`Error: Tool ${L} not found`}),it(q=>{const ye=new Set(q);return ye.delete(U),ye});return}const ie=Is($.input),z=ce.find(q=>q.name===L);let G;if(z&&z.jsonSchema?.properties){const ye=Object.keys(z.jsonSchema.properties).map(me=>ie[me]);console.log(`[ArctenAgent] Executing safe tool ${L} with args:`,ye),G=await Y(...ye)}else if(L==="getState")G=Y();else if(L==="setState"){const q=ie.updates||ie;G=await Y(q)}else G=await Y(...Object.values(ie));console.log(`[ArctenAgent] Tool ${L} completed, result:`,G),Mt({toolCallId:U,tool:L,output:G}),it(q=>{const ye=new Set(q);return ye.delete(U),ye})}catch(Y){console.error(`[ArctenAgent] Error executing safe tool ${L}:`,Y),Mt({toolCallId:U,tool:L,output:`Error: ${Y instanceof Error?Y.message:String(Y)}`}),it(ie=>{const z=new Set(ie);return z.delete(U),z})}})()}}},[ot,be,pe,ce,Mt]),f.useEffect(()=>{if(!Ne||!D.current)return;(async()=>{Lt(!0),Tt(null);try{const I=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,$=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Ne},format:"json"})});if(!$.ok){if($.status===404||$.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${$.status}), using empty state`);const z=H?x||{}:{};Te.current=z,H||Ze(z),j&&j(z),Qe.current=!0,Lt(!1);return}const ie=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${$.status} ${ie}`)}const U=(await $.json())?.value||{},te=!Qe.current;let Y;te?(Y={...H?x||{}:{},...U},Qe.current=!0):Y=U,Te.current=Y,H||Ze(Y),j&&j(Y)}catch(C){C instanceof TypeError&&C.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",C):console.error("[ArctenAgent] Failed to fetch state:",C);const $=C instanceof Error?C:new Error(String(C));if(Tt($),!Qe.current){const L=H?x||{}:{};Te.current=L,H||Ze(L),j&&j(L),Qe.current=!0}}finally{Lt(!1)}})()},[Ne,b,H,x,j]),f.useEffect(()=>{Le&&zt.current&&zt.current.focus()},[Le,ot]);function ul(){gn(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function dl(){gn(!1),localStorage.setItem("arcten-sidebar-expanded","false")}f.useEffect(()=>{},[Le]),f.useEffect(()=>{bn.current&&bn.current.scrollIntoView({behavior:"smooth"})},[ot]),f.useEffect(()=>{function p(C){C.key==="Escape"&&(Ue==="streaming"||Ue==="submitted")&&(C.preventDefault(),qn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ue,qn]);function hl(){const p=crypto.randomUUID();wn(p),Wn([]),At([]),dt(!1)}function Kr(p){if(p.preventDefault(),!Pt.trim())return;(Ue==="streaming"||Ue==="submitted")&&qn();const C=ne[Math.floor(Math.random()*ne.length)]||"Thinking...";st(C),cl({text:Pt}),Ut("")}function fl(p){const C=p.target.value;Ut(C)}f.useEffect(()=>{if(!yn)return;function p(I){if(J){const $=I.clientX-Me.x,L=I.clientY-Me.y;$>=a&&$<=l&&Ft($),L>=400&&L<=1e3&&de(L)}else{const $=window.innerWidth-I.clientX;$>=a&&$<=l&&Ft($)}}function C(){We(!1),localStorage.setItem("arcten-sidebar-width",Fe.toString()),localStorage.setItem("arcten-sidebar-height",Bt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",C)}},[yn,Fe,Bt,J,Me,a,l]);function ml(p){p.preventDefault(),We(!0)}function pl(){xn(!0),St(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function gl(){xn(!1),St(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Gr(){St(!Be),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Be))}function yl(p){J&&(Ct(!0),tt({x:p.clientX-Me.x,y:p.clientY-Me.y}))}return f.useEffect(()=>{if(!J)return;function p(){ut(C=>{const $=window.innerWidth-50,L=window.innerHeight-50,U=50-Fe,te=0,Y=Math.max(U,Math.min(C.x,$)),ie=Math.max(te,Math.min(C.y,L));if(Y!==C.x||ie!==C.y){const z={x:Y,y:ie};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(z)),z}return C})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[J,Fe]),f.useEffect(()=>{if(!jt)return;function p(I){const $=I.clientX-et.x,L=I.clientY-et.y,U=50,te=window.innerWidth-U,Y=window.innerHeight-U,ie=U-Fe,z=0,G=Math.max(ie,Math.min($,te)),q=Math.max(z,Math.min(L,Y));ut({x:G,y:q})}function C(){Ct(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Me))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",C)}},[jt,et,Me,Fe]),zn?W?c.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:c.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",W]})}):M?c.jsx(Lu,{features:pf,children:c.jsx(Jn,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:J?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:J?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
+ ${J?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
+ ${Le?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
22
+ ${J?"border border-border":"border-l border-border"}
23
+ ${Le?"":"w-[30px]"}
24
+ `,style:Le?J?{width:`${Fe}px`,height:Be?"auto":`${Bt}px`,left:`${Me.x}px`,top:`${Me.y}px`}:{width:`${Fe}px`}:void 0,onClick:Le?void 0:ul,children:Le?c.jsxs(c.Fragment,{children:[!J&&c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:ml,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),We(!0)}}),c.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),Ct(!0),tt({x:p.clientX-Me.x,y:p.clientY-Me.y})},children:c.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),c.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),We(!0)}})]}),c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${J?"cursor-move":""}`,onMouseDown:J?yl:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${J&&Be?"cursor-pointer":""}`,onClick:J&&Be?p=>{p.stopPropagation(),Gr()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:hl,"aria-label":"New chat",children:c.jsx(oe.Plus,{className:"h-4 w-4"})})}),c.jsx(yt,{children:"Start a new conversation"})]}),c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?gl:pl,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?c.jsx(oe.Dock,{className:"h-4 w-4"}):c.jsx(oe.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(yt,{children:J?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Gr:dl,"aria-label":J?Be?"Maximize":"Minimize":"Close sidebar",children:J?Be?c.jsx(oe.Maximize2,{className:"h-4 w-4"}):c.jsx(oe.Minimize2,{className:"h-4 w-4"}):c.jsx(oe.X,{className:"h-4 w-4"})})}),c.jsx(yt,{children:J?Be?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Be&&c.jsxs(c.Fragment,{children:[y&&vn.length>0&&c.jsxs("div",{className:`border-b border-border ${Ce?"flex flex-col flex-1":""}`,children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[c.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),c.jsx(je,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{Ce||Ee(),dt(!Ce)},children:Ce?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${Ce?"flex-1 overflow-y-auto":""}`,children:vn.slice(0,Ce?void 0:3).map(p=>c.jsxs("div",{className:"group relative",children:[c.jsxs(gf,{type:"button",className:ae(Nt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>ys(p),children:[c.jsx("span",{className:"text-xs truncate",children:p.title}),c.jsx("div",{className:"ml-2 flex items-center",children:c.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:ve(p.updatedAt)})})]}),c.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:C=>{C.stopPropagation(),He(p._id)},"aria-label":"Delete conversation",children:c.jsx(oe.X,{className:"h-3 w-3"})})]},p._id))})]}),c.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[c.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:ot.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&c.jsx("div",{className:"mb-6",children:o}),c.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Ge.length>0&&c.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:c.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(qt?Ge:Ge.slice(0,10)).map(p=>c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx(xs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ut(p.sampleUsage),zt.current?.focus()},children:p.friendlyName})}),c.jsx(yt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium",children:p.description}),c.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[c.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&c.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[c.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),Ge.length>10&&!qt&&c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsxs(xs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ze(!0),children:["+",Ge.length-10," more"]})}),c.jsx(yt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),c.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Ge.slice(10).map(p=>c.jsxs("div",{children:[c.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),c.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),c.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),qt&&Ge.length>10&&c.jsx(xs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ze(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[ot.map(p=>{const I=p.parts.filter(z=>z.type==="text").map(z=>z.text).join("");let $=p.parts;p.role==="assistant"&&p.parts.some(G=>G.timestamp)&&($=[...p.parts].sort((G,q)=>{const ye=G.timestamp||0,me=q.timestamp||0;return ye-me}));let L=[],U=new Map,te=[],Y,ie=!0;if(p.role==="assistant"){const z=$.filter(me=>me.type==="text"&&me.text),G=[],q=[];z.forEach(me=>{const{citations:ft,citationMap:Pe,groupedCitations:De,referencesText:mt}=po(me.text);L.push(...ft),G.push(Pe),De&&q.push(...De),mt&&(Y=mt)}),G.forEach(me=>{me.forEach((ft,Pe)=>{U.has(Pe)||U.set(Pe,ft)})}),te=Array.from(new Map(q.map(me=>[me.url,me])).values()).sort((me,ft)=>(me.numbers[0]||0)-(ft.numbers[0]||0)),ie=!(Ue==="streaming"&&p.id===ot.at(-1)?.id)}return c.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:c.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?c.jsx(yf,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:I}):c.jsx("div",{className:"space-y-2",children:$.map((z,G)=>{if(z.type?.startsWith("tool-")){const q=z.type?.replace("tool-","")||"",ye=ce.find(Pe=>Pe.name===q),me=z.state==="input-available",ft=z.state==="output-available";if(me&&be.has(q),me){if(be.has(q))return null;const Pe=Is(z.input);return c.jsx(Jn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(vf,{toolName:q,description:ye?.description||"",args:Pe,onApprove:async()=>{if(rt.has(z.toolCallId))return;it(mt=>new Set(mt).add(z.toolCallId));const De=pe.get(q);if(De)try{const mt=await De(...Object.values(Pe));Mt({toolCallId:z.toolCallId,tool:q,output:mt})}catch(mt){Mt({toolCallId:z.toolCallId,tool:q,output:`Error: ${mt}`})}},onDeny:async()=>{rt.has(z.toolCallId)||(it(De=>new Set(De).add(z.toolCallId)),Mt({toolCallId:z.toolCallId,tool:q,output:"User denied tool execution"}))}})},`${z.toolCallId}-${G}`)}else if(ft){const Pe=z.output==="User denied tool execution",De=Is(z.input);return c.jsx(wf,{toolName:q,args:De,isDenied:Pe,isSafe:be.has(q)},`${z.toolCallId}-${G}`)}return null}if(z.type==="text"&&z.text&&Ke){const{processedText:q}=po(z.text),Pe=!$.slice(G+1).some(De=>De.type==="text"&&De.text)&&ie&&U.size>0;return c.jsx(Vf,{text:q,citations:L,citationMap:U,groupedCitations:Pe?te:void 0,referencesText:Pe?Y:void 0,ResponseComponent:Ke,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:B,showReferences:Pe},`${p.id}-${G}`)}return z.type==="reasoning"&&z.text?c.jsxs(nl,{className:"w-full",isStreaming:Ue==="streaming"&&G===p.parts.length-1&&p.id===ot.at(-1)?.id,children:[c.jsx(sl,{}),c.jsx(rl,{children:z.text})]},`${p.id}-${G}`):null})})})},p.id)}),c.jsx("div",{ref:bn})]})}),Wr&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Wr.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx($u,{mode:"wait",children:(Ue==="streaming"||Ue==="submitted")&&c.jsxs(Jn,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[c.jsx(Jn,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),c.jsx("p",{className:"text-xs text-muted-foreground",children:_t})]})}),c.jsxs("form",{onSubmit:Kr,className:"relative",children:[c.jsx(bo,{ref:zt,value:Pt,onChange:fl,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Kr(p))}}),Ue==="streaming"||Ue==="submitted"?c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx("button",{type:"button",className:ae(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:qn,children:c.jsx(oe.Square,{className:"h-4 w-4"})})}),c.jsxs(yt,{children:[c.jsx(Jr,{children:"Escape"})," to stop"]})]}):c.jsxs(pt,{children:[c.jsx(gt,{asChild:!0,children:c.jsx("button",{type:"submit",className:ae(Nt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Pt.trim(),children:c.jsx(oe.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(yt,{children:[c.jsx(Jr,{children:"Enter"})," to send"]})]})]})]})]}),c.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[c.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),c.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),c.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[c.jsx(oe.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),c.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):c.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:c.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function Kf(e){return c.jsx(_f,{children:c.jsx(Wf,{...e})})}const Gf={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function jn(e){for(const[t,n]of Object.entries(Gf))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function ol(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function al(e,t,n){const s=Object.keys(n).length,r=t.length;return r>=3||s>=2||s>0&&s<r}function Hf(e,t,n,s={}){const r=[];return t.forEach(o=>{const i=o in n,a=n[o];if(!i&&s[o]!==void 0)return;const l={name:o,type:Yf(a||jn(o)||"text"),label:ll(o),placeholder:Jf(o,a),required:!0,value:s[o]||void 0};l.type==="password"&&(l.validation=u=>u.length<8?"Password must be at least 8 characters":null),r.push(l)}),r.sort((o,i)=>{const a=o.name in n,l=i.name in n;return a===l?0:a?1:-1}),{shouldUseForm:al(e,t,n),fields:r,title:Zf(e),description:Qf(e,r.length)}}function Yf(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function ll(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Jf(e,t){return t?ol(t,e).placeholder:`Enter ${ll(e).toLowerCase()}...`}function Zf(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Qf(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function En(e){if(typeof e=="string")try{const t=JSON.parse(e);return En(t)}catch{return e}if(Array.isArray(e))return e.map(En);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=En(s);return t}return e}function em(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return En(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?En(e):{}}function tm({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,sensitiveParams:l,autoDetectSensitive:u=!1,autoFormGeneration:d=!1,formMode:h="auto",systemPrompt:m="",initialMessages:g=[],conversationId:v,state:b,onStateChange:y,allowStateEdits:x=!0,onToolCall:j,onFinish:k,sources:N,ragConfig:R,ragFilters:B}={}){const O=f.useMemo(()=>R!==void 0?R:B?{enabled:!0,filters:B}:N&&N.length>0?{enabled:!0,organizationId:N[0],autoExecute:!0,filters:void 0}:{enabled:!1},[N,R,B]),E=f.useMemo(()=>{const w={};if(l)for(const[P,T]of Object.entries(l))if(w[P]={},Array.isArray(T))for(const A of T){const V=jn(A);w[P][A]=V||"text"}else for(const[A,V]of Object.entries(T))w[P][A]=V;if(a){for(const[P,T]of Object.entries(a))if(T&&typeof T=="object"&&"sensitiveParams"in T){w[P]||(w[P]={});const A=T.sensitiveParams;if(Array.isArray(A))for(const V of A){const X=jn(V);w[P][V]=X||"text"}else if(A&&typeof A=="object")for(const[V,X]of Object.entries(A))w[P][V]=X}}return w},[l,a,u]),[F,S]=f.useState(n||null),M=f.useRef(n||null),[_,D]=f.useState(null),[W,le]=f.useState(null),se=f.useRef(null),[Z,re]=f.useState([]),[H,$e]=f.useState(v||(typeof window<"u"?crypto.randomUUID():null)),[Ze,Te]=f.useState(!1),[ms,Lt]=f.useState(new Set),[_r,Tt]=f.useState(new Map),[Qe,Le]=f.useState(new Map),[gn,Fe]=f.useState(new Map),[Ft,Bt]=f.useState(new Map),de=b!==void 0,[yn,We]=f.useState({}),J=f.useRef({}),xn=de?b||{}:yn;de&&b?J.current=b:de||(J.current=yn);const[Be,St]=f.useState(!1),[Me,ut]=f.useState(null),jt=f.useRef(!1),Ct=f.useCallback(async(w,P=3)=>{if(!H||!M.current)return;const T=async()=>{const V=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,X=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:H,updates:w},format:"json"})});if(!X.ok){if(X.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const Q=await X.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${X.status} ${Q}`)}};for(let A=0;A<P;A++)try{await T(),ut(null);return}catch(V){if(A===P-1){const Q=V instanceof Error?V:new Error(String(V));throw ut(Q),console.error("Failed to sync state to Convex after retries:",V),Q}await new Promise(Q=>setTimeout(Q,Math.pow(2,A)*100))}},[H,e,M]),et=f.useMemo(()=>function(){return J.current},[]),tt=f.useMemo(()=>async function(P){const T={...J.current,...P};J.current=T,de||We(T),y&&y(T);try{await Ct(P)}catch(A){throw A}},[Ct,y,de]);f.useEffect(()=>{de&&b&&(J.current=b)},[de,b]);const zn=f.useCallback(w=>new Promise(P=>{Tt(T=>new Map(T).set(w.id,w)),Le(T=>new Map(T).set(w.id,P))}),[]),ps=f.useCallback((w,P)=>{const T=Qe.get(w);T&&(T(P),Tt(A=>{const V=new Map(A);return V.delete(w),V}),Le(A=>{const V=new Map(A);return V.delete(w),V}))},[Qe]),bn=f.useCallback(w=>new Promise(P=>{Fe(T=>new Map(T).set(w.id,w)),Bt(T=>new Map(T).set(w.id,P))}),[]),zt=f.useCallback((w,P)=>{const T=Ft.get(w);T&&(T(P),Fe(A=>{const V=new Map(A);return V.delete(w),V}),Bt(A=>{const V=new Map(A);return V.delete(w),V}))},[Ft]),Pt=f.useCallback((w,P)=>{const T=E[w]||{},A=Object.keys(T).length>0;if(u){const V=Object.keys(P).filter(X=>jn(X)!==null);return A||V.length>0}return A},[E,u]),Ut=f.useCallback((w,P)=>{const T={...E[w]||{}};if(u){for(const A of Object.keys(P))if(!(A in T)){const V=jn(A);V&&(T[A]=V)}}return T},[E,u]),Ke=f.useMemo(()=>O?.enabled?async function(P,T=20,A){const V={...O.filters,...A};if(N&&N.length>1){const Q=N.map(ne=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...M.current?{Authorization:`Bearer ${M.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(T,100),organizationId:ne,...Object.keys(V).length>0?{filters:V}:{}})}).then(ee=>ee.ok?ee.json():null)),ce=await Promise.all(Q),pe=[];for(const ne of ce)ne?.candidates&&pe.push(...ne.candidates);pe.sort((ne,ee)=>{const Ee=ne.scores?.rerank||ne.scores?.dense||0;return(ee.scores?.rerank||ee.scores?.dense||0)-Ee});const be=pe.slice(0,T).map((ne,ee)=>{const Ee=ne.citation||ne.url;return{rank:ee+1,doc_id:ne.doc_id,block_id:ne.block_id,url:ne.url,citation:Ee,title:ne.title||"Untitled",snippet:ne.snippet,score:ne.scores?.rerank||ne.scores?.dense||0,metadata:{site:ne.metadata?.site,lang:ne.metadata?.lang,contentType:ne.metadata?.content_type}}});return{success:!0,query:P,total:pe.length,results:be,summary:`Found ${pe.length} relevant results across ${N.length} source(s) for "${P}". Top result: ${be[0]?.title||"N/A"}`}}const X=O.organizationId&&O.organizationId!=="default"?O.organizationId:N&&N.length>0?N[0]:void 0;try{const Q={q:P,k:Math.min(T,100)};X&&(Q.organizationId=X),Object.keys(V).length>0&&(Q.filters=V);const ce={"Content-Type":"application/json"};M.current&&(ce.Authorization=`Bearer ${M.current}`);const pe=await fetch(`${e}/search`,{method:"POST",headers:ce,body:JSON.stringify(Q)});if(!pe.ok){const ee=await pe.text();return{success:!1,error:`Search failed: ${pe.status} ${ee}`}}const be=await pe.json(),ne=be.candidates.map((ee,Ee)=>{const ve=ee.citation||ee.url;return{rank:Ee+1,doc_id:ee.doc_id,block_id:ee.block_id,url:ee.url,citation:ve,title:ee.title||"Untitled",snippet:ee.snippet,score:ee.scores?.rerank||ee.scores?.dense||0,metadata:{site:ee.metadata?.site,lang:ee.metadata?.lang,contentType:ee.metadata?.content_type}}});return{success:!0,query:be.query,total:be.total,results:ne,summary:`Found ${be.total} relevant results for "${P}". Top result: ${ne[0]?.title||"N/A"}`}}catch(Q){return{success:!1,error:Q instanceof Error?Q.message:"Unknown error occurred"}}}:null,[O,e,M]),nt=f.useMemo(()=>O?.enabled?async function(P,T){const A=O.organizationId&&O.organizationId!=="default"?O.organizationId:N&&N.length>0?N[0]:void 0;try{const V={"Content-Type":"application/json"};M.current&&(V.Authorization=`Bearer ${M.current}`);const X=await fetch(`${e}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:P,block_ids:T,...A?{organizationId:A}:{}})});if(!X.ok){const ce=await X.text();return{success:!1,error:`Fetch failed: ${X.status} ${ce}`}}const Q=await X.json();return{success:!0,blocks:Q.blocks||[],fullContent:Q.fullContent||"",pageUrl:Q.pageUrl||"",pageTitle:Q.pageTitle||"",summary:`Fetched ${Q.blocks?.length||0} blocks from ${Q.pageTitle||P}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[O,e,M]),_t=f.useMemo(()=>{const w=[...o,...i,et];return(!de||x)&&w.push(tt),O?.enabled&&(Ke&&w.push(Ke),nt&&w.push(nt)),w},[o,i,et,tt,Ke,nt,O,de,x]),st=f.useMemo(()=>el(_t,a),[_t,a]),rt=f.useMemo(()=>{const w=new Map,P=new Map(st.map(T=>[T.name,T]));return w.set("getState",et),(!de||x)&&w.set("setState",tt),O?.enabled&&(Ke&&w.set("searchDocs",Ke),nt&&w.set("fetchDocContent",nt)),_t.forEach(T=>{if(T===et||T===tt||T===Ke||T===nt)return;const A=T[Ye];if(A){const X=P.get(A);if(X){w.set(X.name,T);return}}const V=st.find(X=>X.name===T.name);V&&w.set(V.name,T)}),w},[_t,st,et,tt,Ke,nt,O,de,x]),it=f.useMemo(()=>new Set(st.map(w=>w.name)),[st]),Un=f.useMemo(()=>{const w=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!de||x)&&w.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const P=[];return O?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...st,...w,...P]},[st,O,de,x]),Xt=f.useMemo(()=>Un.filter(w=>w.name==="getState"?!0:w.name==="setState"?!de||x:O?.enabled&&(w.name==="searchDocs"||w.name==="fetchDocContent")?!0:it.has(w.name)),[Un,it,de,x,O]),Ge=f.useMemo(()=>{const w=new Set;return w.add("getState"),w.add("setState"),O?.enabled&&O.autoExecute!==!1&&(w.add("searchDocs"),w.add("fetchDocContent")),i.forEach(P=>{for(const[T,A]of rt.entries())if(A===P){w.add(T);break}}),w},[i,rt,O]);f.useEffect(()=>s||n?void 0:((async()=>{try{const P=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!P.ok)throw new Error("Failed to fetch token");const T=await P.json();S(T.clientToken),M.current=T.clientToken,le(T.expiresAt),D(null)}catch(P){console.error("[useAgent] Token fetch failed:",P),D(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{se.current&&clearTimeout(se.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!W||s||n)return;se.current&&clearTimeout(se.current);const w=Math.floor(Date.now()/1e3),P=W-w,A=Math.max(0,P-5);return se.current=setTimeout(async()=>{try{const V=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!V.ok)throw new Error("Failed to refresh token");const X=await V.json();S(X.clientToken),M.current=X.clientToken,le(X.expiresAt),D(null)}catch(V){console.error("[useAgent] Token refresh failed:",V),D(V instanceof Error?V.message:"Failed to refresh token")}},A*1e3),()=>{se.current&&clearTimeout(se.current)}},[W,t,JSON.stringify(r),s,n]);const gs=async(w,P={})=>{const T=P.headers?new Headers(P.headers):new Headers;T.delete("user-agent"),T.delete("User-Agent"),console.log("[useAgent] Making request to:",w),console.log("[useAgent] Method:",P.method||"GET"),console.log("[useAgent] Has Authorization header:",T.has("Authorization")),console.log("[useAgent] Client token available:",!!M.current);try{const A=await fetch(w,{...P,headers:T});if(!A.ok){console.error("[useAgent] Request failed:",A.status,A.statusText);const V=await A.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",V)}return A}catch(A){throw console.error("[useAgent] Fetch error:",A),A}},qt=`${e}/chat`;console.log("[useAgent] Chat API URL:",qt);const{messages:ze,sendMessage:vn,status:Wt,error:Ne,stop:wn,addToolResult:Ce,setMessages:dt}=go.useChat({id:H||void 0,messages:g,transport:new ss.DefaultChatTransport({api:qt,fetch:gs,headers:()=>{const w={};return M.current?(w.Authorization=`Bearer ${M.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),w},body:()=>{const w=Xt.map(A=>({name:A.name,description:A.description,inputSchema:A.jsonSchema})),P=w.filter(A=>A.name==="getState"||A.name==="setState").map(A=>A.name),T=w.filter(A=>A.name==="searchDocs"||A.name==="fetchDocContent").map(A=>A.name);return P.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",P),T.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",T):O?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:w,systemPrompt:m,state:J.current,...B&&{ragFilters:B}}}}),sendAutomaticallyWhen:ss.lastAssistantMessageIsCompleteWithToolCalls});f.useEffect(()=>{ze.forEach(w=>{w.role==="assistant"&&w.parts.forEach(P=>{if(!P.type?.startsWith("tool-")||P.state!=="input-available")return;const T=P.type.replace("tool-",""),A=P.toolCallId;if(ms.has(A))return;Lt(X=>new Set(X).add(A));const V=em(P.input);if(Pt(T,V)){const X=Ut(T,V),Q=Object.keys(V);(async()=>{try{let ce={};if(d&&(h==="batch"||h==="auto"&&al(T,Q,X))){const ve=Hf(T,Q,X,V),ht={id:`${A}-form`,toolName:T,toolCallId:A,title:ve.title,description:ve.description,fields:ve.fields},He=await bn(ht);if(He===null){Ce({toolCallId:A,tool:T,output:"User cancelled secure input"});return}ce=He}else for(const[ve,ht]of Object.entries(X)){if(V[ve]!==void 0)continue;const He=ol(ht,ve),ys={id:`${A}-${ve}`,type:ht,paramName:ve,toolName:T,toolCallId:A,title:He.title,description:He.description,placeholder:He.placeholder},Xn=await zn(ys);if(Xn===null){Ce({toolCallId:A,tool:T,output:"User cancelled secure input"});return}ce[ve]=Xn}const be={...V,...ce},ne=rt.get(T);if(!ne)throw new Error(`Tool ${T} not found`);let ee;const Ee=Xt.find(ve=>ve.name===T);if(Ee&&Ee.jsonSchema?.properties){const ht=Object.keys(Ee.jsonSchema.properties).map(He=>be[He]);ee=await ne(...ht)}else ee=await ne(...Object.values(be));Ce({toolCallId:A,tool:T,output:ee})}catch(ce){console.error(`[useAgent] Error executing tool with secure input ${T}:`,ce),Ce({toolCallId:A,tool:T,output:`Error: ${ce}`})}})()}else if(Ge.has(T)){const X=rt.get(T);X?(async()=>{try{const Q=Xt.find(pe=>pe.name===T);let ce;if(Q&&Q.jsonSchema?.properties){const be=Object.keys(Q.jsonSchema.properties).map(ne=>V[ne]);ce=await X(...be)}else if(T==="getState")ce=X();else if(T==="setState"){const pe=V.updates||V;ce=await X(pe)}else ce=await X(...Object.values(V));Ce({toolCallId:A,tool:T,output:ce})}catch(Q){console.error(`[useAgent] Error executing tool ${T}:`,Q),Ce({toolCallId:A,tool:T,output:`Error: ${Q}`})}})():console.warn(`[useAgent] Tool ${T} not found in toolsMap`)}else j&&j({toolCall:{toolCallId:A,toolName:T,args:V}})})})},[ze,Ge,rt,j,Ce,ms,tt,Xt,Pt,Ut,zn]),f.useEffect(()=>{if(Wt==="ready"&&ze.length>0&&k){const w=ze[ze.length-1];w&&w.role==="assistant"&&k({message:w,messages:ze,isAbort:!1,isDisconnect:!1,isError:!!Ne})}},[Wt,ze,Ne,k]);async function Xr(){if(!(!r?.id||!F)){Te(!0);try{const P=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${F}`}})).json();re(P.conversations||[])}catch(w){console.error("Failed to fetch conversations:",w)}finally{Te(!1)}}}f.useEffect(()=>{r?.id&&F&&Xr()},[JSON.stringify(r),F,e]),f.useEffect(()=>{if(!H||!M.current)return;(async()=>{St(!0),ut(null);try{const P=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:H},format:"json"})});if(!P.ok){const V=await P.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${P.status} ${V}`)}const A=(await P.json())?.value||{};J.current=A,de||We(A),y&&y(A),jt.current=!0}catch(P){console.error("Failed to fetch state:",P);const T=P instanceof Error?P:new Error(String(P));ut(T),jt.current||(J.current={},de?y&&y({}):(We({}),y&&y({})),jt.current=!0)}finally{St(!1)}})()},[H,e,de,y]);async function Kt(w){$e(w),Te(!0);try{const P=await fetch(`${e}/conversations/${w}/messages`,{headers:{Authorization:`Bearer ${M.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const A=(await P.json()).messages||[];dt(A)}catch(P){console.error("Failed to load conversation messages:",P)}finally{Te(!1)}}async function qr(w){if(F)try{await fetch(`${e}/conversations/${w}`,{method:"DELETE",headers:{Authorization:`Bearer ${F}`}}),re(Z.filter(P=>P._id!==w)),w===H&&At()}catch(P){console.error("Failed to delete conversation:",P)}}function At(){const w=crypto.randomUUID();$e(w),dt([]),Lt(new Set),J.current={},de?y&&y({}):(We({}),y&&y({})),jt.current=!1}function _n(w){Ce(w)}async function kt(w){const P={...J.current,...w};J.current=P,de||We(P),y&&y(P);try{await Ct(w)}catch(T){throw T}}return{id:H,messages:ze,status:Wt,error:Ne,sendMessage:vn,stop:wn,addToolOutput:_n,setMessages:dt,conversations:Z,loadConversation:Kt,deleteConversation:qr,startNewConversation:At,isLoadingConversations:Ze,clientToken:F,tokenError:_,state:xn,setState:kt,isStateLoading:Be,stateError:Me,pendingSecureInputs:Array.from(_r.values()),completeSecureInput:ps,pendingSecureForms:Array.from(gn.values()),completeSecureForm:zt}}exports.verifyToken=Nl.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Ye;exports.ArctenAgent=Kf;exports.preserveToolName=xf;exports.useAgent=tm;