@arcteninc/core 0.0.84 → 0.0.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Ga=Object.create;var Cr=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Ja=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Qa=Object.prototype.hasOwnProperty;var tc=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ja(e))!Qa.call(t,r)&&r!==n&&Cr(t,r,{get:()=>e[r],enumerable:!(s=Ya(e,r))||s.enumerable});return t};var ec=(t,e,n)=>(n=t!=null?Ga(Za(t)):{},tc(e||!t||!t.__esModule?Cr(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),ft=require("lucide-react"),Wi=require("@ai-sdk/react"),Nn=require("ai"),Ki=require("@radix-ui/react-slot"),qi=require("class-variance-authority"),nc=require("clsx"),sc=require("tailwind-merge"),rc=require("@radix-ui/react-tooltip"),Pr=require("@radix-ui/react-use-controllable-state"),ic=require("@radix-ui/react-collapsible"),oc=require("react-dom"),ac=require("./server.cjs");function Is(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 Ot=Is(m),Ne=Is(rc),Os=Is(ic);function mt(...t){return sc.twMerge(nc.clsx(t))}const pe=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"}}),Vn=Ot.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Ki.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:mt(pe({variant:e,size:n,className:t})),...r})});Vn.displayName="Button";const cc=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 Gn({className:t,variant:e,asChild:n=!1,...s}){const r=n?Ki.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:mt(cc({variant:e}),t),...s})}const lc=({textAreaRef:t,triggerAutoSize:e,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ot.useState(!0);Ot.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])},Hi=Ot.forwardRef(({maxHeight:t=Number.MAX_SAFE_INTEGER,minHeight:e=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ot.useRef(null),[c,u]=Ot.useState("");return lc({textAreaRef:a,triggerAutoSize:c,maxHeight:t,minHeight:e}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:t,minHeight:e})),Ot.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)}})});Hi.displayName="AutosizeTextarea";function uc({delayDuration:t=0,...e}){return d.jsx(Ne.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function Qt({...t}){return d.jsx(uc,{children:d.jsx(Ne.Root,{"data-slot":"tooltip",...t})})}function te({...t}){return d.jsx(Ne.Trigger,{"data-slot":"tooltip-trigger",...t})}function ee({className:t,sideOffset:e=0,children:n,...s}){return d.jsx(Ne.Portal,{children:d.jsxs(Ne.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(Ne.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function jr({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 Ls=m.createContext({});function Fs(t){const e=m.useRef(null);return e.current===null&&(e.current=t()),e.current}const $s=typeof window<"u",Xi=$s?m.useLayoutEffect:m.useEffect,$n=m.createContext(null);function Bs(t,e){t.indexOf(e)===-1&&t.push(e)}function zs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Wt=(t,e,n)=>n>e?e:n<t?t:n;function hs(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let Oe=()=>{},Kt=()=>{};process.env.NODE_ENV!=="production"&&(Oe=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(hs(e,n))},Kt=(t,e,n)=>{if(!t)throw new Error(hs(e,n))});const qt={},Gi=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Yi(t){return typeof t=="object"&&t!==null}const Ji=t=>/^0[^.\s]+$/u.test(t);function Us(t){let e;return()=>(e===void 0&&(e=t()),e)}const Nt=t=>t,dc=(t,e)=>n=>e(t(n)),un=(...t)=>t.reduce(dc),sn=(t,e,n)=>{const s=e-t;return s===0?1:(n-t)/s};class _s{constructor(){this.subscriptions=[]}add(e){return Bs(this.subscriptions,e),()=>zs(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 Lt=t=>t*1e3,Dt=t=>t/1e3;function Zi(t,e){return e?t*(1e3/e):0}const kr=new Set;function Ws(t,e,n){t||kr.has(e)||(console.warn(hs(e,n)),kr.add(e))}const Qi=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,hc=1e-7,fc=12;function mc(t,e,n,s,r){let o,i,a=0;do i=e+(n-e)/2,o=Qi(i,s,r)-t,o>0?n=i:e=i;while(Math.abs(o)>hc&&++a<fc);return i}function dn(t,e,n,s){if(t===e&&n===s)return Nt;const r=o=>mc(o,0,1,t,n);return o=>o===0||o===1?o:Qi(r(o),e,s)}const to=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,eo=t=>e=>1-t(1-e),no=dn(.33,1.53,.69,.99),Ks=eo(no),so=to(Ks),ro=t=>(t*=2)<1?.5*Ks(t):.5*(2-Math.pow(2,-10*(t-1))),qs=t=>1-Math.sin(Math.acos(t)),io=eo(qs),oo=to(qs),pc=dn(.42,0,1,1),gc=dn(0,0,.58,1),ao=dn(.42,0,.58,1),yc=t=>Array.isArray(t)&&typeof t[0]!="number",co=t=>Array.isArray(t)&&typeof t[0]=="number",Mr={linear:Nt,easeIn:pc,easeInOut:ao,easeOut:gc,circIn:qs,circInOut:oo,circOut:io,backIn:Ks,backInOut:so,backOut:no,anticipate:ro},xc=t=>typeof t=="string",Er=t=>{if(co(t)){Kt(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,s,r]=t;return dn(e,n,s,r)}else if(xc(t))return Kt(Mr[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Mr[t];return t},Tn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function vc(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 x=f&&r?n:s;return h&&i.add(l),x.has(l)||x.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 bc=40;function lo(t,e){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Tn.reduce((T,S)=>(T[S]=vc(o),T),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:x}=i,b=()=>{const T=qt.useManualTiming?r.timestamp:performance.now();n=!1,qt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(T-r.timestamp,bc),1)),r.timestamp=T,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),x.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(b))},j=()=>{n=!0,s=!0,r.isProcessing||t(b)};return{schedule:Tn.reduce((T,S)=>{const E=i[S];return T[S]=(R,C=!1,k=!1)=>(n||j(),E.schedule(R,C,k)),T},{}),cancel:T=>{for(let S=0;S<Tn.length;S++)i[Tn[S]].cancel(T)},state:r,steps:i}}const{schedule:st,cancel:se,state:pt,steps:Yn}=lo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Nt,!0);let jn;function wc(){jn=void 0}const At={now:()=>(jn===void 0&&At.set(pt.isProcessing||qt.useManualTiming?pt.timestamp:performance.now()),jn),set:t=>{jn=t,queueMicrotask(wc)}},uo=t=>e=>typeof e=="string"&&e.startsWith(t),Hs=uo("--"),Tc=uo("var(--"),Xs=t=>Tc(t)?Sc.test(t.split("/*")[0].trim()):!1,Sc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Le={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},rn={...Le,transform:t=>Wt(0,1,t)},Sn={...Le,default:1},Je=t=>Math.round(t*1e5)/1e5,Gs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ac(t){return t==null}const Cc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ys=(t,e)=>n=>!!(typeof n=="string"&&Cc.test(n)&&n.startsWith(t)||e&&!Ac(n)&&Object.prototype.hasOwnProperty.call(n,e)),ho=(t,e,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Gs);return{[t]:parseFloat(r),[e]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Pc=t=>Wt(0,255,t),Jn={...Le,transform:t=>Math.round(Pc(t))},ye={test:Ys("rgb","red"),parse:ho("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+Jn.transform(t)+", "+Jn.transform(e)+", "+Jn.transform(n)+", "+Je(rn.transform(s))+")"};function jc(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 fs={test:Ys("#"),parse:jc,transform:ye.transform},hn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),ne=hn("deg"),Ut=hn("%"),L=hn("px"),kc=hn("vh"),Mc=hn("vw"),Dr={...Ut,parse:t=>Ut.parse(t)/100,transform:t=>Ut.transform(t*100)},Pe={test:Ys("hsl","hue"),parse:ho("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+Ut.transform(Je(e))+", "+Ut.transform(Je(n))+", "+Je(rn.transform(s))+")"},ut={test:t=>ye.test(t)||fs.test(t)||Pe.test(t),parse:t=>ye.test(t)?ye.parse(t):Pe.test(t)?Pe.parse(t):fs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ye.transform(t):Pe.transform(t),getAnimatableNone:t=>{const e=ut.parse(t);return e.alpha=0,ut.transform(e)}},Ec=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Dc(t){return isNaN(t)&&typeof t=="string"&&(t.match(Gs)?.length||0)+(t.match(Ec)?.length||0)>0}const fo="number",mo="color",Nc="var",Vc="var(",Nr="${}",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 on(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=e.replace(Rc,c=>(ut.test(c)?(s.color.push(o),r.push(mo),n.push(ut.parse(c))):c.startsWith(Vc)?(s.var.push(o),r.push(Nc),n.push(c)):(s.number.push(o),r.push(fo),n.push(parseFloat(c))),++o,Nr)).split(Nr);return{values:n,split:a,indexes:s,types:r}}function po(t){return on(t).values}function go(t){const{split:e,types:n}=on(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===fo?o+=Je(r[i]):a===mo?o+=ut.transform(r[i]):o+=r[i]}return o}}const Ic=t=>typeof t=="number"?0:ut.test(t)?ut.getAnimatableNone(t):t;function Oc(t){const e=po(t);return go(t)(e.map(Ic))}const re={test:Dc,parse:po,createTransformer:go,getAnimatableNone:Oc};function Zn(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 Lc({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=Zn(c,a,t+1/3),o=Zn(c,a,t),i=Zn(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function Rn(t,e){return n=>n>0?e:t}const it=(t,e,n)=>t+(e-t)*n,Qn=(t,e,n)=>{const s=t*t,r=n*(e*e-s)+s;return r<0?0:Math.sqrt(r)},Fc=[fs,ye,Pe],$c=t=>Fc.find(e=>e.test(t));function Vr(t){const e=$c(t);if(Oe(!!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===Pe&&(n=Lc(n)),n}const Rr=(t,e)=>{const n=Vr(t),s=Vr(e);if(!n||!s)return Rn(t,e);const r={...n};return o=>(r.red=Qn(n.red,s.red,o),r.green=Qn(n.green,s.green,o),r.blue=Qn(n.blue,s.blue,o),r.alpha=it(n.alpha,s.alpha,o),ye.transform(r))},ms=new Set(["none","hidden"]);function Bc(t,e){return ms.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function zc(t,e){return n=>it(t,e,n)}function Js(t){return typeof t=="number"?zc:typeof t=="string"?Xs(t)?Rn:ut.test(t)?Rr:Wc:Array.isArray(t)?yo:typeof t=="object"?ut.test(t)?Rr:Uc:Rn}function yo(t,e){const n=[...t],s=n.length,r=t.map((o,i)=>Js(o)(o,e[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Uc(t,e){const n={...t,...e},s={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(s[r]=Js(t[r])(t[r],e[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function _c(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 Wc=(t,e)=>{const n=re.createTransformer(e),s=on(t),r=on(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?ms.has(t)&&!r.values.length||ms.has(e)&&!s.values.length?Bc(t,e):un(yo(_c(s,r),r.values),n):(Oe(!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"),Rn(t,e))};function xo(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?it(t,e,n):Js(t)(t,e)}const Kc=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>st.update(e,n),stop:()=>se(e),now:()=>pt.isProcessing?pt.timestamp:At.now()}},vo=(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)})`},In=2e4;function Zs(t){let e=0;const n=50;let s=t.next(e);for(;!s.done&&e<In;)e+=n,s=t.next(e);return e>=In?1/0:e}function qc(t,e=100,n){const s=n({...t,keyframes:[0,e]}),r=Math.min(Zs(s),In);return{type:"keyframes",ease:o=>s.next(r*o).value/e,duration:Dt(r)}}const Hc=5;function bo(t,e,n){const s=Math.max(e-Hc,0);return Zi(n-t(s),e-s)}const rt={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},ts=.001;function Xc({duration:t=rt.duration,bounce:e=rt.bounce,velocity:n=rt.velocity,mass:s=rt.mass}){let r,o;Oe(t<=Lt(rt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-e;i=Wt(rt.minDamping,rt.maxDamping,i),t=Wt(rt.minDuration,rt.maxDuration,Dt(t)),i<1?(r=u=>{const l=u*i,h=l*t,f=l-n,g=ps(u,i),x=Math.exp(-h);return ts-f/g*x},o=u=>{const h=u*i*t,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*t,x=Math.exp(-h),b=ps(Math.pow(u,2),i);return(-r(u)+ts>0?-1:1)*((f-g)*x)/b}):(r=u=>{const l=Math.exp(-u*t),h=(u-n)*t+1;return-ts+l*h},o=u=>{const l=Math.exp(-u*t),h=(n-u)*(t*t);return l*h});const a=5/t,c=Yc(r,o,a);if(t=Lt(t),isNaN(c))return{stiffness:rt.stiffness,damping:rt.damping,duration:t};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:t}}}const Gc=12;function Yc(t,e,n){let s=n;for(let r=1;r<Gc;r++)s=s-t(s)/e(s);return s}function ps(t,e){return t*Math.sqrt(1-e*e)}const Jc=["duration","bounce"],Zc=["stiffness","damping","mass"];function Ir(t,e){return e.some(n=>t[n]!==void 0)}function Qc(t){let e={velocity:rt.velocity,stiffness:rt.stiffness,damping:rt.damping,mass:rt.mass,isResolvedFromDuration:!1,...t};if(!Ir(t,Zc)&&Ir(t,Jc))if(t.visualDuration){const n=t.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Wt(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:rt.mass,stiffness:r,damping:o}}else{const n=Xc(t);e={...e,...n,mass:rt.mass},e.isResolvedFromDuration=!0}return e}function On(t=rt.visualDuration,e=rt.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}=Qc({...n,velocity:-Dt(n.velocity||0)}),x=f||0,b=u/(2*Math.sqrt(c*l)),j=i-o,y=Dt(Math.sqrt(c/l)),v=Math.abs(j)<5;s||(s=v?rt.restSpeed.granular:rt.restSpeed.default),r||(r=v?rt.restDelta.granular:rt.restDelta.default);let T;if(b<1){const E=ps(y,b);T=R=>{const C=Math.exp(-b*y*R);return i-C*((x+b*y*j)/E*Math.sin(E*R)+j*Math.cos(E*R))}}else if(b===1)T=E=>i-Math.exp(-y*E)*(j+(x+y*j)*E);else{const E=y*Math.sqrt(b*b-1);T=R=>{const C=Math.exp(-b*y*R),k=Math.min(E*R,300);return i-C*((x+b*y*j)*Math.sinh(k)+E*j*Math.cosh(k))/E}}const S={calculatedDuration:g&&h||null,next:E=>{const R=T(E);if(g)a.done=E>=h;else{let C=E===0?x:0;b<1&&(C=E===0?Lt(x):bo(T,E,R));const k=Math.abs(C)<=s,W=Math.abs(i-R)<=r;a.done=k&&W}return a.value=a.done?i:R,a},toString:()=>{const E=Math.min(Zs(S),In),R=vo(C=>S.next(E*C).value,E,30);return E+"ms "+R},toTransition:()=>{}};return S}On.applyToOptions=t=>{const e=qc(t,100,On);return t.ease=e.ease,t.duration=Lt(e.duration),t.type="keyframes",t};function gs({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=k=>a!==void 0&&k<a||c!==void 0&&k>c,x=k=>a===void 0?c:c===void 0||Math.abs(a-k)<Math.abs(c-k)?a:c;let b=n*e;const j=h+b,y=i===void 0?j:i(j);y!==j&&(b=y-h);const v=k=>-b*Math.exp(-k/s),T=k=>y+v(k),S=k=>{const W=v(k),O=T(k);f.done=Math.abs(W)<=u,f.value=f.done?y:O};let E,R;const C=k=>{g(f.value)&&(E=k,R=On({keyframes:[f.value,x(f.value)],velocity:bo(T,k,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return C(0),{calculatedDuration:null,next:k=>{let W=!1;return!R&&E===void 0&&(W=!0,S(k),C(k)),E!==void 0&&k>=E?R.next(k-E):(!W&&S(k),f)}}}function tl(t,e,n){const s=[],r=n||qt.mix||xo,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]||Nt:e;a=un(c,a)}s.push(a)}return s}function el(t,e,{clamp:n=!0,ease:s,mixer:r}={}){const o=t.length;if(Kt(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=tl(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=sn(t[h],t[h+1],l);return a[h](f)};return n?l=>u(Wt(t[0],t[o-1],l)):u}function nl(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const r=sn(0,e,s);t.push(it(n,1,r))}}function sl(t){const e=[0];return nl(e,t.length-1),e}function rl(t,e){return t.map(n=>n*e)}function il(t,e){return t.map(()=>e||ao).splice(0,t.length-1)}function je({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const r=yc(s)?s.map(Er):Er(s),o={done:!1,value:e[0]},i=rl(n&&n.length===e.length?n:sl(e),t),a=el(i,e,{ease:Array.isArray(r)?r:il(e,r)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const ol=t=>t!==null;function Qs(t,{repeat:e,repeatType:n="loop"},s,r=1){const o=t.filter(ol),a=r<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const al={decay:gs,inertia:gs,tween:je,keyframes:je,spring:On};function wo(t){typeof t.type=="string"&&(t.type=al[t.type])}class tr{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 cl=t=>t/100;class er extends tr{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!==At.now()&&this.tick(At.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;wo(e);const{type:n=je,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=e;let{keyframes:a}=e;const c=n||je;process.env.NODE_ENV!=="production"&&c!==je&&Kt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==je&&typeof a[0]!="number"&&(this.mixKeyframes=un(cl,xo(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=Zs(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:x,onUpdate:b,finalKeyframe:j}=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 T=this.currentTime,S=s;if(h){const k=Math.min(this.currentTime,r)/a;let W=Math.floor(k),O=k%1;!O&&k>=1&&(O=1),O===1&&W--,W=Math.min(W,h+1),!!(W%2)&&(f==="reverse"?(O=1-O,g&&(O-=g/a)):f==="mirror"&&(S=i)),T=Wt(0,1,O)*a}const E=v?{done:!1,value:l[0]}:S.next(T);o&&(E.value=o(E.value));let{done:R}=E;!v&&c!==null&&(R=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const C=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&R);return C&&x!==gs&&(E.value=Qs(l,this.options,j,this.speed)),b&&b(E.value),C&&this.finish(),E}then(e,n){return this.finished.then(e,n)}get duration(){return Dt(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Dt(e)}get time(){return Dt(this.currentTime)}set time(e){e=Lt(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(At.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=Dt(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=Kc,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(At.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 ll(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const xe=t=>t*180/Math.PI,ys=t=>{const e=xe(Math.atan2(t[1],t[0]));return xs(e)},ul={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:ys,rotateZ:ys,skewX:t=>xe(Math.atan(t[1])),skewY:t=>xe(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},xs=t=>(t=t%360,t<0&&(t+=360),t),Or=ys,Lr=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Fr=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),dl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Lr,scaleY:Fr,scale:t=>(Lr(t)+Fr(t))/2,rotateX:t=>xs(xe(Math.atan2(t[6],t[5]))),rotateY:t=>xs(xe(Math.atan2(-t[2],t[0]))),rotateZ:Or,rotate:Or,skewX:t=>xe(Math.atan(t[4])),skewY:t=>xe(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function vs(t){return t.includes("scale")?1:0}function bs(t,e){if(!t||t==="none")return vs(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=dl,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=ul,r=a}if(!r)return vs(e);const o=s[e],i=r[1].split(",").map(fl);return typeof o=="function"?o(i):i[o]}const hl=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return bs(n,e)};function fl(t){return parseFloat(t.trim())}const Fe=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],$e=new Set(Fe),$r=t=>t===Le||t===L,ml=new Set(["x","y","z"]),pl=Fe.filter(t=>!ml.has(t));function gl(t){const e=[];return pl.forEach(n=>{const s=t.getValue(n);s!==void 0&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}const ve={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})=>bs(e,"x"),y:(t,{transform:e})=>bs(e,"y")};ve.translateX=ve.x;ve.translateY=ve.y;const be=new Set;let ws=!1,Ts=!1,Ss=!1;function To(){if(Ts){const t=Array.from(be).filter(s=>s.needsMeasurement),e=new Set(t.map(s=>s.element)),n=new Map;e.forEach(s=>{const r=gl(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)})}Ts=!1,ws=!1,be.forEach(t=>t.complete(Ss)),be.clear()}function So(){be.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ts=!0)})}function yl(){Ss=!0,So(),To(),Ss=!1}class nr{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?(be.add(this),ws||(ws=!0,st.read(So),st.resolveKeyframes(To))):(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])}ll(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),be.delete(this)}cancel(){this.state==="scheduled"&&(be.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const xl=t=>t.startsWith("--");function vl(t,e,n){xl(e)?t.style.setProperty(e,n):t.style[e]=n}const bl=Us(()=>window.ScrollTimeline!==void 0),wl={};function Tl(t,e){const n=Us(t);return()=>wl[e]??n()}const Ao=Tl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ye=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,Br={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ye([0,.65,.55,1]),circOut:Ye([.55,0,1,.45]),backIn:Ye([.31,.01,.66,-.59]),backOut:Ye([.33,1.53,.69,.99])};function Co(t,e){if(t)return typeof t=="function"?Ao()?vo(t,e):"ease-out":co(t)?Ye(t):Array.isArray(t)?t.map(n=>Co(n,e)||Br.easeOut):Br[t]}function Sl(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=Co(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 Po(t){return typeof t=="function"&&"applyToOptions"in t}function Al({type:t,...e}){return Po(t)&&Ao()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Cl extends tr{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,Kt(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Al(e);this.animation=Sl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=Qs(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):vl(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 Dt(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Dt(e)}get time(){return Dt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=Lt(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&&bl()?(this.animation.timeline=e,Nt):n(this)}}const jo={anticipate:ro,backInOut:so,circInOut:oo};function Pl(t){return t in jo}function jl(t){typeof t.ease=="string"&&Pl(t.ease)&&(t.ease=jo[t.ease])}const zr=10;class kl extends Cl{constructor(e){jl(e),wo(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 er({...i,autoplay:!1}),c=Lt(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-zr).value,a.sample(c).value,zr),a.stop()}}const Ur=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(re.test(t)||t==="0")&&!t.startsWith("url("));function Ml(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 El(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=Ur(r,e),a=Ur(o,e);return Oe(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:Ml(t)||(n==="spring"||Po(n))&&s}function As(t){t.duration=0,t.type="keyframes"}const Dl=new Set(["opacity","clipPath","filter","transform"]),Nl=Us(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Vl(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 Nl()&&n&&Dl.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Rl=40;class Il extends tr{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=At.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||nr;this.keyframeResolver=new g(a,(x,b,j)=>this.onKeyframesResolved(x,b,f,!j),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=At.now(),El(e,o,i,a)||((qt.instantAnimations||!c)&&l?.(Qs(e,s,n)),e[0]=e[e.length-1],As(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Rl?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:e},g=!u&&Vl(f)?new kl({...f,element:f.motionValue.owner.current}):new er(f);g.finished.then(()=>this.notifyFinished()).catch(Nt),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(),yl()),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 Ol=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ll(t){const e=Ol.exec(t);if(!e)return[,];const[,n,s,r]=e;return[`--${n??s}`,r]}const Fl=4;function ko(t,e,n=1){Kt(n<=Fl,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Ll(t);if(!s)return;const o=window.getComputedStyle(e).getPropertyValue(s);if(o){const i=o.trim();return Gi(i)?parseFloat(i):i}return Xs(r)?ko(r,e,n+1):r}function sr(t,e){return t?.[e]??t?.default??t}const Mo=new Set(["width","height","top","left","right","bottom",...Fe]),$l={test:t=>t==="auto",parse:t=>t},Eo=t=>e=>e.test(t),Do=[Le,L,Ut,ne,Mc,kc,$l],_r=t=>Do.find(Eo(t));function Bl(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ji(t):!0}const zl=new Set(["brightness","contrast","saturate","opacity"]);function Ul(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[s]=n.match(Gs)||[];if(!s)return t;const r=n.replace(s,"");let o=zl.has(e)?1:0;return s!==n&&(o*=100),e+"("+o+r+")"}const _l=/\b([a-z-]*)\(.*?\)/gu,Cs={...re,getAnimatableNone:t=>{const e=t.match(_l);return e?e.map(Ul).join(" "):t}},Wr={...Le,transform:Math.round},Wl={rotate:ne,rotateX:ne,rotateY:ne,rotateZ:ne,scale:Sn,scaleX:Sn,scaleY:Sn,scaleZ:Sn,skew:ne,skewX:ne,skewY:ne,distance:L,translateX:L,translateY:L,translateZ:L,x:L,y:L,z:L,perspective:L,transformPerspective:L,opacity:rn,originX:Dr,originY:Dr,originZ:L},rr={borderWidth:L,borderTopWidth:L,borderRightWidth:L,borderBottomWidth:L,borderLeftWidth:L,borderRadius:L,radius:L,borderTopLeftRadius:L,borderTopRightRadius:L,borderBottomRightRadius:L,borderBottomLeftRadius:L,width:L,maxWidth:L,height:L,maxHeight:L,top:L,right:L,bottom:L,left:L,padding:L,paddingTop:L,paddingRight:L,paddingBottom:L,paddingLeft:L,margin:L,marginTop:L,marginRight:L,marginBottom:L,marginLeft:L,backgroundPositionX:L,backgroundPositionY:L,...Wl,zIndex:Wr,fillOpacity:rn,strokeOpacity:rn,numOctaves:Wr},Kl={...rr,color:ut,backgroundColor:ut,outlineColor:ut,fill:ut,stroke:ut,borderColor:ut,borderTopColor:ut,borderRightColor:ut,borderBottomColor:ut,borderLeftColor:ut,filter:Cs,WebkitFilter:Cs},No=t=>Kl[t];function Vo(t,e){let n=No(t);return n!==Cs&&(n=re),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const ql=new Set(["auto","none","0"]);function Hl(t,e,n){let s=0,r;for(;s<t.length&&!r;){const o=t[s];typeof o=="string"&&!ql.has(o)&&on(o).values.length&&(r=t[s]),s++}if(r&&n)for(const o of e)t[o]=Vo(n,r)}class Xl extends nr{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(),Xs(u))){const l=ko(u,n.current);l!==void 0&&(e[c]=l),c===e.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Mo.has(s)||e.length!==2)return;const[r,o]=e,i=_r(r),a=_r(o);if(i!==a)if($r(i)&&$r(a))for(let c=0;c<e.length;c++){const u=e[c];typeof u=="string"&&(e[c]=parseFloat(u))}else ve[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,s=[];for(let r=0;r<e.length;r++)(e[r]===null||Bl(e[r]))&&s.push(r);s.length&&Hl(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=ve[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]=ve[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 Gl(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 Ro=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function Io(t){return Yi(t)&&"offsetHeight"in t}const Kr=30,Yl=t=>!isNaN(parseFloat(t));class Jl{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=At.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=At.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Yl(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Ws(!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 _s);const s=this.events[e].add(n);return e==="change"?()=>{s(),st.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=At.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Kr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Kr);return Zi(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 Re(t,e){return new Jl(t,e)}const{schedule:ir}=lo(queueMicrotask,!1),It={x:!1,y:!1};function Oo(){return It.x||It.y}function Zl(t){return t==="x"||t==="y"?It[t]?null:(It[t]=!0,()=>{It[t]=!1}):It.x||It.y?null:(It.x=It.y=!0,()=>{It.x=It.y=!1})}function Lo(t,e){const n=Gl(t),s=new AbortController,r={passive:!0,...e,signal:s.signal};return[n,r,()=>s.abort()]}function qr(t){return!(t.pointerType==="touch"||Oo())}function Ql(t,e,n={}){const[s,r,o]=Lo(t,n),i=a=>{if(!qr(a))return;const{target:c}=a,u=e(c,a);if(typeof u!="function"||!c)return;const l=h=>{qr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Fo=(t,e)=>e?t===e?!0:Fo(t,e.parentElement):!1,or=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,tu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function eu(t){return tu.has(t.tagName)||t.tabIndex!==-1}const kn=new WeakSet;function Hr(t){return e=>{e.key==="Enter"&&t(e)}}function es(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const nu=(t,e)=>{const n=t.currentTarget;if(!n)return;const s=Hr(()=>{if(kn.has(n))return;es(n,"down");const r=Hr(()=>{es(n,"up")}),o=()=>es(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 Xr(t){return or(t)&&!Oo()}function su(t,e,n={}){const[s,r,o]=Lo(t,n),i=a=>{const c=a.currentTarget;if(!Xr(a))return;kn.add(c);const u=e(c,a),l=(g,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),kn.has(c)&&kn.delete(c),Xr(g)&&typeof u=="function"&&u(g,{success:x})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Fo(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),Io(a)&&(a.addEventListener("focus",u=>nu(u,r)),!eu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function $o(t){return Yi(t)&&"ownerSVGElement"in t}function ru(t){return $o(t)&&t.tagName==="svg"}const gt=t=>!!(t&&t.getVelocity),iu=[...Do,ut,re],ou=t=>iu.find(Eo(t)),ar=m.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Gr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function au(...t){return e=>{let n=!1;const s=t.map(r=>{const o=Gr(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():Gr(t[r],null)}}}}function cu(...t){return Ot.useCallback(au(...t),t)}class lu extends Ot.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=Io(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 uu({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(ar),c=cu(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 x=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const j=s??document.head;return j.appendChild(b),b.sheet&&b.sheet.insertRule(`
1
+ "use strict";var Ya=Object.create;var Cr=Object.defineProperty;var Ja=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var tc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Za(t))!ec.call(e,r)&&r!==n&&Cr(e,r,{get:()=>t[r],enumerable:!(s=Ja(t,r))||s.enumerable});return e};var nc=(e,t,n)=>(n=e!=null?Ya(Qa(e)):{},tc(t||!e||!e.__esModule?Cr(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("react/jsx-runtime"),m=require("react"),fe=require("lucide-react"),Ki=require("@ai-sdk/react"),Vn=require("ai"),qi=require("@radix-ui/react-slot"),Hi=require("class-variance-authority"),sc=require("clsx"),rc=require("tailwind-merge"),ic=require("@radix-ui/react-tooltip"),jr=require("@radix-ui/react-use-controllable-state"),oc=require("@radix-ui/react-collapsible"),ac=require("react-dom"),cc=require("./server.cjs");function Os(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 Re=Os(m),It=Os(ic),Ls=Os(oc);function me(...e){return rc.twMerge(sc.clsx(e))}const yt=Hi.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"}}),Rn=Re.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?qi.Slot:"button";return h.jsx(i,{ref:o,"data-slot":"button",className:me(yt({variant:t,size:n,className:e})),...r})});Rn.displayName="Button";const lc=Hi.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 Yn({className:e,variant:t,asChild:n=!1,...s}){const r=n?qi.Slot:"span";return h.jsx(r,{"data-slot":"badge",className:me(lc({variant:t}),e),...s})}const uc=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Re.useState(!0);Re.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 c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[e.current,t])},Gi=Re.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Re.useRef(null),[c,u]=Re.useState("");return uc({textAreaRef:a,triggerAutoSize:c,maxHeight:e,minHeight:t}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Re.useEffect(()=>{u(r)},[o?.defaultValue,r]),h.jsx("textarea",{...o,value:r,ref:a,className:me("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)}})});Gi.displayName="AutosizeTextarea";function dc({delayDuration:e=0,...t}){return h.jsx(It.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function nt({...e}){return h.jsx(dc,{children:h.jsx(It.Root,{"data-slot":"tooltip",...e})})}function st({...e}){return h.jsx(It.Trigger,{"data-slot":"tooltip-trigger",...e})}function rt({className:e,sideOffset:t=0,children:n,...s}){return h.jsx(It.Portal,{children:h.jsxs(It.Content,{"data-slot":"tooltip-content",sideOffset:t,className:me("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,h.jsx(It.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function kr({className:e,...t}){return h.jsx("kbd",{"data-slot":"kbd",className:me("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 Fs=m.createContext({});function $s(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const Bs=typeof window<"u",Xi=Bs?m.useLayoutEffect:m.useEffect,Bn=m.createContext(null);function zs(e,t){e.indexOf(t)===-1&&e.push(t)}function Us(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const We=(e,t,n)=>n>t?t:n<e?e:n;function fs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let $t=()=>{},Ke=()=>{};process.env.NODE_ENV!=="production"&&($t=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(fs(t,n))},Ke=(e,t,n)=>{if(!e)throw new Error(fs(t,n))});const qe={},Yi=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ji(e){return typeof e=="object"&&e!==null}const Zi=e=>/^0[^.\s]+$/u.test(e);function _s(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ee=e=>e,hc=(e,t)=>n=>t(e(n)),hn=(...e)=>e.reduce(hc),on=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Ws{constructor(){this.subscriptions=[]}add(t){return zs(this.subscriptions,t),()=>Us(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 Ie=e=>e*1e3,Me=e=>e/1e3;function Qi(e,t){return t?e*(1e3/t):0}const Mr=new Set;function Ks(e,t,n){e||Mr.has(t)||(console.warn(fs(t,n)),Mr.add(t))}const eo=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,fc=1e-7,mc=12;function pc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=eo(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>fc&&++a<mc);return i}function fn(e,t,n,s){if(e===t&&n===s)return Ee;const r=o=>pc(o,0,1,e,n);return o=>o===0||o===1?o:eo(r(o),t,s)}const to=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,no=e=>t=>1-e(1-t),so=fn(.33,1.53,.69,.99),qs=no(so),ro=to(qs),io=e=>(e*=2)<1?.5*qs(e):.5*(2-Math.pow(2,-10*(e-1))),Hs=e=>1-Math.sin(Math.acos(e)),oo=no(Hs),ao=to(Hs),gc=fn(.42,0,1,1),yc=fn(0,0,.58,1),co=fn(.42,0,.58,1),xc=e=>Array.isArray(e)&&typeof e[0]!="number",lo=e=>Array.isArray(e)&&typeof e[0]=="number",Er={linear:Ee,easeIn:gc,easeInOut:co,easeOut:yc,circIn:Hs,circInOut:ao,circOut:oo,backIn:qs,backInOut:ro,backOut:so,anticipate:io},vc=e=>typeof e=="string",Dr=e=>{if(lo(e)){Ke(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return fn(t,n,s,r)}else if(vc(e))return Ke(Er[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Er[e];return e},Sn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function bc(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 c(l){i.has(l)&&(u.schedule(l),e()),l(a)}const u={schedule:(l,f=!1,d=!1)=>{const b=d&&r?n:s;return f&&i.add(l),b.has(l)||b.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 wc=40;function uo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Sn.reduce((y,N)=>(y[N]=bc(o),y),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:f,preRender:d,render:g,postRender:b}=i,x=()=>{const y=qe.useManualTiming?r.timestamp:performance.now();n=!1,qe.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(y-r.timestamp,wc),1)),r.timestamp=y,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),f.process(r),d.process(r),g.process(r),b.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(x))},S=()=>{n=!0,s=!0,r.isProcessing||e(x)};return{schedule:Sn.reduce((y,N)=>{const M=i[N];return y[N]=(k,P=!1,j=!1)=>(n||S(),M.schedule(k,P,j)),y},{}),cancel:y=>{for(let N=0;N<Sn.length;N++)i[Sn[N]].cancel(y)},state:r,steps:i}}const{schedule:ne,cancel:ot,state:ye,steps:Jn}=uo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ee,!0);let kn;function Tc(){kn=void 0}const Pe={now:()=>(kn===void 0&&Pe.set(ye.isProcessing||qe.useManualTiming?ye.timestamp:performance.now()),kn),set:e=>{kn=e,queueMicrotask(Tc)}},ho=e=>t=>typeof t=="string"&&t.startsWith(e),Gs=ho("--"),Sc=ho("var(--"),Xs=e=>Sc(e)?Ac.test(e.split("/*")[0].trim()):!1,Ac=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Bt={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},an={...Bt,transform:e=>We(0,1,e)},An={...Bt,default:1},Qt=e=>Math.round(e*1e5)/1e5,Ys=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Pc(e){return e==null}const Cc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Js=(e,t)=>n=>!!(typeof n=="string"&&Cc.test(n)&&n.startsWith(e)||t&&!Pc(n)&&Object.prototype.hasOwnProperty.call(n,t)),fo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Ys);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},jc=e=>We(0,255,e),Zn={...Bt,transform:e=>Math.round(jc(e))},vt={test:Js("rgb","red"),parse:fo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Zn.transform(e)+", "+Zn.transform(t)+", "+Zn.transform(n)+", "+Qt(an.transform(s))+")"};function kc(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 ms={test:Js("#"),parse:kc,transform:vt.transform},mn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),it=mn("deg"),ze=mn("%"),F=mn("px"),Mc=mn("vh"),Ec=mn("vw"),Nr={...ze,parse:e=>ze.parse(e)/100,transform:e=>ze.transform(e*100)},Mt={test:Js("hsl","hue"),parse:fo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+ze.transform(Qt(t))+", "+ze.transform(Qt(n))+", "+Qt(an.transform(s))+")"},he={test:e=>vt.test(e)||ms.test(e)||Mt.test(e),parse:e=>vt.test(e)?vt.parse(e):Mt.test(e)?Mt.parse(e):ms.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?vt.transform(e):Mt.transform(e),getAnimatableNone:e=>{const t=he.parse(e);return t.alpha=0,he.transform(t)}},Dc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Nc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Ys)?.length||0)+(e.match(Dc)?.length||0)>0}const mo="number",po="color",Vc="var",Rc="var(",Vr="${}",Ic=/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 cn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(Ic,c=>(he.test(c)?(s.color.push(o),r.push(po),n.push(he.parse(c))):c.startsWith(Rc)?(s.var.push(o),r.push(Vc),n.push(c)):(s.number.push(o),r.push(mo),n.push(parseFloat(c))),++o,Vr)).split(Vr);return{values:n,split:a,indexes:s,types:r}}function go(e){return cn(e).values}function yo(e){const{split:t,types:n}=cn(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===mo?o+=Qt(r[i]):a===po?o+=he.transform(r[i]):o+=r[i]}return o}}const Oc=e=>typeof e=="number"?0:he.test(e)?he.getAnimatableNone(e):e;function Lc(e){const t=go(e);return yo(e)(t.map(Oc))}const at={test:Nc,parse:go,createTransformer:yo,getAnimatableNone:Lc};function Qn(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 Fc({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,c=2*n-a;r=Qn(c,a,e+1/3),o=Qn(c,a,e),i=Qn(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function In(e,t){return n=>n>0?t:e}const oe=(e,t,n)=>e+(t-e)*n,es=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},$c=[ms,vt,Mt],Bc=e=>$c.find(t=>t.test(e));function Rr(e){const t=Bc(e);if($t(!!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===Mt&&(n=Fc(n)),n}const Ir=(e,t)=>{const n=Rr(e),s=Rr(t);if(!n||!s)return In(e,t);const r={...n};return o=>(r.red=es(n.red,s.red,o),r.green=es(n.green,s.green,o),r.blue=es(n.blue,s.blue,o),r.alpha=oe(n.alpha,s.alpha,o),vt.transform(r))},ps=new Set(["none","hidden"]);function zc(e,t){return ps.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Uc(e,t){return n=>oe(e,t,n)}function Zs(e){return typeof e=="number"?Uc:typeof e=="string"?Xs(e)?In:he.test(e)?Ir:Kc:Array.isArray(e)?xo:typeof e=="object"?he.test(e)?Ir:_c:In}function xo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Zs(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function _c(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Zs(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Wc(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 Kc=(e,t)=>{const n=at.createTransformer(t),s=cn(e),r=cn(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?ps.has(e)&&!r.values.length||ps.has(t)&&!s.values.length?zc(e,t):hn(xo(Wc(s,r),r.values),n):($t(!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"),In(e,t))};function vo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?oe(e,t,n):Zs(e)(e,t)}const qc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ne.update(t,n),stop:()=>ot(t),now:()=>ye.isProcessing?ye.timestamp:Pe.now()}},bo=(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)})`},On=2e4;function Qs(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<On;)t+=n,s=e.next(t);return t>=On?1/0:t}function Hc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Qs(s),On);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Me(r)}}const Gc=5;function wo(e,t,n){const s=Math.max(t-Gc,0);return Qi(n-e(s),t-s)}const ie={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},ts=.001;function Xc({duration:e=ie.duration,bounce:t=ie.bounce,velocity:n=ie.velocity,mass:s=ie.mass}){let r,o;$t(e<=Ie(ie.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=We(ie.minDamping,ie.maxDamping,i),e=We(ie.minDuration,ie.maxDuration,Me(e)),i<1?(r=u=>{const l=u*i,f=l*e,d=l-n,g=gs(u,i),b=Math.exp(-f);return ts-d/g*b},o=u=>{const f=u*i*e,d=f*n+n,g=Math.pow(i,2)*Math.pow(u,2)*e,b=Math.exp(-f),x=gs(Math.pow(u,2),i);return(-r(u)+ts>0?-1:1)*((d-g)*b)/x}):(r=u=>{const l=Math.exp(-u*e),f=(u-n)*e+1;return-ts+l*f},o=u=>{const l=Math.exp(-u*e),f=(n-u)*(e*e);return l*f});const a=5/e,c=Jc(r,o,a);if(e=Ie(e),isNaN(c))return{stiffness:ie.stiffness,damping:ie.damping,duration:e};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const Yc=12;function Jc(e,t,n){let s=n;for(let r=1;r<Yc;r++)s=s-e(s)/t(s);return s}function gs(e,t){return e*Math.sqrt(1-t*t)}const Zc=["duration","bounce"],Qc=["stiffness","damping","mass"];function Or(e,t){return t.some(n=>e[n]!==void 0)}function el(e){let t={velocity:ie.velocity,stiffness:ie.stiffness,damping:ie.damping,mass:ie.mass,isResolvedFromDuration:!1,...e};if(!Or(e,Qc)&&Or(e,Zc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*We(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:ie.mass,stiffness:r,damping:o}}else{const n=Xc(e);t={...t,...n,mass:ie.mass},t.isResolvedFromDuration=!0}return t}function Ln(e=ie.visualDuration,t=ie.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:c,damping:u,mass:l,duration:f,velocity:d,isResolvedFromDuration:g}=el({...n,velocity:-Me(n.velocity||0)}),b=d||0,x=u/(2*Math.sqrt(c*l)),S=i-o,T=Me(Math.sqrt(c/l)),v=Math.abs(S)<5;s||(s=v?ie.restSpeed.granular:ie.restSpeed.default),r||(r=v?ie.restDelta.granular:ie.restDelta.default);let y;if(x<1){const M=gs(T,x);y=k=>{const P=Math.exp(-x*T*k);return i-P*((b+x*T*S)/M*Math.sin(M*k)+S*Math.cos(M*k))}}else if(x===1)y=M=>i-Math.exp(-T*M)*(S+(b+T*S)*M);else{const M=T*Math.sqrt(x*x-1);y=k=>{const P=Math.exp(-x*T*k),j=Math.min(M*k,300);return i-P*((b+x*T*S)*Math.sinh(j)+M*S*Math.cosh(j))/M}}const N={calculatedDuration:g&&f||null,next:M=>{const k=y(M);if(g)a.done=M>=f;else{let P=M===0?b:0;x<1&&(P=M===0?Ie(b):wo(y,M,k));const j=Math.abs(P)<=s,q=Math.abs(i-k)<=r;a.done=j&&q}return a.value=a.done?i:k,a},toString:()=>{const M=Math.min(Qs(N),On),k=bo(P=>N.next(M*P).value,M,30);return M+"ms "+k},toTransition:()=>{}};return N}Ln.applyToOptions=e=>{const t=Hc(e,100,Ln);return e.ease=t.ease,e.duration=Ie(t.duration),e.type="keyframes",e};function ys({keyframes:e,velocity:t=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 f=e[0],d={done:!1,value:f},g=j=>a!==void 0&&j<a||c!==void 0&&j>c,b=j=>a===void 0?c:c===void 0||Math.abs(a-j)<Math.abs(c-j)?a:c;let x=n*t;const S=f+x,T=i===void 0?S:i(S);T!==S&&(x=T-f);const v=j=>-x*Math.exp(-j/s),y=j=>T+v(j),N=j=>{const q=v(j),L=y(j);d.done=Math.abs(q)<=u,d.value=d.done?T:L};let M,k;const P=j=>{g(d.value)&&(M=j,k=Ln({keyframes:[d.value,b(d.value)],velocity:wo(y,j,d.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return P(0),{calculatedDuration:null,next:j=>{let q=!1;return!k&&M===void 0&&(q=!0,N(j),P(j)),M!==void 0&&j>=M?k.next(j-M):(!q&&N(j),d)}}}function tl(e,t,n){const s=[],r=n||qe.mix||vo,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const c=Array.isArray(t)?t[i]||Ee:t;a=hn(c,a)}s.push(a)}return s}function nl(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(Ke(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=tl(t,s,r),c=a.length,u=l=>{if(i&&l<e[0])return t[0];let f=0;if(c>1)for(;f<e.length-2&&!(l<e[f+1]);f++);const d=on(e[f],e[f+1],l);return a[f](d)};return n?l=>u(We(e[0],e[o-1],l)):u}function sl(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=on(0,t,s);e.push(oe(n,1,r))}}function rl(e){const t=[0];return sl(t,e.length-1),t}function il(e,t){return e.map(n=>n*t)}function ol(e,t){return e.map(()=>t||co).splice(0,e.length-1)}function Et({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=xc(s)?s.map(Dr):Dr(s),o={done:!1,value:t[0]},i=il(n&&n.length===t.length?n:rl(t),e),a=nl(i,t,{ease:Array.isArray(r)?r:ol(t,r)});return{calculatedDuration:e,next:c=>(o.value=a(c),o.done=c>=e,o)}}const al=e=>e!==null;function er(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(al),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const cl={decay:ys,inertia:ys,tween:Et,keyframes:Et,spring:Ln};function To(e){typeof e.type=="string"&&(e.type=cl[e.type])}class tr{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 ll=e=>e/100;class nr extends tr{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!==Pe.now()&&this.tick(Pe.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;To(t);const{type:n=Et,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const c=n||Et;process.env.NODE_ENV!=="production"&&c!==Et&&Ke(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Et&&typeof a[0]!="number"&&(this.mixKeyframes=hn(ll,vo(a[0],a[1])),a=[0,100]);const u=c({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=Qs(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+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:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:f,repeatType:d,repeatDelay:g,type:b,onUpdate:x,finalKeyframe:S}=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 T=this.currentTime-u*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?T<0:T>r;this.currentTime=Math.max(T,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let y=this.currentTime,N=s;if(f){const j=Math.min(this.currentTime,r)/a;let q=Math.floor(j),L=j%1;!L&&j>=1&&(L=1),L===1&&q--,q=Math.min(q,f+1),!!(q%2)&&(d==="reverse"?(L=1-L,g&&(L-=g/a)):d==="mirror"&&(N=i)),y=We(0,1,L)*a}const M=v?{done:!1,value:l[0]}:N.next(y);o&&(M.value=o(M.value));let{done:k}=M;!v&&c!==null&&(k=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return P&&b!==ys&&(M.value=er(l,this.options,S,this.speed)),x&&x(M.value),P&&this.finish(),M}then(t,n){return this.finished.then(t,n)}get duration(){return Me(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Me(t)}get time(){return Me(this.currentTime)}set time(t){t=Ie(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(Pe.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Me(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=qc,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(Pe.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 ul(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const bt=e=>e*180/Math.PI,xs=e=>{const t=bt(Math.atan2(e[1],e[0]));return vs(t)},dl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:xs,rotateZ:xs,skewX:e=>bt(Math.atan(e[1])),skewY:e=>bt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},vs=e=>(e=e%360,e<0&&(e+=360),e),Lr=xs,Fr=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),$r=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),hl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Fr,scaleY:$r,scale:e=>(Fr(e)+$r(e))/2,rotateX:e=>vs(bt(Math.atan2(e[6],e[5]))),rotateY:e=>vs(bt(Math.atan2(-e[2],e[0]))),rotateZ:Lr,rotate:Lr,skewX:e=>bt(Math.atan(e[4])),skewY:e=>bt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function bs(e){return e.includes("scale")?1:0}function ws(e,t){if(!e||e==="none")return bs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=hl,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=dl,r=a}if(!r)return bs(t);const o=s[t],i=r[1].split(",").map(ml);return typeof o=="function"?o(i):i[o]}const fl=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return ws(n,t)};function ml(e){return parseFloat(e.trim())}const zt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ut=new Set(zt),Br=e=>e===Bt||e===F,pl=new Set(["x","y","z"]),gl=zt.filter(e=>!pl.has(e));function yl(e){const t=[];return gl.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const wt={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})=>ws(t,"x"),y:(e,{transform:t})=>ws(t,"y")};wt.translateX=wt.x;wt.translateY=wt.y;const Tt=new Set;let Ts=!1,Ss=!1,As=!1;function So(){if(Ss){const e=Array.from(Tt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=yl(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)})}Ss=!1,Ts=!1,Tt.forEach(e=>e.complete(As)),Tt.clear()}function Ao(){Tt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ss=!0)})}function xl(){As=!0,Ao(),So(),As=!1}class sr{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?(Tt.add(this),Ts||(Ts=!0,ne.read(Ao),ne.resolveKeyframes(So))):(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])}ul(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Tt.delete(this)}cancel(){this.state==="scheduled"&&(Tt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const vl=e=>e.startsWith("--");function bl(e,t,n){vl(t)?e.style.setProperty(t,n):e.style[t]=n}const wl=_s(()=>window.ScrollTimeline!==void 0),Tl={};function Sl(e,t){const n=_s(e);return()=>Tl[t]??n()}const Po=Sl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zt=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,zr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zt([0,.65,.55,1]),circOut:Zt([.55,0,1,.45]),backIn:Zt([.31,.01,.66,-.59]),backOut:Zt([.33,1.53,.69,.99])};function Co(e,t){if(e)return typeof e=="function"?Po()?bo(e,t):"ease-out":lo(e)?Zt(e):Array.isArray(e)?e.map(n=>Co(n,t)||zr.easeOut):zr[e]}function Al(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[t]:n};c&&(l.offset=c);const f=Co(a,r);Array.isArray(f)&&(l.easing=f);const d={delay:s,duration:r,easing:Array.isArray(f)?"linear":f,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(d.pseudoElement=u),e.animate(l,d)}function jo(e){return typeof e=="function"&&"applyToOptions"in e}function Pl({type:e,...t}){return jo(e)&&Po()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Cl extends tr{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:c}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,Ke(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Pl(t);this.animation=Al(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=er(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):bl(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: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 Me(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Me(t)}get time(){return Me(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Ie(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&&wl()?(this.animation.timeline=t,Ee):n(this)}}const ko={anticipate:io,backInOut:ro,circInOut:ao};function jl(e){return e in ko}function kl(e){typeof e.ease=="string"&&jl(e.ease)&&(e.ease=ko[e.ease])}const Ur=10;class Ml extends Cl{constructor(t){kl(t),To(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 nr({...i,autoplay:!1}),c=Ie(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Ur).value,a.sample(c).value,Ur),a.stop()}}const _r=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(at.test(e)||e==="0")&&!e.startsWith("url("));function El(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 Dl(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=_r(r,t),a=_r(o,t);return $t(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:El(e)||(n==="spring"||jo(n))&&s}function Ps(e){e.duration=0,e.type="keyframes"}const Nl=new Set(["opacity","clipPath","filter","transform"]),Vl=_s(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Rl(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:c,transformTemplate:u}=t.owner.getProps();return Vl()&&n&&Nl.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Il=40;class Ol extends tr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...f}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Pe.now();const d={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...f},g=l?.KeyframeResolver||sr;this.keyframeResolver=new g(a,(b,x,S)=>this.onKeyframesResolved(b,x,d,!S),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=Pe.now(),Dl(t,o,i,a)||((qe.instantAnimations||!c)&&l?.(er(t,s,n)),t[0]=t[t.length-1],Ps(s),s.repeat=0);const d={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Il?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=!u&&Rl(d)?new Ml({...d,element:d.motionValue.owner.current}):new nr(d);g.finished.then(()=>this.notifyFinished()).catch(Ee),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(),xl()),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 Ll=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Fl(e){const t=Ll.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const $l=4;function Mo(e,t,n=1){Ke(n<=$l,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Fl(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Yi(i)?parseFloat(i):i}return Xs(r)?Mo(r,t,n+1):r}function rr(e,t){return e?.[t]??e?.default??e}const Eo=new Set(["width","height","top","left","right","bottom",...zt]),Bl={test:e=>e==="auto",parse:e=>e},Do=e=>t=>t.test(e),No=[Bt,F,ze,it,Ec,Mc,Bl],Wr=e=>No.find(Do(e));function zl(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Zi(e):!0}const Ul=new Set(["brightness","contrast","saturate","opacity"]);function _l(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Ys)||[];if(!s)return e;const r=n.replace(s,"");let o=Ul.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Wl=/\b([a-z-]*)\(.*?\)/gu,Cs={...at,getAnimatableNone:e=>{const t=e.match(Wl);return t?t.map(_l).join(" "):e}},Kr={...Bt,transform:Math.round},Kl={rotate:it,rotateX:it,rotateY:it,rotateZ:it,scale:An,scaleX:An,scaleY:An,scaleZ:An,skew:it,skewX:it,skewY:it,distance:F,translateX:F,translateY:F,translateZ:F,x:F,y:F,z:F,perspective:F,transformPerspective:F,opacity:an,originX:Nr,originY:Nr,originZ:F},ir={borderWidth:F,borderTopWidth:F,borderRightWidth:F,borderBottomWidth:F,borderLeftWidth:F,borderRadius:F,radius:F,borderTopLeftRadius:F,borderTopRightRadius:F,borderBottomRightRadius:F,borderBottomLeftRadius:F,width:F,maxWidth:F,height:F,maxHeight:F,top:F,right:F,bottom:F,left:F,padding:F,paddingTop:F,paddingRight:F,paddingBottom:F,paddingLeft:F,margin:F,marginTop:F,marginRight:F,marginBottom:F,marginLeft:F,backgroundPositionX:F,backgroundPositionY:F,...Kl,zIndex:Kr,fillOpacity:an,strokeOpacity:an,numOctaves:Kr},ql={...ir,color:he,backgroundColor:he,outlineColor:he,fill:he,stroke:he,borderColor:he,borderTopColor:he,borderRightColor:he,borderBottomColor:he,borderLeftColor:he,filter:Cs,WebkitFilter:Cs},Vo=e=>ql[e];function Ro(e,t){let n=Vo(e);return n!==Cs&&(n=at),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Hl=new Set(["auto","none","0"]);function Gl(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Hl.has(o)&&cn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=Ro(n,r)}class Xl extends sr{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 c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),Xs(u))){const l=Mo(u,n.current);l!==void 0&&(t[c]=l),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Eo.has(s)||t.length!==2)return;const[r,o]=t,i=Wr(r),a=Wr(o);if(i!==a)if(Br(i)&&Br(a))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else wt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||zl(t[r]))&&s.push(r);s.length&&Gl(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=wt[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]=wt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{t.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function Yl(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 Io=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Oo(e){return Ji(e)&&"offsetHeight"in e}const qr=30,Jl=e=>!isNaN(parseFloat(e));class Zl{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Pe.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=Pe.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Jl(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Ks(!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 Ws);const s=this.events[t].add(n);return t==="change"?()=>{s(),ne.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=Pe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>qr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,qr);return Qi(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 Lt(e,t){return new Zl(e,t)}const{schedule:or}=uo(queueMicrotask,!1),Ve={x:!1,y:!1};function Lo(){return Ve.x||Ve.y}function Ql(e){return e==="x"||e==="y"?Ve[e]?null:(Ve[e]=!0,()=>{Ve[e]=!1}):Ve.x||Ve.y?null:(Ve.x=Ve.y=!0,()=>{Ve.x=Ve.y=!1})}function Fo(e,t){const n=Yl(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Hr(e){return!(e.pointerType==="touch"||Lo())}function eu(e,t,n={}){const[s,r,o]=Fo(e,n),i=a=>{if(!Hr(a))return;const{target:c}=a,u=t(c,a);if(typeof u!="function"||!c)return;const l=f=>{Hr(f)&&(u(f),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const $o=(e,t)=>t?e===t?!0:$o(e,t.parentElement):!1,ar=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,tu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function nu(e){return tu.has(e.tagName)||e.tabIndex!==-1}const Mn=new WeakSet;function Gr(e){return t=>{t.key==="Enter"&&e(t)}}function ns(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const su=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Gr(()=>{if(Mn.has(n))return;ns(n,"down");const r=Gr(()=>{ns(n,"up")}),o=()=>ns(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 Xr(e){return ar(e)&&!Lo()}function ru(e,t,n={}){const[s,r,o]=Fo(e,n),i=a=>{const c=a.currentTarget;if(!Xr(a))return;Mn.add(c);const u=t(c,a),l=(g,b)=>{window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",d),Mn.has(c)&&Mn.delete(c),Xr(g)&&typeof u=="function"&&u(g,{success:b})},f=g=>{l(g,c===window||c===document||n.useGlobalTarget||$o(c,g.target))},d=g=>{l(g,!1)};window.addEventListener("pointerup",f,r),window.addEventListener("pointercancel",d,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),Oo(a)&&(a.addEventListener("focus",u=>su(u,r)),!nu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Bo(e){return Ji(e)&&"ownerSVGElement"in e}function iu(e){return Bo(e)&&e.tagName==="svg"}const be=e=>!!(e&&e.getVelocity),ou=[...No,he,at],au=e=>ou.find(Do(e)),cr=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Yr(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function cu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Yr(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():Yr(e[r],null)}}}}function lu(...e){return Re.useCallback(cu(...e),e)}class uu extends Re.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=Oo(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 du({children:e,isPresent:t,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(cr),c=lu(o,e?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:f,left:d,right:g}=i.current;if(t||!o.current||!u||!l)return;const b=n==="left"?`left: ${d}`:`right: ${g}`;o.current.dataset.motionPopId=r;const x=document.createElement("style");a&&(x.nonce=a);const S=s??document.head;return S.appendChild(x),x.sheet&&x.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
5
5
  height: ${l}px !important;
6
- ${x}px !important;
7
- top: ${h}px !important;
6
+ ${b}px !important;
7
+ top: ${f}px !important;
8
8
  }
9
- `),()=>{j.contains(b)&&j.removeChild(b)}},[e]),d.jsx(lu,{isPresent:e,childRef:o,sizeRef:i,children:Ot.cloneElement(t,{ref:c})})}const du=({children:t,initial:e,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=Fs(hu),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 x of u.values())if(!x)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,x)=>u.set(x,!1))},[n]),Ot.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(t=d.jsx(uu,{isPresent:n,anchorX:a,root:c,children:t})),d.jsx($n.Provider,{value:f,children:t})};function hu(){return new Map}function Bo(t=!0){const e=m.useContext($n);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 An=t=>t.key||"";function Yr(t){const e=[];return m.Children.forEach(t,n=>{m.isValidElement(n)&&e.push(n)}),e}const fu=({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]=Bo(i),h=m.useMemo(()=>Yr(t),[t]),f=i&&!u?[]:h.map(An),g=m.useRef(!0),x=m.useRef(h),b=Fs(()=>new Map),[j,y]=m.useState(h),[v,T]=m.useState(h);Xi(()=>{g.current=!1,x.current=h;for(let R=0;R<v.length;R++){const C=An(v[R]);f.includes(C)?b.delete(C):b.get(C)!==!0&&b.set(C,!1)}},[v,f.length,f.join("-")]);const S=[];if(h!==j){let R=[...h];for(let C=0;C<v.length;C++){const k=v[C],W=An(k);f.includes(W)||(R.splice(C,0,k),S.push(k))}return o==="wait"&&S.length&&(R=S),T(Yr(R)),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:E}=m.useContext(Ls);return d.jsx(d.Fragment,{children:v.map(R=>{const C=An(R),k=i&&!u?!1:h===v||f.includes(C),W=()=>{if(b.has(C))b.set(C,!0);else return;let O=!0;b.forEach(et=>{et||(O=!1)}),O&&(E?.(),T(x.current),i&&l?.(),s&&s())};return d.jsx(du,{isPresent:k,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:k?void 0:W,anchorX:a,children:R},C)})})},cr=m.createContext({strict:!1}),Jr={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"]},Ie={};for(const t in Jr)Ie[t]={isEnabled:e=>Jr[t].some(n=>!!e[n])};function Ps(t){for(const e in t)Ie[e]={...Ie[e],...t[e]}}function mu({children:t,features:e,strict:n=!1}){const[,s]=m.useState(!ns(e)),r=m.useRef(void 0);if(!ns(e)){const{renderer:o,...i}=e;r.current=o,Ps(i)}return m.useEffect(()=>{ns(e)&&e().then(({renderer:o,...i})=>{Ps(i),r.current=o,s(!0)})},[]),d.jsx(cr.Provider,{value:{renderer:r.current,strict:n},children:t})}function ns(t){return typeof t=="function"}const pu=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 Ln(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||pu.has(t)}let zo=t=>!Ln(t);function gu(t){typeof t=="function"&&(zo=e=>e.startsWith("on")?!Ln(e):t(e))}try{gu(require("@emotion/is-prop-valid").default)}catch{}function yu(t,e,n){const s={};for(const r in t)r==="values"&&typeof t.values=="object"||(zo(r)||n===!0&&Ln(r)||!e&&!Ln(r)||t.draggable&&r.startsWith("onDrag"))&&(s[r]=t[r]);return s}const Bn=m.createContext({});function zn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function an(t){return typeof t=="string"||Array.isArray(t)}const lr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ur=["initial",...lr];function Un(t){return zn(t.animate)||ur.some(e=>an(t[e]))}function Uo(t){return!!(Un(t)||t.variants)}function xu(t,e){if(Un(t)){const{initial:n,animate:s}=t;return{initial:n===!1||an(n)?n:void 0,animate:an(s)?s:void 0}}return t.inherit!==!1?e:{}}function vu(t){const{initial:e,animate:n}=xu(t,m.useContext(Bn));return m.useMemo(()=>({initial:e,animate:n}),[Zr(e),Zr(n)])}function Zr(t){return Array.isArray(t)?t.join(" "):t}const cn={};function bu(t){for(const e in t)cn[e]=t[e],Hs(e)&&(cn[e].isCSSVariable=!0)}function _o(t,{layout:e,layoutId:n}){return $e.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!cn[t]||t==="opacity")}const wu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Tu=Fe.length;function Su(t,e,n){let s="",r=!0;for(let o=0;o<Tu;o++){const i=Fe[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=Ro(a,rr[i]);if(!c){r=!1;const l=wu[i]||i;s+=`${l}(${u}) `}n&&(e[i]=u)}}return s=s.trim(),n?s=n(e,r?"":s):r&&(s="none"),s}function dr(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($e.has(c)){i=!0;continue}else if(Hs(c)){r[c]=u;continue}else{const l=Ro(u,rr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(e.transform||(i||n?s.transform=Su(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 hr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Wo(t,e,n){for(const s in e)!gt(e[s])&&!_o(s,n)&&(t[s]=e[s])}function Au({transformTemplate:t},e){return m.useMemo(()=>{const n=hr();return dr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Cu(t,e){const n=t.style||{},s={};return Wo(s,n,t),Object.assign(s,Au(t,e)),s}function Pu(t,e){const n={},s=Cu(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 ju={offset:"stroke-dashoffset",array:"stroke-dasharray"},ku={offset:"strokeDashoffset",array:"strokeDasharray"};function Mu(t,e,n=1,s=0,r=!0){t.pathLength=1;const o=r?ju:ku;t[o.offset]=L.transform(-s);const i=L.transform(e),a=L.transform(n);t[o.array]=`${i} ${a}`}function Ko(t,{attrX:e,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(dr(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&&Mu(h,r,o,i,!1)}const qo=()=>({...hr(),attrs:{}}),Ho=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Eu(t,e,n,s){const r=m.useMemo(()=>{const o=qo();return Ko(o,e,Ho(s),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Wo(o,t.style,t),r.style={...o,...r.style}}return r}const Du=["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 fr(t){return typeof t!="string"||t.includes("-")?!1:!!(Du.indexOf(t)>-1||/[A-Z]/u.test(t))}function Nu(t,e,n,{latestValues:s},r,o=!1){const a=(fr(t)?Eu:Pu)(e,s,r,t),c=yu(e,typeof t=="string",o),u=t!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=e,h=m.useMemo(()=>gt(l)?l.get():l,[l]);return m.createElement(t,{...u,children:h})}function Qr(t){const e=[{},{}];return t?.values.forEach((n,s)=>{e[0][s]=n.get(),e[1][s]=n.getVelocity()}),e}function mr(t,e,n,s){if(typeof e=="function"){const[r,o]=Qr(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]=Qr(s);e=e(n!==void 0?n:t.custom,r,o)}return e}function Mn(t){return gt(t)?t.get():t}function Vu({scrapeMotionValuesFromProps:t,createRenderState:e},n,s,r){return{latestValues:Ru(n,s,r,t),renderState:e()}}function Ru(t,e,n,s){const r={},o=s(t,{});for(const f in o)r[f]=Mn(o[f]);let{initial:i,animate:a}=t;const c=Un(t),u=Uo(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"&&!zn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const x=mr(t,f[g]);if(x){const{transitionEnd:b,transition:j,...y}=x;for(const v in y){let T=y[v];if(Array.isArray(T)){const S=l?T.length-1:0;T=T[S]}T!==null&&(r[v]=T)}for(const v in b)r[v]=b[v]}}}return r}const Xo=t=>(e,n)=>{const s=m.useContext(Bn),r=m.useContext($n),o=()=>Vu(t,e,s,r);return n?o():Fs(o)};function pr(t,e,n){const{style:s}=t,r={};for(const o in s)(gt(s[o])||e.style&&gt(e.style[o])||_o(o,t)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Iu=Xo({scrapeMotionValuesFromProps:pr,createRenderState:hr});function Go(t,e,n){const s=pr(t,e,n);for(const r in t)if(gt(t[r])||gt(e[r])){const o=Fe.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=t[r]}return s}const Ou=Xo({scrapeMotionValuesFromProps:Go,createRenderState:qo}),Lu=Symbol.for("motionComponentSymbol");function ke(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Fu(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):ke(n)&&(n.current=s))},[e])}const gr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),$u="framerAppearId",Yo="data-"+gr($u),Jo=m.createContext({});function Bu(t,e,n,s,r){const{visualElement:o}=m.useContext(Bn),i=m.useContext(cr),a=m.useContext($n),c=m.useContext(ar).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(Jo);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&zu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[Yo],x=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return Xi(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),x.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!x.current&&l.animationState&&l.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),x.current=!1),l.enteringChildren=void 0)}),l}function zu(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:Zo(t.parent)),t.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&ke(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function Zo(t){if(t)return t.options.allowProjection!==!1?t.projection:Zo(t.parent)}function En(t,{forwardMotionProps:e=!1}={},n,s){n&&Ps(n);const r=fr(t)?Ou:Iu;function o(a,c){let u;const l={...m.useContext(ar),...a,layoutId:Uu(a)},{isStatic:h}=l,f=vu(a),g=r(a,h);if(!h&&$s){_u(l,n);const x=Wu(l);u=x.MeasureLayout,f.visualElement=Bu(t,g,l,s,x.ProjectionNode)}return d.jsxs(Bn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Nu(t,a,Fu(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[Lu]=t,i}function Uu({layoutId:t}){const e=m.useContext(Ls).id;return e&&t!==void 0?e+"-"+t:t}function _u(t,e){const n=m.useContext(cr).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?Oe(!1,s,"lazy-strict-mode"):Kt(!1,s,"lazy-strict-mode")}}function Wu(t){const{drag:e,layout:n}=Ie;if(!e&&!n)return{};const s={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Ku(t,e){if(typeof Proxy>"u")return En;const n=new Map,s=(o,i)=>En(o,i,t,e),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Ws(!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,En(i,void 0,t,e)),n.get(i))})}function Qo({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}function qu({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Hu(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 ss(t){return t===void 0||t===1}function js({scale:t,scaleX:e,scaleY:n}){return!ss(t)||!ss(e)||!ss(n)}function ge(t){return js(t)||ta(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ta(t){return ti(t.x)||ti(t.y)}function ti(t){return t&&t!=="0%"}function Fn(t,e,n){const s=t-n,r=e*s;return n+r}function ei(t,e,n,s,r){return r!==void 0&&(t=Fn(t,r,s)),Fn(t,n,s)+e}function ks(t,e=0,n=1,s,r){t.min=ei(t.min,e,n,s,r),t.max=ei(t.max,e,n,s,r)}function ea(t,{x:e,y:n}){ks(t.x,e.translate,e.scale,e.originPoint),ks(t.y,n.translate,n.scale,n.originPoint)}const ni=.999999999999,si=1.0000000000001;function Xu(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&&Ee(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(e.x*=i.x.scale,e.y*=i.y.scale,ea(t,i)),s&&ge(o.latestValues)&&Ee(t,o.latestValues))}e.x<si&&e.x>ni&&(e.x=1),e.y<si&&e.y>ni&&(e.y=1)}function Me(t,e){t.min=t.min+e,t.max=t.max+e}function ri(t,e,n,s,r=.5){const o=it(t.min,t.max,r);ks(t,e,n,o,s)}function Ee(t,e){ri(t.x,e.x,e.scaleX,e.scale,e.originX),ri(t.y,e.y,e.scaleY,e.scale,e.originY)}function na(t,e){return Qo(Hu(t.getBoundingClientRect(),e))}function Gu(t,e,n){const s=na(t,n),{scroll:r}=e;return r&&(Me(s.x,r.offset.x),Me(s.y,r.offset.y)),s}const ii=()=>({translate:0,scale:1,origin:0,originPoint:0}),De=()=>({x:ii(),y:ii()}),oi=()=>({min:0,max:0}),at=()=>({x:oi(),y:oi()}),Ms={current:null},sa={current:!1};function Yu(){if(sa.current=!0,!!$s)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Ms.current=t.matches;t.addEventListener("change",e),e()}else Ms.current=!1}const Ju=new WeakMap;function Zu(t,e,n){for(const s in e){const r=e[s],o=n[s];if(gt(r))t.addValue(s,r);else if(gt(o))t.addValue(s,Re(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,Re(i!==void 0?i:r,{owner:t}))}}for(const s in n)e[s]===void 0&&t.removeValue(s);return e}const ai=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Qu{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=nr,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=At.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,st.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=Un(n),this.isVariantNode=Uo(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&&gt(g)&&g.set(c[f])}}mount(e){this.current=e,Ju.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)),sa.current||Yu(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ms.current,process.env.NODE_ENV!=="production"&&Ws(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(),se(this.notifyUpdate),se(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=$e.has(e);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[e]=i,this.props.onUpdate&&st.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 Ie){const n=Ie[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):at()}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<ai.length;s++){const r=ai[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=Zu(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=Re(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"&&(Gi(s)||Ji(s))?s=parseFloat(s):!ou(s)&&re.test(n)&&(s=Vo(e,n)),this.setBaseTarget(e,gt(s)?s.get():s)),gt(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=mr(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&&!gt(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 _s),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){ir.render(this.render)}}class ra extends Qu{constructor(){super(...arguments),this.KeyframeResolver=Xl}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;gt(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function ia(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 td(t){return window.getComputedStyle(t)}class ed extends ra{constructor(){super(...arguments),this.type="html",this.renderInstance=ia}readValueFromInstance(e,n){if($e.has(n))return this.projection?.isProjecting?vs(n):hl(e,n);{const s=td(e),r=(Hs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return na(e,n)}build(e,n,s){dr(e,n,s.transformTemplate)}scrapeMotionValuesFromProps(e,n,s){return pr(e,n,s)}}const oa=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 nd(t,e,n,s){ia(t,e,void 0,s);for(const r in e.attrs)t.setAttribute(oa.has(r)?r:gr(r),e.attrs[r])}class sd extends ra{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=at}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if($e.has(n)){const s=No(n);return s&&s.default||0}return n=oa.has(n)?n:gr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,s){return Go(e,n,s)}build(e,n,s){Ko(e,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(e,n,s,r){nd(e,n,s,r)}mount(e){this.isSVGTag=Ho(e.tagName),super.mount(e)}}const aa=(t,e)=>fr(t)?new sd(e):new ed(e,{allowProjection:t!==m.Fragment});function Ve(t,e,n){const s=t.getProps();return mr(s,e,n!==void 0?n:s.custom,t)}const Es=t=>Array.isArray(t);function rd(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Re(n))}function id(t){return Es(t)?t[t.length-1]||0:t}function od(t,e){const n=Ve(t,e);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=id(o[i]);rd(t,i,a)}}function ad(t){return!!(gt(t)&&t.add)}function Ds(t,e){const n=t.getValue("willChange");if(ad(n))return n.add(e);if(!n&&qt.WillChange){const s=new qt.WillChange("auto");t.addValue("willChange",s),s.add(e)}}function ca(t){return t.props[Yo]}const cd=t=>t!==null;function ld(t,{repeat:e,repeatType:n="loop"},s){const r=t.filter(cd),o=e&&n!=="loop"&&e%2===1?0:r.length-1;return r[o]}const ud={type:"spring",stiffness:500,damping:25,restSpeed:10},dd=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),hd={type:"keyframes",duration:.8},fd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},md=(t,{keyframes:e})=>e.length>2?hd:$e.has(t)?t.startsWith("scale")?dd(e[1]):ud:fd;function pd({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 yr=(t,e,n,s={},r,o)=>i=>{const a=sr(s,t)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-Lt(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};pd(a)||Object.assign(l,md(t,l)),l.duration&&(l.duration=Lt(l.duration)),l.repeatDelay&&(l.repeatDelay=Lt(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(As(l),l.delay===0&&(h=!0)),(qt.instantAnimations||qt.skipAnimations)&&(h=!0,As(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&e.get()!==void 0){const f=ld(l.keyframes,a);if(f!==void 0){st.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new er(l):new Il(l)};function gd({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,s}function la(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&&gd(u,l))continue;const g={delay:n,...sr(o||{},l)},x=h.get();if(x!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===x&&!g.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=ca(t);if(y){const v=window.MotionHandoffAnimation(y,l,st);v!==null&&(g.startTime=v,b=!0)}}Ds(t,l),h.start(yr(l,h,f,t.shouldReduceMotion&&Mo.has(l)?{type:!1}:g,t,b));const j=h.animation;j&&c.push(j)}return i&&Promise.all(c).then(()=>{st.update(()=>{i&&od(t,i)})}),c}function ua(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 Ns(t,e,n={}){const s=Ve(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(la(t,s,n)):()=>Promise.resolve(),i=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return yd(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 yd(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(Ns(c,e,{...i,delay:n+(typeof s=="function"?0:s)+ua(t.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(a)}function xd(t,e,n={}){t.notify("AnimationStart",e);let s;if(Array.isArray(e)){const r=e.map(o=>Ns(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Ns(t,e,n);else{const r=typeof e=="function"?Ve(t,e,n.custom):e;s=Promise.all(la(t,r,n))}return s.then(()=>{t.notify("AnimationComplete",e)})}function da(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 vd=ur.length;function ha(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?ha(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<vd;n++){const s=ur[n],r=t.props[s];(an(r)||r===!1)&&(e[s]=r)}return e}const bd=[...lr].reverse(),wd=lr.length;function Td(t){return e=>Promise.all(e.map(({animation:n,options:s})=>xd(t,n,s)))}function Sd(t){let e=Td(t),n=ci(),s=!0;const r=c=>(u,l)=>{const h=Ve(t,l,c==="exit"?t.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...x}=h;u={...u,...x,...g}}return u};function o(c){e=c(t)}function i(c){const{props:u}=t,l=ha(t.parent)||{},h=[],f=new Set;let g={},x=1/0;for(let j=0;j<wd;j++){const y=bd[j],v=n[y],T=u[y]!==void 0?u[y]:l[y],S=an(T),E=y===c?v.isActive:null;E===!1&&(x=j);let R=T===l[y]&&T!==u[y]&&S;if(R&&s&&t.manuallyAnimateOnMount&&(R=!1),v.protectedKeys={...g},!v.isActive&&E===null||!T&&!v.prevProp||zn(T)||typeof T=="boolean")continue;const C=Ad(v.prevProp,T);let k=C||y===c&&v.isActive&&!R&&S||j>x&&S,W=!1;const O=Array.isArray(T)?T:[T];let et=O.reduce(r(y),{});E===!1&&(et={});const{prevResolvedValues:Y={}}=v,ct={...Y,...et},yt=ot=>{k=!0,f.has(ot)&&(W=!0,f.delete(ot)),v.needsAnimating[ot]=!0;const lt=t.getValue(ot);lt&&(lt.liveStyle=!1)};for(const ot in ct){const lt=et[ot],tt=Y[ot];if(g.hasOwnProperty(ot))continue;let ht=!1;Es(lt)&&Es(tt)?ht=!da(lt,tt):ht=lt!==tt,ht?lt!=null?yt(ot):f.add(ot):lt!==void 0&&f.has(ot)?yt(ot):v.protectedKeys[ot]=!0}v.prevProp=T,v.prevResolvedValues=et,v.isActive&&(g={...g,...et}),s&&t.blockInitialAnimation&&(k=!1);const dt=R&&C;k&&(!dt||W)&&h.push(...O.map(ot=>{const lt={type:y};if(typeof ot=="string"&&s&&!dt&&t.manuallyAnimateOnMount&&t.parent){const{parent:tt}=t,ht=Ve(tt,ot);if(tt.enteringChildren&&ht){const{delayChildren:oe}=ht.transition||{};lt.delay=ua(tt.enteringChildren,t,oe)}}return{animation:ot,options:lt}}))}if(f.size){const j={};if(typeof u.initial!="boolean"){const y=Ve(t,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(j.transition=y.transition)}f.forEach(y=>{const v=t.getBaseTarget(y),T=t.getValue(y);T&&(T.liveStyle=!0),j[y]=v??null}),h.push({animation:j})}let b=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(b=!1),s=!1,b?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=ci()}}}function Ad(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!da(e,t):!1}function me(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ci(){return{animate:me(!0),whileInView:me(),whileHover:me(),whileTap:me(),whileDrag:me(),whileFocus:me(),exit:me()}}class ie{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Cd extends ie{constructor(e){super(e),e.animationState||(e.animationState=Sd(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();zn(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 Pd=0;class jd extends ie{constructor(){super(...arguments),this.id=Pd++}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 fa={animation:{Feature:Cd},exit:{Feature:jd}};function ln(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function fn(t){return{point:{x:t.pageX,y:t.pageY}}}const kd=t=>e=>or(e)&&t(e,fn(e));function Ze(t,e,n,s){return ln(t,e,kd(n),s)}const ma=1e-4,Md=1-ma,Ed=1+ma,pa=.01,Dd=0-pa,Nd=0+pa;function vt(t){return t.max-t.min}function Vd(t,e,n){return Math.abs(t-e)<=n}function li(t,e,n,s=.5){t.origin=s,t.originPoint=it(e.min,e.max,t.origin),t.scale=vt(n)/vt(e),t.translate=it(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Md&&t.scale<=Ed||isNaN(t.scale))&&(t.scale=1),(t.translate>=Dd&&t.translate<=Nd||isNaN(t.translate))&&(t.translate=0)}function Qe(t,e,n,s){li(t.x,e.x,n.x,s?s.originX:void 0),li(t.y,e.y,n.y,s?s.originY:void 0)}function ui(t,e,n){t.min=n.min+e.min,t.max=t.min+vt(e)}function Rd(t,e,n){ui(t.x,e.x,n.x),ui(t.y,e.y,n.y)}function di(t,e,n){t.min=e.min-n.min,t.max=t.min+vt(e)}function tn(t,e,n){di(t.x,e.x,n.x),di(t.y,e.y,n.y)}function Et(t){return[t("x"),t("y")]}const ga=({current:t})=>t?t.ownerDocument.defaultView:null,hi=(t,e)=>Math.abs(t-e);function Id(t,e){const n=hi(t.x,e.x),s=hi(t.y,e.y);return Math.sqrt(n**2+s**2)}class ya{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=is(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,x=Id(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!x)return;const{point:b}=f,{timestamp:j}=pt;this.history.push({...b,timestamp:j});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=rs(g,this.transformPagePoint),st.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:x,onSessionEnd:b,resumeAnimation:j}=this.handlers;if(this.dragSnapToOrigin&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=is(f.type==="pointercancel"?this.lastMoveEventInfo:rs(g,this.transformPagePoint),this.history);this.startEvent&&x&&x(f,y),b&&b(f,y)},!or(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=fn(e),c=rs(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=pt;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(e,is(c,this.history)),this.removeListeners=un(Ze(this.contextWindow,"pointermove",this.handlePointerMove),Ze(this.contextWindow,"pointerup",this.handlePointerUp),Ze(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),se(this.updatePoint)}}function rs(t,e){return e?{point:e(t.point)}:t}function fi(t,e){return{x:t.x-e.x,y:t.y-e.y}}function is({point:t},e){return{point:t,delta:fi(t,xa(e)),offset:fi(t,Od(e)),velocity:Ld(e,.1)}}function Od(t){return t[0]}function xa(t){return t[t.length-1]}function Ld(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,s=null;const r=xa(t);for(;n>=0&&(s=t[n],!(r.timestamp-s.timestamp>Lt(e)));)n--;if(!s)return{x:0,y:0};const o=Dt(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 Fd(t,{min:e,max:n},s){return e!==void 0&&t<e?t=s?it(e,t,s.min):Math.max(t,e):n!==void 0&&t>n&&(t=s?it(n,t,s.max):Math.min(t,n)),t}function mi(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 $d(t,{top:e,left:n,bottom:s,right:r}){return{x:mi(t.x,n,r),y:mi(t.y,e,s)}}function pi(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 Bd(t,e){return{x:pi(t.x,e.x),y:pi(t.y,e.y)}}function zd(t,e){let n=.5;const s=vt(t),r=vt(e);return r>s?n=sn(e.min,e.max-s,t.min):s>r&&(n=sn(t.min,t.max-r,e.min)),Wt(0,1,n)}function Ud(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 Vs=.35;function _d(t=Vs){return t===!1?t=0:t===!0&&(t=Vs),{x:gi(t,"left","right"),y:gi(t,"top","bottom")}}function gi(t,e,n){return{min:yi(t,e),max:yi(t,n)}}function yi(t,e){return typeof t=="number"?t:t[e]||0}const Wd=new WeakMap;class Kd{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=at(),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(fn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:x,onDragStart:b}=this.getProps();if(g&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Zl(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),Et(y=>{let v=this.getAxisMotionValue(y).get()||0;if(Ut.test(v)){const{projection:T}=this.visualElement;if(T&&T.layout){const S=T.layout.layoutBox[y];S&&(v=vt(S)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&st.postRender(()=>b(h,f)),Ds(this.visualElement,"transform");const{animationState:j}=this.visualElement;j&&j.setActive("whileDrag",!0)},a=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:x,onDirectionLock:b,onDrag:j}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(x&&this.currentDirection===null){this.currentDirection=qd(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),j&&j(h,f)},c=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f,this.stop(h,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Et(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new ya(e,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:ga(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&&st.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||!Cn(e,r,this.currentDirection))return;const o=this.getAxisMotionValue(e);let i=this.originPoint[e]+s[e];this.constraints&&this.constraints[e]&&(i=Fd(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&&ke(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&s?this.constraints=$d(s.layoutBox,e):this.constraints=!1,this.elastic=_d(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Et(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Ud(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!ke(e))return!1;const s=e.current;Kt(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=Gu(s,r.root,this.visualElement.getTransformPagePoint());let i=Bd(r.layout.layoutBox,o);if(n){const a=n(qu(i));this.hasMutatedConstraints=!!a,a&&(i=Qo(a))}return i}startAnimation(e){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Et(l=>{if(!Cn(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,x={type:"inertia",velocity:s?e[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,x)});return Promise.all(u).then(a)}startAxisValueAnimation(e,n){const s=this.getAxisMotionValue(e);return Ds(this.visualElement,e),s.start(yr(e,s,0,n,this.visualElement,!1))}stopAnimation(){Et(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Et(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){Et(n=>{const{drag:s}=this.getProps();if(!Cn(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]-it(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!ke(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Et(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=zd({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(),Et(i=>{if(!Cn(i,e,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(it(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Wd.set(this.visualElement,this);const e=this.visualElement.current,n=Ze(e,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();ke(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()),st.read(s);const i=ln(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Et(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=Vs,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Cn(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function qd(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Hd extends ie{constructor(e){super(e),this.removeGroupControls=Nt,this.removeListeners=Nt,this.controls=new Kd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Nt}unmount(){this.removeGroupControls(),this.removeListeners()}}const xi=t=>(e,n)=>{t&&st.postRender(()=>t(e,n))};class Xd extends ie{constructor(){super(...arguments),this.removePointerDownListener=Nt}onPointerDown(e){this.session=new ya(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:ga(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:xi(e),onStart:xi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&st.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Ze(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 Dn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function vi(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Ge={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(L.test(t))t=parseFloat(t);else return t;const n=vi(t,e.target.x),s=vi(t,e.target.y);return`${n}% ${s}%`}},Gd={correct:(t,{treeScale:e,projectionDelta:n})=>{const s=t,r=re.parse(t);if(r.length>5)return s;const o=re.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=it(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 os=!1;class Yd extends m.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=e;bu(Jd),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),os&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Dn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,os=!0,r||e.layoutDependency!==n||n===void 0||e.isPresent!==o?i.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?i.promote():i.relegate()||st.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ir.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=e;os=!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 va(t){const[e,n]=Bo(),s=m.useContext(Ls);return d.jsx(Yd,{...t,layoutGroup:s,switchLayoutGroup:m.useContext(Jo),isPresent:e,safeToRemove:n})}const Jd={borderRadius:{...Ge,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Ge,borderTopRightRadius:Ge,borderBottomLeftRadius:Ge,borderBottomRightRadius:Ge,boxShadow:Gd};function Zd(t,e,n){const s=gt(t)?t:Re(t);return s.start(yr("",s,e,n)),s.animation}const Qd=(t,e)=>t.depth-e.depth;class th{constructor(){this.children=[],this.isDirty=!1}add(e){Bs(this.children,e),this.isDirty=!0}remove(e){zs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Qd),this.isDirty=!1,this.children.forEach(e)}}function eh(t,e){const n=At.now(),s=({timestamp:r})=>{const o=r-n;o>=e&&(se(s),t(o-e))};return st.setup(s,!0),()=>se(s)}const ba=["TopLeft","TopRight","BottomLeft","BottomRight"],nh=ba.length,bi=t=>typeof t=="string"?parseFloat(t):t,wi=t=>typeof t=="number"||L.test(t);function sh(t,e,n,s,r,o){r?(t.opacity=it(0,n.opacity??1,rh(s)),t.opacityExit=it(e.opacity??1,0,ih(s))):o&&(t.opacity=it(e.opacity??1,n.opacity??1,s));for(let i=0;i<nh;i++){const a=`border${ba[i]}Radius`;let c=Ti(e,a),u=Ti(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||wi(c)===wi(u)?(t[a]=Math.max(it(bi(c),bi(u),s),0),(Ut.test(u)||Ut.test(c))&&(t[a]+="%")):t[a]=u}(e.rotate||n.rotate)&&(t.rotate=it(e.rotate||0,n.rotate||0,s))}function Ti(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const rh=wa(0,.5,io),ih=wa(.5,.95,Nt);function wa(t,e,n){return s=>s<t?0:s>e?1:n(sn(t,e,s))}function Si(t,e){t.min=e.min,t.max=e.max}function Mt(t,e){Si(t.x,e.x),Si(t.y,e.y)}function Ai(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Ci(t,e,n,s,r){return t-=e,t=Fn(t,1/n,s),r!==void 0&&(t=Fn(t,1/r,s)),t}function oh(t,e=0,n=1,s=.5,r,o=t,i=t){if(Ut.test(e)&&(e=parseFloat(e),e=it(i.min,i.max,e/100)-i.min),typeof e!="number")return;let a=it(o.min,o.max,s);t===o&&(a-=e),t.min=Ci(t.min,e,n,a,r),t.max=Ci(t.max,e,n,a,r)}function Pi(t,e,[n,s,r],o,i){oh(t,e[n],e[s],e[r],e.scale,o,i)}const ah=["x","scaleX","originX"],ch=["y","scaleY","originY"];function ji(t,e,n,s){Pi(t.x,e,ah,n?n.x:void 0,s?s.x:void 0),Pi(t.y,e,ch,n?n.y:void 0,s?s.y:void 0)}function ki(t){return t.translate===0&&t.scale===1}function Ta(t){return ki(t.x)&&ki(t.y)}function Mi(t,e){return t.min===e.min&&t.max===e.max}function lh(t,e){return Mi(t.x,e.x)&&Mi(t.y,e.y)}function Ei(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Sa(t,e){return Ei(t.x,e.x)&&Ei(t.y,e.y)}function Di(t){return vt(t.x)/vt(t.y)}function Ni(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class uh{constructor(){this.members=[]}add(e){Bs(this.members,e),e.scheduleRender()}remove(e){if(zs(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 dh(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:x}=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) `),x&&(s+=`skewY(${x}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 as=["","X","Y","Z"],hh=1e3;let fh=0;function cs(t,e,n,s){const{latestValues:r}=e;r[t]&&(n[t]=r[t],e.setStaticValue(t,0),s&&(s[t]=0))}function Aa(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=ca(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",st,!(r||o))}const{parent:s}=t;s&&!s.hasCheckedOptimisedAppear&&Aa(s)}function Ca({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=e?.()){this.id=fh++,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(gh),this.nodes.forEach(bh),this.nodes.forEach(wh),this.nodes.forEach(yh)},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 th)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new _s),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=$o(i)&&!ru(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;st.read(()=>{h=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=eh(f,250),Dn.hasAnimatedSinceResize&&(Dn.hasAnimatedSinceResize=!1,this.nodes.forEach(Ii)))})}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 x=this.options.transition||u.getDefaultTransition()||Ph,{onLayoutAnimationStart:b,onLayoutAnimationComplete:j}=u.getProps(),y=!this.targetLayout||!Sa(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 T={...sr(x,"layout"),onPlay:b,onComplete:j};(u.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(l,v)}else h||Ii(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(),se(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(Th),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&&Aa(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(Vi);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ri);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(vh),this.nodes.forEach(mh),this.nodes.forEach(ph)):this.nodes.forEach(Ri),this.clearAllSnapshots();const a=At.now();pt.delta=Wt(0,1e3/60,a-pt.timestamp),pt.timestamp=a,pt.isProcessing=!0,Yn.update.process(pt),Yn.preRender.process(pt),Yn.render.process(pt),pt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ir.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(xh),this.sharedNodes.forEach(Sh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,st.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){st.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!vt(this.snapshot.measuredBox.x)&&!vt(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=at(),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&&!Ta(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||ge(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)),jh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return at();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(kh))){const{scroll:u}=this.root;u&&(Me(a.x,u.offset.x),Me(a.y,u.offset.y))}return a}removeElementScroll(i){const a=at();if(Mt(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&&Mt(a,i),Me(a.x,l.offset.x),Me(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=at();Mt(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&&Ee(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),ge(l.latestValues)&&Ee(c,l.latestValues)}return ge(this.latestValues)&&Ee(c,this.latestValues),c}removeTransform(i){const a=at();Mt(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!ge(u.latestValues))continue;js(u.latestValues)&&u.updateSnapshot();const l=at(),h=u.measurePageBox();Mt(l,h),ji(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return ge(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!==pt.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=pt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=at(),this.relativeTargetOrigin=at(),tn(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Mt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=at(),this.targetWithTransforms=at()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Rd(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Mt(this.target,this.layout.layoutBox),ea(this.target,this.targetDelta)):Mt(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=at(),this.relativeTargetOrigin=at(),tn(this.relativeTargetOrigin,this.target,f.target),Mt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||js(this.parent.latestValues)||ta(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===pt.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;Mt(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;Xu(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=at());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ai(this.prevProjectionDelta.x,this.projectionDelta.x),Ai(this.prevProjectionDelta.y,this.projectionDelta.y)),Qe(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Ni(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ni(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=De(),this.projectionDelta=De(),this.projectionDeltaWithTransform=De()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=De();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=at(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,b=g!==x,j=this.getStack(),y=!j||j.members.length<=1,v=!!(b&&!y&&this.options.crossfade===!0&&!this.path.some(Ch));this.animationProgress=0;let T;this.mixTargetDelta=S=>{const E=S/1e3;Oi(h.x,i.x,E),Oi(h.y,i.y,E),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(tn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Ah(this.relativeTarget,this.relativeTargetOrigin,f,E),T&&lh(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=at()),Mt(T,this.relativeTarget)),b&&(this.animationValues=l,sh(l,u,this.latestValues,E,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(se(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=st.update(()=>{Dn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Re(0)),this.currentAnimation=Zd(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(hh),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&&Pa(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||at();const h=vt(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=vt(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Mt(a,c),Ee(a,l),Qe(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new uh),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&&cs("z",i,u,this.animationValues);for(let l=0;l<as.length;l++)cs(`rotate${as[l]}`,i,u,this.animationValues),cs(`skew${as[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=Mn(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=Mn(a?.pointerEvents)||""),this.hasProjected&&!ge(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=dh(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 x in cn){if(l[x]===void 0)continue;const{correct:b,applyTo:j,isCSSVariable:y}=cn[x],v=h==="none"?l[x]:b(l[x],u);if(j){const T=j.length;for(let S=0;S<T;S++)i[j[S]]=v}else y?this.options.visualElement.renderState.vars[x]=v:i[x]=v}this.options.layoutId&&(i.pointerEvents=u===this?Mn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Vi),this.root.sharedNodes.clear()}}}function mh(t){t.updateLayout()}function ph(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"?Et(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=vt(h);h.min=n[l].min,h.max=h.min+f}):Pa(r,e.layoutBox,n)&&Et(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=vt(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=De();Qe(i,n,e.layoutBox);const a=De();o?Qe(a,t.applyTransform(s,!0),e.measuredBox):Qe(a,n,e.layoutBox);const c=!Ta(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=at();tn(g,e.layoutBox,h.layoutBox);const x=at();tn(x,n,f.layoutBox),Sa(g,x)||(u=!0),l.options.layoutRoot&&(t.relativeTarget=x,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 gh(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 yh(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function xh(t){t.clearSnapshot()}function Vi(t){t.clearMeasurements()}function Ri(t){t.isLayoutDirty=!1}function vh(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Ii(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function bh(t){t.resolveTargetDelta()}function wh(t){t.calcProjection()}function Th(t){t.resetSkewAndRotation()}function Sh(t){t.removeLeadSnapshot()}function Oi(t,e,n){t.translate=it(e.translate,0,n),t.scale=it(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Li(t,e,n,s){t.min=it(e.min,n.min,s),t.max=it(e.max,n.max,s)}function Ah(t,e,n,s){Li(t.x,e.x,n.x,s),Li(t.y,e.y,n.y,s)}function Ch(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Ph={duration:.45,ease:[.4,0,.1,1]},Fi=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),$i=Fi("applewebkit/")&&!Fi("chrome/")?Math.round:Nt;function Bi(t){t.min=$i(t.min),t.max=$i(t.max)}function jh(t){Bi(t.x),Bi(t.y)}function Pa(t,e,n){return t==="position"||t==="preserve-aspect"&&!Vd(Di(e),Di(n),.2)}function kh(t){return t!==t.root&&t.scroll?.wasRoot}const Mh=Ca({attachResizeListener:(t,e)=>ln(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ls={current:void 0},ja=Ca({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ls.current){const t=new Mh({});t.mount(window),t.setOptions({layoutScroll:!0}),ls.current=t}return ls.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Eh={pan:{Feature:Xd},drag:{Feature:Hd,ProjectionNode:ja,MeasureLayout:va}};function zi(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&&st.postRender(()=>o(e,fn(e)))}class Dh extends ie{mount(){const{current:e}=this.node;e&&(this.unmount=Ql(e,(n,s)=>(zi(this.node,s,"Start"),r=>zi(this.node,r,"End"))))}unmount(){}}class Nh extends ie{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=un(ln(this.node.current,"focus",()=>this.onFocus()),ln(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ui(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&&st.postRender(()=>o(e,fn(e)))}class Vh extends ie{mount(){const{current:e}=this.node;e&&(this.unmount=su(e,(n,s)=>(Ui(this.node,s,"Start"),(r,{success:o})=>Ui(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Rs=new WeakMap,us=new WeakMap,Rh=t=>{const e=Rs.get(t.target);e&&e(t)},Ih=t=>{t.forEach(Rh)};function Oh({root:t,...e}){const n=t||document;us.has(n)||us.set(n,{});const s=us.get(n),r=JSON.stringify(e);return s[r]||(s[r]=new IntersectionObserver(Ih,{root:t,...e})),s[r]}function Lh(t,e,n){const s=Oh(e);return Rs.set(t,n),s.observe(t),()=>{Rs.delete(t),s.unobserve(t)}}const Fh={some:0,all:1};class $h extends ie{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:Fh[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 Lh(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(Bh(e,n))&&this.startObserver()}unmount(){}}function Bh({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const ka={inView:{Feature:$h},tap:{Feature:Vh},focus:{Feature:Nh},hover:{Feature:Dh}},zh={layout:{ProjectionNode:ja,MeasureLayout:va}},Uh={...fa,...ka,...Eh,...zh},_h=Ku(Uh,aa),Wh={renderer:aa,...fa,...ka};function Ma(t,e){return En(t,e)}const Pn=Ma("div"),Kh=Ma("p"),zt=Symbol.for("@arcteninc/core:originalName");function qh(t,e){return t[zt]=e,t}function Hh(t,e,n,s){if(typeof t!="function")return null;const r=t[zt];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[zt]=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[zt]=i.name,{fn:t,meta:i}}else if(i=Object.values(e).find(c=>!n.has(c.name)),i)return t[zt]=i.name,{fn:t,meta:i};return null}function Ea(t,e){let n,s;if(!e)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{S.contains(x)&&S.removeChild(x)}},[t]),h.jsx(uu,{isPresent:t,childRef:o,sizeRef:i,children:Re.cloneElement(e,{ref:c})})}const hu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=$s(fu),l=m.useId();let f=!0,d=m.useMemo(()=>(f=!1,{id:l,initial:t,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const b of u.values())if(!b)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&f&&(d={...d}),m.useMemo(()=>{u.forEach((g,b)=>u.set(b,!1))},[n]),Re.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=h.jsx(du,{isPresent:n,anchorX:a,root:c,children:e})),h.jsx(Bn.Provider,{value:d,children:e})};function fu(){return new Map}function zo(e=!0){const t=m.useContext(Bn);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=m.useId();m.useEffect(()=>{if(e)return r(o)},[e]);const i=m.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const Pn=e=>e.key||"";function Jr(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const mu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=zo(i),f=m.useMemo(()=>Jr(e),[e]),d=i&&!u?[]:f.map(Pn),g=m.useRef(!0),b=m.useRef(f),x=$s(()=>new Map),[S,T]=m.useState(f),[v,y]=m.useState(f);Xi(()=>{g.current=!1,b.current=f;for(let k=0;k<v.length;k++){const P=Pn(v[k]);d.includes(P)?x.delete(P):x.get(P)!==!0&&x.set(P,!1)}},[v,d.length,d.join("-")]);const N=[];if(f!==S){let k=[...f];for(let P=0;P<v.length;P++){const j=v[P],q=Pn(j);d.includes(q)||(k.splice(P,0,j),N.push(j))}return o==="wait"&&N.length&&(k=N),y(Jr(k)),T(f),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:M}=m.useContext(Fs);return h.jsx(h.Fragment,{children:v.map(k=>{const P=Pn(k),j=i&&!u?!1:f===v||d.includes(P),q=()=>{if(x.has(P))x.set(P,!0);else return;let L=!0;x.forEach(Y=>{Y||(L=!1)}),L&&(M?.(),y(b.current),i&&l?.(),s&&s())};return h.jsx(hu,{isPresent:j,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:j?void 0:q,anchorX:a,children:k},P)})})},lr=m.createContext({strict:!1}),Zr={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"]},Ft={};for(const e in Zr)Ft[e]={isEnabled:t=>Zr[e].some(n=>!!t[n])};function js(e){for(const t in e)Ft[t]={...Ft[t],...e[t]}}function pu({children:e,features:t,strict:n=!1}){const[,s]=m.useState(!ss(t)),r=m.useRef(void 0);if(!ss(t)){const{renderer:o,...i}=t;r.current=o,js(i)}return m.useEffect(()=>{ss(t)&&t().then(({renderer:o,...i})=>{js(i),r.current=o,s(!0)})},[]),h.jsx(lr.Provider,{value:{renderer:r.current,strict:n},children:e})}function ss(e){return typeof e=="function"}const gu=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 Fn(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||gu.has(e)}let Uo=e=>!Fn(e);function yu(e){typeof e=="function"&&(Uo=t=>t.startsWith("on")?!Fn(t):e(t))}try{yu(require("@emotion/is-prop-valid").default)}catch{}function xu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Uo(r)||n===!0&&Fn(r)||!t&&!Fn(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const zn=m.createContext({});function Un(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function ln(e){return typeof e=="string"||Array.isArray(e)}const ur=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],dr=["initial",...ur];function _n(e){return Un(e.animate)||dr.some(t=>ln(e[t]))}function _o(e){return!!(_n(e)||e.variants)}function vu(e,t){if(_n(e)){const{initial:n,animate:s}=e;return{initial:n===!1||ln(n)?n:void 0,animate:ln(s)?s:void 0}}return e.inherit!==!1?t:{}}function bu(e){const{initial:t,animate:n}=vu(e,m.useContext(zn));return m.useMemo(()=>({initial:t,animate:n}),[Qr(t),Qr(n)])}function Qr(e){return Array.isArray(e)?e.join(" "):e}const un={};function wu(e){for(const t in e)un[t]=e[t],Gs(t)&&(un[t].isCSSVariable=!0)}function Wo(e,{layout:t,layoutId:n}){return Ut.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!un[e]||e==="opacity")}const Tu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Su=zt.length;function Au(e,t,n){let s="",r=!0;for(let o=0;o<Su;o++){const i=zt[o],a=e[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=Io(a,ir[i]);if(!c){r=!1;const l=Tu[i]||i;s+=`${l}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function hr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const c in t){const u=t[c];if(Ut.has(c)){i=!0;continue}else if(Gs(c)){r[c]=u;continue}else{const l=Io(u,ir[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(t.transform||(i||n?s.transform=Au(t,e.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 fr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ko(e,t,n){for(const s in t)!be(t[s])&&!Wo(s,n)&&(e[s]=t[s])}function Pu({transformTemplate:e},t){return m.useMemo(()=>{const n=fr();return hr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Cu(e,t){const n=e.style||{},s={};return Ko(s,n,e),Object.assign(s,Pu(e,t)),s}function ju(e,t){const n={},s=Cu(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 ku={offset:"stroke-dashoffset",array:"stroke-dasharray"},Mu={offset:"strokeDashoffset",array:"strokeDasharray"};function Eu(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?ku:Mu;e[o.offset]=F.transform(-s);const i=F.transform(t),a=F.transform(n);e[o.array]=`${i} ${a}`}function qo(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(hr(e,a,u),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:f,style:d}=e;f.transform&&(d.transform=f.transform,delete f.transform),(d.transform||f.transformOrigin)&&(d.transformOrigin=f.transformOrigin??"50% 50%",delete f.transformOrigin),d.transform&&(d.transformBox=l?.transformBox??"fill-box",delete f.transformBox),t!==void 0&&(f.x=t),n!==void 0&&(f.y=n),s!==void 0&&(f.scale=s),r!==void 0&&Eu(f,r,o,i,!1)}const Ho=()=>({...fr(),attrs:{}}),Go=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Du(e,t,n,s){const r=m.useMemo(()=>{const o=Ho();return qo(o,t,Go(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ko(o,e.style,e),r.style={...o,...r.style}}return r}const Nu=["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 mr(e){return typeof e!="string"||e.includes("-")?!1:!!(Nu.indexOf(e)>-1||/[A-Z]/u.test(e))}function Vu(e,t,n,{latestValues:s},r,o=!1){const a=(mr(e)?Du:ju)(t,s,r,e),c=xu(t,typeof e=="string",o),u=e!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=t,f=m.useMemo(()=>be(l)?l.get():l,[l]);return m.createElement(e,{...u,children:f})}function ei(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function pr(e,t,n,s){if(typeof t=="function"){const[r,o]=ei(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]=ei(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function En(e){return be(e)?e.get():e}function Ru({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Iu(n,s,r,e),renderState:t()}}function Iu(e,t,n,s){const r={},o=s(e,{});for(const d in o)r[d]=En(o[d]);let{initial:i,animate:a}=e;const c=_n(e),u=_o(e);t&&u&&!c&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const f=l?a:i;if(f&&typeof f!="boolean"&&!Un(f)){const d=Array.isArray(f)?f:[f];for(let g=0;g<d.length;g++){const b=pr(e,d[g]);if(b){const{transitionEnd:x,transition:S,...T}=b;for(const v in T){let y=T[v];if(Array.isArray(y)){const N=l?y.length-1:0;y=y[N]}y!==null&&(r[v]=y)}for(const v in x)r[v]=x[v]}}}return r}const Xo=e=>(t,n)=>{const s=m.useContext(zn),r=m.useContext(Bn),o=()=>Ru(e,t,s,r);return n?o():$s(o)};function gr(e,t,n){const{style:s}=e,r={};for(const o in s)(be(s[o])||t.style&&be(t.style[o])||Wo(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Ou=Xo({scrapeMotionValuesFromProps:gr,createRenderState:fr});function Yo(e,t,n){const s=gr(e,t,n);for(const r in e)if(be(e[r])||be(t[r])){const o=zt.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Lu=Xo({scrapeMotionValuesFromProps:Yo,createRenderState:Ho}),Fu=Symbol.for("motionComponentSymbol");function Dt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function $u(e,t,n){return m.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Dt(n)&&(n.current=s))},[t])}const yr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bu="framerAppearId",Jo="data-"+yr(Bu),Zo=m.createContext({});function zu(e,t,n,s,r){const{visualElement:o}=m.useContext(zn),i=m.useContext(lr),a=m.useContext(Bn),c=m.useContext(cr).reducedMotion,u=m.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:c}));const l=u.current,f=m.useContext(Zo);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Uu(u.current,n,r,f);const d=m.useRef(!1);m.useInsertionEffect(()=>{l&&d.current&&l.update(n,a)});const g=n[Jo],b=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return Xi(()=>{l&&(d.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),b.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!b.current&&l.animationState&&l.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),b.current=!1),l.enteringChildren=void 0)}),l}function Uu(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Qo(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Dt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function Qo(e){if(e)return e.options.allowProjection!==!1?e.projection:Qo(e.parent)}function Dn(e,{forwardMotionProps:t=!1}={},n,s){n&&js(n);const r=mr(e)?Lu:Ou;function o(a,c){let u;const l={...m.useContext(cr),...a,layoutId:_u(a)},{isStatic:f}=l,d=bu(a),g=r(a,f);if(!f&&Bs){Wu(l,n);const b=Ku(l);u=b.MeasureLayout,d.visualElement=zu(e,g,l,s,b.ProjectionNode)}return h.jsxs(zn.Provider,{value:d,children:[u&&d.visualElement?h.jsx(u,{visualElement:d.visualElement,...l}):null,Vu(e,a,$u(g,d.visualElement,c),g,f,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=m.forwardRef(o);return i[Fu]=e,i}function _u({layoutId:e}){const t=m.useContext(Fs).id;return t&&e!==void 0?t+"-"+e:e}function Wu(e,t){const n=m.useContext(lr).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?$t(!1,s,"lazy-strict-mode"):Ke(!1,s,"lazy-strict-mode")}}function Ku(e){const{drag:t,layout:n}=Ft;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function qu(e,t){if(typeof Proxy>"u")return Dn;const n=new Map,s=(o,i)=>Dn(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Ks(!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,Dn(i,void 0,e,t)),n.get(i))})}function ea({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Hu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Gu(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 rs(e){return e===void 0||e===1}function ks({scale:e,scaleX:t,scaleY:n}){return!rs(e)||!rs(t)||!rs(n)}function xt(e){return ks(e)||ta(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function ta(e){return ti(e.x)||ti(e.y)}function ti(e){return e&&e!=="0%"}function $n(e,t,n){const s=e-n,r=t*s;return n+r}function ni(e,t,n,s,r){return r!==void 0&&(e=$n(e,r,s)),$n(e,n,s)+t}function Ms(e,t=0,n=1,s,r){e.min=ni(e.min,t,n,s,r),e.max=ni(e.max,t,n,s,r)}function na(e,{x:t,y:n}){Ms(e.x,t.translate,t.scale,t.originPoint),Ms(e.y,n.translate,n.scale,n.originPoint)}const si=.999999999999,ri=1.0000000000001;function Xu(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:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Vt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,na(e,i)),s&&xt(o.latestValues)&&Vt(e,o.latestValues))}t.x<ri&&t.x>si&&(t.x=1),t.y<ri&&t.y>si&&(t.y=1)}function Nt(e,t){e.min=e.min+t,e.max=e.max+t}function ii(e,t,n,s,r=.5){const o=oe(e.min,e.max,r);Ms(e,t,n,o,s)}function Vt(e,t){ii(e.x,t.x,t.scaleX,t.scale,t.originX),ii(e.y,t.y,t.scaleY,t.scale,t.originY)}function sa(e,t){return ea(Gu(e.getBoundingClientRect(),t))}function Yu(e,t,n){const s=sa(e,n),{scroll:r}=t;return r&&(Nt(s.x,r.offset.x),Nt(s.y,r.offset.y)),s}const oi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Rt=()=>({x:oi(),y:oi()}),ai=()=>({min:0,max:0}),ue=()=>({x:ai(),y:ai()}),Es={current:null},ra={current:!1};function Ju(){if(ra.current=!0,!!Bs)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Es.current=e.matches;e.addEventListener("change",t),t()}else Es.current=!1}const Zu=new WeakMap;function Qu(e,t,n){for(const s in t){const r=t[s],o=n[s];if(be(r))e.addValue(s,r);else if(be(o))e.addValue(s,Lt(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,Lt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const ci=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class ed{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=sr,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 d=Pe.now();this.renderScheduledAt<d&&(this.renderScheduledAt=d,ne.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=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=_n(n),this.isVariantNode=_o(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:l,...f}=this.scrapeMotionValuesFromProps(n,{},this);for(const d in f){const g=f[d];c[d]!==void 0&&be(g)&&g.set(c[d])}}mount(t){this.current=t,Zu.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)),ra.current||Ju(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Es.current,process.env.NODE_ENV!=="production"&&Ks(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(),ot(this.notifyUpdate),ot(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=Ut.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ne.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 Ft){const n=Ft[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):ue()}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<ci.length;s++){const r=ci[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=Qu(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=Lt(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"&&(Yi(s)||Zi(s))?s=parseFloat(s):!au(s)&&at.test(n)&&(s=Ro(t,n)),this.setBaseTarget(t,be(s)?s.get():s)),be(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=pr(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&&!be(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 Ws),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){or.render(this.render)}}class ia extends ed{constructor(){super(...arguments),this.KeyframeResolver=Xl}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;be(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function oa(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 td(e){return window.getComputedStyle(e)}class nd extends ia{constructor(){super(...arguments),this.type="html",this.renderInstance=oa}readValueFromInstance(t,n){if(Ut.has(n))return this.projection?.isProjecting?bs(n):fl(t,n);{const s=td(t),r=(Gs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return sa(t,n)}build(t,n,s){hr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return gr(t,n,s)}}const aa=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 sd(e,t,n,s){oa(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(aa.has(r)?r:yr(r),t.attrs[r])}class rd extends ia{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ue}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Ut.has(n)){const s=Vo(n);return s&&s.default||0}return n=aa.has(n)?n:yr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Yo(t,n,s)}build(t,n,s){qo(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){sd(t,n,s,r)}mount(t){this.isSVGTag=Go(t.tagName),super.mount(t)}}const ca=(e,t)=>mr(e)?new rd(t):new nd(t,{allowProjection:e!==m.Fragment});function Ot(e,t,n){const s=e.getProps();return pr(s,t,n!==void 0?n:s.custom,e)}const Ds=e=>Array.isArray(e);function id(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Lt(n))}function od(e){return Ds(e)?e[e.length-1]||0:e}function ad(e,t){const n=Ot(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=od(o[i]);id(e,i,a)}}function cd(e){return!!(be(e)&&e.add)}function Ns(e,t){const n=e.getValue("willChange");if(cd(n))return n.add(t);if(!n&&qe.WillChange){const s=new qe.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function la(e){return e.props[Jo]}const ld=e=>e!==null;function ud(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(ld),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const dd={type:"spring",stiffness:500,damping:25,restSpeed:10},hd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),fd={type:"keyframes",duration:.8},md={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},pd=(e,{keyframes:t})=>t.length>2?fd:Ut.has(e)?e.startsWith("scale")?hd(t[1]):dd:md;function gd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const xr=(e,t,n,s={},r,o)=>i=>{const a=rr(s,e)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-Ie(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:d=>{t.set(d),a.onUpdate&&a.onUpdate(d)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};gd(a)||Object.assign(l,pd(e,l)),l.duration&&(l.duration=Ie(l.duration)),l.repeatDelay&&(l.repeatDelay=Ie(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let f=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(Ps(l),l.delay===0&&(f=!0)),(qe.instantAnimations||qe.skipAnimations)&&(f=!0,Ps(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,f&&!o&&t.get()!==void 0){const d=ud(l.keyframes,a);if(d!==void 0){ne.update(()=>{l.onUpdate(d),l.onComplete()});return}}return a.isSync?new nr(l):new Ol(l)};function yd({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function ua(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const c=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const l in a){const f=e.getValue(l,e.latestValues[l]??null),d=a[l];if(d===void 0||u&&yd(u,l))continue;const g={delay:n,...rr(o||{},l)},b=f.get();if(b!==void 0&&!f.isAnimating&&!Array.isArray(d)&&d===b&&!g.velocity)continue;let x=!1;if(window.MotionHandoffAnimation){const T=la(e);if(T){const v=window.MotionHandoffAnimation(T,l,ne);v!==null&&(g.startTime=v,x=!0)}}Ns(e,l),f.start(xr(l,f,d,e.shouldReduceMotion&&Eo.has(l)?{type:!1}:g,e,x));const S=f.animation;S&&c.push(S)}return i&&Promise.all(c).then(()=>{ne.update(()=>{i&&ad(e,i)})}),c}function da(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,l)=>u.sortNodePosition(l)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Vs(e,t,n={}){const s=Ot(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(ua(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:f}=r;return xd(e,t,c,u,l,f,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 xd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(Vs(c,t,{...i,delay:n+(typeof s=="function"?0:s)+da(e.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function vd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>Vs(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=Vs(e,t,n);else{const r=typeof t=="function"?Ot(e,t,n.custom):t;s=Promise.all(ua(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function ha(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 bd=dr.length;function fa(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?fa(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<bd;n++){const s=dr[n],r=e.props[s];(ln(r)||r===!1)&&(t[s]=r)}return t}const wd=[...ur].reverse(),Td=ur.length;function Sd(e){return t=>Promise.all(t.map(({animation:n,options:s})=>vd(e,n,s)))}function Ad(e){let t=Sd(e),n=li(),s=!0;const r=c=>(u,l)=>{const f=Ot(e,l,c==="exit"?e.presenceContext?.custom:void 0);if(f){const{transition:d,transitionEnd:g,...b}=f;u={...u,...b,...g}}return u};function o(c){t=c(e)}function i(c){const{props:u}=e,l=fa(e.parent)||{},f=[],d=new Set;let g={},b=1/0;for(let S=0;S<Td;S++){const T=wd[S],v=n[T],y=u[T]!==void 0?u[T]:l[T],N=ln(y),M=T===c?v.isActive:null;M===!1&&(b=S);let k=y===l[T]&&y!==u[T]&&N;if(k&&s&&e.manuallyAnimateOnMount&&(k=!1),v.protectedKeys={...g},!v.isActive&&M===null||!y&&!v.prevProp||Un(y)||typeof y=="boolean")continue;const P=Pd(v.prevProp,y);let j=P||T===c&&v.isActive&&!k&&N||S>b&&N,q=!1;const L=Array.isArray(y)?y:[y];let Y=L.reduce(r(T),{});M===!1&&(Y={});const{prevResolvedValues:se={}}=v,de={...se,...Y},re=te=>{j=!0,d.has(te)&&(q=!0,d.delete(te)),v.needsAnimating[te]=!0;const le=e.getValue(te);le&&(le.liveStyle=!1)};for(const te in de){const le=Y[te],ae=se[te];if(g.hasOwnProperty(te))continue;let J=!1;Ds(le)&&Ds(ae)?J=!ha(le,ae):J=le!==ae,J?le!=null?re(te):d.add(te):le!==void 0&&d.has(te)?re(te):v.protectedKeys[te]=!0}v.prevProp=y,v.prevResolvedValues=Y,v.isActive&&(g={...g,...Y}),s&&e.blockInitialAnimation&&(j=!1);const pe=k&&P;j&&(!pe||q)&&f.push(...L.map(te=>{const le={type:T};if(typeof te=="string"&&s&&!pe&&e.manuallyAnimateOnMount&&e.parent){const{parent:ae}=e,J=Ot(ae,te);if(ae.enteringChildren&&J){const{delayChildren:He}=J.transition||{};le.delay=da(ae.enteringChildren,e,He)}}return{animation:te,options:le}}))}if(d.size){const S={};if(typeof u.initial!="boolean"){const T=Ot(e,Array.isArray(u.initial)?u.initial[0]:u.initial);T&&T.transition&&(S.transition=T.transition)}d.forEach(T=>{const v=e.getBaseTarget(T),y=e.getValue(T);y&&(y.liveStyle=!0),S[T]=v??null}),f.push({animation:S})}let x=!!f.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(x=!1),s=!1,x?t(f):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(f=>f.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const f in n)n[f].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=li()}}}function Pd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!ha(t,e):!1}function gt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function li(){return{animate:gt(!0),whileInView:gt(),whileHover:gt(),whileTap:gt(),whileDrag:gt(),whileFocus:gt(),exit:gt()}}class ct{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Cd extends ct{constructor(t){super(t),t.animationState||(t.animationState=Ad(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Un(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 jd=0;class kd extends ct{constructor(){super(...arguments),this.id=jd++}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 ma={animation:{Feature:Cd},exit:{Feature:kd}};function dn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function pn(e){return{point:{x:e.pageX,y:e.pageY}}}const Md=e=>t=>ar(t)&&e(t,pn(t));function en(e,t,n,s){return dn(e,t,Md(n),s)}const pa=1e-4,Ed=1-pa,Dd=1+pa,ga=.01,Nd=0-ga,Vd=0+ga;function we(e){return e.max-e.min}function Rd(e,t,n){return Math.abs(e-t)<=n}function ui(e,t,n,s=.5){e.origin=s,e.originPoint=oe(t.min,t.max,e.origin),e.scale=we(n)/we(t),e.translate=oe(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Ed&&e.scale<=Dd||isNaN(e.scale))&&(e.scale=1),(e.translate>=Nd&&e.translate<=Vd||isNaN(e.translate))&&(e.translate=0)}function tn(e,t,n,s){ui(e.x,t.x,n.x,s?s.originX:void 0),ui(e.y,t.y,n.y,s?s.originY:void 0)}function di(e,t,n){e.min=n.min+t.min,e.max=e.min+we(t)}function Id(e,t,n){di(e.x,t.x,n.x),di(e.y,t.y,n.y)}function hi(e,t,n){e.min=t.min-n.min,e.max=e.min+we(t)}function nn(e,t,n){hi(e.x,t.x,n.x),hi(e.y,t.y,n.y)}function ke(e){return[e("x"),e("y")]}const ya=({current:e})=>e?e.ownerDocument.defaultView:null,fi=(e,t)=>Math.abs(e-t);function Od(e,t){const n=fi(e.x,t.x),s=fi(e.y,t.y);return Math.sqrt(n**2+s**2)}class xa{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 d=os(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,b=Od(d.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!b)return;const{point:x}=d,{timestamp:S}=ye;this.history.push({...x,timestamp:S});const{onStart:T,onMove:v}=this.handlers;g||(T&&T(this.lastMoveEvent,d),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,d)},this.handlePointerMove=(d,g)=>{this.lastMoveEvent=d,this.lastMoveEventInfo=is(g,this.transformPagePoint),ne.update(this.updatePoint,!0)},this.handlePointerUp=(d,g)=>{this.end();const{onEnd:b,onSessionEnd:x,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const T=os(d.type==="pointercancel"?this.lastMoveEventInfo:is(g,this.transformPagePoint),this.history);this.startEvent&&b&&b(d,T),x&&x(d,T)},!ar(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=pn(t),c=is(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=ye;this.history=[{...u,timestamp:l}];const{onSessionStart:f}=n;f&&f(t,os(c,this.history)),this.removeListeners=hn(en(this.contextWindow,"pointermove",this.handlePointerMove),en(this.contextWindow,"pointerup",this.handlePointerUp),en(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),ot(this.updatePoint)}}function is(e,t){return t?{point:t(e.point)}:e}function mi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function os({point:e},t){return{point:e,delta:mi(e,va(t)),offset:mi(e,Ld(t)),velocity:Fd(t,.1)}}function Ld(e){return e[0]}function va(e){return e[e.length-1]}function Fd(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=va(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ie(t)));)n--;if(!s)return{x:0,y:0};const o=Me(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 $d(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?oe(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?oe(n,e,s.max):Math.min(e,n)),e}function pi(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 Bd(e,{top:t,left:n,bottom:s,right:r}){return{x:pi(e.x,n,r),y:pi(e.y,t,s)}}function gi(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 zd(e,t){return{x:gi(e.x,t.x),y:gi(e.y,t.y)}}function Ud(e,t){let n=.5;const s=we(e),r=we(t);return r>s?n=on(t.min,t.max-s,e.min):s>r&&(n=on(e.min,e.max-r,t.min)),We(0,1,n)}function _d(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 Rs=.35;function Wd(e=Rs){return e===!1?e=0:e===!0&&(e=Rs),{x:yi(e,"left","right"),y:yi(e,"top","bottom")}}function yi(e,t,n){return{min:xi(e,t),max:xi(e,n)}}function xi(e,t){return typeof e=="number"?e:e[t]||0}const Kd=new WeakMap;class qd{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=ue(),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=f=>{const{dragSnapToOrigin:d}=this.getProps();d?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(pn(f).point)},i=(f,d)=>{const{drag:g,dragPropagation:b,onDragStart:x}=this.getProps();if(g&&!b&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Ql(g),!this.openDragLock))return;this.latestPointerEvent=f,this.latestPanInfo=d,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ke(T=>{let v=this.getAxisMotionValue(T).get()||0;if(ze.test(v)){const{projection:y}=this.visualElement;if(y&&y.layout){const N=y.layout.layoutBox[T];N&&(v=we(N)*(parseFloat(v)/100))}}this.originPoint[T]=v}),x&&ne.postRender(()=>x(f,d)),Ns(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(f,d)=>{this.latestPointerEvent=f,this.latestPanInfo=d;const{dragPropagation:g,dragDirectionLock:b,onDirectionLock:x,onDrag:S}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:T}=d;if(b&&this.currentDirection===null){this.currentDirection=Hd(T),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",d.point,T),this.updateAxis("y",d.point,T),this.visualElement.render(),S&&S(f,d)},c=(f,d)=>{this.latestPointerEvent=f,this.latestPanInfo=d,this.stop(f,d),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>ke(f=>this.getAnimationState(f)==="paused"&&this.getAxisMotionValue(f).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new xa(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:ya(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&&ne.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||!Cn(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=$d(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&&Dt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Bd(s.layoutBox,t):this.constraints=!1,this.elastic=Wd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&ke(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=_d(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Dt(t))return!1;const s=t.current;Ke(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=Yu(s,r.root,this.visualElement.getTransformPagePoint());let i=zd(r.layout.layoutBox,o);if(n){const a=n(Hu(i));this.hasMutatedConstraints=!!a,a&&(i=ea(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=ke(l=>{if(!Cn(l,n,this.currentDirection))return;let f=c&&c[l]||{};i&&(f={min:0,max:0});const d=r?200:1e6,g=r?40:1e7,b={type:"inertia",velocity:s?t[l]:0,bounceStiffness:d,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...f};return this.startAxisValueAnimation(l,b)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Ns(this.visualElement,t),s.start(xr(t,s,0,n,this.visualElement,!1))}stopAnimation(){ke(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){ke(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){ke(n=>{const{drag:s}=this.getProps();if(!Cn(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]-oe(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Dt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};ke(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Ud({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(),ke(i=>{if(!Cn(i,t,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(oe(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Kd.set(this.visualElement,this);const t=this.visualElement.current,n=en(t,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Dt(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()),ne.read(s);const i=dn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(ke(l=>{const f=this.getAxisMotionValue(l);f&&(this.originPoint[l]+=c[l].translate,f.set(f.get()+c[l].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=Rs,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Cn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Hd(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Gd extends ct{constructor(t){super(t),this.removeGroupControls=Ee,this.removeListeners=Ee,this.controls=new qd(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ee}unmount(){this.removeGroupControls(),this.removeListeners()}}const vi=e=>(t,n)=>{e&&ne.postRender(()=>e(t,n))};class Xd extends ct{constructor(){super(...arguments),this.removePointerDownListener=Ee}onPointerDown(t){this.session=new xa(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:ya(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:vi(t),onStart:vi(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ne.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=en(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 Nn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function bi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Jt={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(F.test(e))e=parseFloat(e);else return e;const n=bi(e,t.target.x),s=bi(e,t.target.y);return`${n}% ${s}%`}},Yd={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=at.parse(e);if(r.length>5)return s;const o=at.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=c;const u=oe(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 as=!1;class Jd extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;wu(Zd),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),as&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Nn.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,as=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ne.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),or.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;as=!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 ba(e){const[t,n]=zo(),s=m.useContext(Fs);return h.jsx(Jd,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(Zo),isPresent:t,safeToRemove:n})}const Zd={borderRadius:{...Jt,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Jt,borderTopRightRadius:Jt,borderBottomLeftRadius:Jt,borderBottomRightRadius:Jt,boxShadow:Yd};function Qd(e,t,n){const s=be(e)?e:Lt(e);return s.start(xr("",s,t,n)),s.animation}const eh=(e,t)=>e.depth-t.depth;class th{constructor(){this.children=[],this.isDirty=!1}add(t){zs(this.children,t),this.isDirty=!0}remove(t){Us(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(eh),this.isDirty=!1,this.children.forEach(t)}}function nh(e,t){const n=Pe.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(ot(s),e(o-t))};return ne.setup(s,!0),()=>ot(s)}const wa=["TopLeft","TopRight","BottomLeft","BottomRight"],sh=wa.length,wi=e=>typeof e=="string"?parseFloat(e):e,Ti=e=>typeof e=="number"||F.test(e);function rh(e,t,n,s,r,o){r?(e.opacity=oe(0,n.opacity??1,ih(s)),e.opacityExit=oe(t.opacity??1,0,oh(s))):o&&(e.opacity=oe(t.opacity??1,n.opacity??1,s));for(let i=0;i<sh;i++){const a=`border${wa[i]}Radius`;let c=Si(t,a),u=Si(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||Ti(c)===Ti(u)?(e[a]=Math.max(oe(wi(c),wi(u),s),0),(ze.test(u)||ze.test(c))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=oe(t.rotate||0,n.rotate||0,s))}function Si(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const ih=Ta(0,.5,oo),oh=Ta(.5,.95,Ee);function Ta(e,t,n){return s=>s<e?0:s>t?1:n(on(e,t,s))}function Ai(e,t){e.min=t.min,e.max=t.max}function je(e,t){Ai(e.x,t.x),Ai(e.y,t.y)}function Pi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Ci(e,t,n,s,r){return e-=t,e=$n(e,1/n,s),r!==void 0&&(e=$n(e,1/r,s)),e}function ah(e,t=0,n=1,s=.5,r,o=e,i=e){if(ze.test(t)&&(t=parseFloat(t),t=oe(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=oe(o.min,o.max,s);e===o&&(a-=t),e.min=Ci(e.min,t,n,a,r),e.max=Ci(e.max,t,n,a,r)}function ji(e,t,[n,s,r],o,i){ah(e,t[n],t[s],t[r],t.scale,o,i)}const ch=["x","scaleX","originX"],lh=["y","scaleY","originY"];function ki(e,t,n,s){ji(e.x,t,ch,n?n.x:void 0,s?s.x:void 0),ji(e.y,t,lh,n?n.y:void 0,s?s.y:void 0)}function Mi(e){return e.translate===0&&e.scale===1}function Sa(e){return Mi(e.x)&&Mi(e.y)}function Ei(e,t){return e.min===t.min&&e.max===t.max}function uh(e,t){return Ei(e.x,t.x)&&Ei(e.y,t.y)}function Di(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Aa(e,t){return Di(e.x,t.x)&&Di(e.y,t.y)}function Ni(e){return we(e.x)/we(e.y)}function Vi(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class dh{constructor(){this.members=[]}add(t){zs(this.members,t),t.scheduleRender()}remove(t){if(Us(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 hh(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:l,rotateX:f,rotateY:d,skewX:g,skewY:b}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),f&&(s+=`rotateX(${f}deg) `),d&&(s+=`rotateY(${d}deg) `),g&&(s+=`skewX(${g}deg) `),b&&(s+=`skewY(${b}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const cs=["","X","Y","Z"],fh=1e3;let mh=0;function ls(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Pa(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=la(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ne,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Pa(s)}function Ca({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=mh++,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(yh),this.nodes.forEach(wh),this.nodes.forEach(Th),this.nodes.forEach(xh)},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 th)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Ws),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=Bo(i)&&!iu(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),e){let l,f=0;const d=()=>this.root.updateBlockedByResize=!1;ne.read(()=>{f=window.innerWidth}),e(i,()=>{const g=window.innerWidth;g!==f&&(f=g,this.root.updateBlockedByResize=!0,l&&l(),l=nh(d,250),Nn.hasAnimatedSinceResize&&(Nn.hasAnimatedSinceResize=!1,this.nodes.forEach(Oi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:f,hasRelativeLayoutChanged:d,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const b=this.options.transition||u.getDefaultTransition()||jh,{onLayoutAnimationStart:x,onLayoutAnimationComplete:S}=u.getProps(),T=!this.targetLayout||!Aa(this.targetLayout,g),v=!f&&d;if(this.options.layoutRoot||this.resumeFrom||v||f&&(T||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const y={...rr(b,"layout"),onPlay:x,onComplete:S};(u.shouldReduceMotion||this.options.layoutRoot)&&(y.delay=0,y.type=!1),this.startAnimation(y),this.setAnimationOrigin(l,v)}else f||Oi(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(),ot(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(Sh),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&&Pa(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const f=this.path[l];f.shouldResetTransform=!0,f.updateScroll("snapshot"),f.options.layoutRoot&&f.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(Ri);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ii);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(bh),this.nodes.forEach(ph),this.nodes.forEach(gh)):this.nodes.forEach(Ii),this.clearAllSnapshots();const a=Pe.now();ye.delta=We(0,1e3/60,a-ye.timestamp),ye.timestamp=a,ye.isProcessing=!0,Jn.update.process(ye),Jn.preRender.process(ye),Jn.render.process(ye),ye.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,or.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(vh),this.sharedNodes.forEach(Ah)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ne.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ne.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!we(this.snapshot.measuredBox.x)&&!we(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=ue(),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&&!Sa(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||xt(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)),kh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ue();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Mh))){const{scroll:u}=this.root;u&&(Nt(a.x,u.offset.x),Nt(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ue();if(je(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:f}=u;u!==this.root&&l&&f.layoutScroll&&(l.wasRoot&&je(a,i),Nt(a.x,l.offset.x),Nt(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=ue();je(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&&Vt(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),xt(l.latestValues)&&Vt(c,l.latestValues)}return xt(this.latestValues)&&Vt(c,this.latestValues),c}removeTransform(i){const a=ue();je(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!xt(u.latestValues))continue;ks(u.latestValues)&&u.updateSnapshot();const l=ue(),f=u.measurePageBox();je(l,f),ki(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return xt(this.latestValues)&&ki(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!==ye.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:f}=this.options;if(!(!this.layout||!(l||f))){if(this.resolvedRelativeTargetAt=ye.timestamp,!this.targetDelta&&!this.relativeTarget){const d=this.getClosestProjectingParent();d&&d.layout&&this.animationProgress!==1?(this.relativeParent=d,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ue(),this.relativeTargetOrigin=ue(),nn(this.relativeTargetOrigin,this.layout.layoutBox,d.layout.layoutBox),je(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ue(),this.targetWithTransforms=ue()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Id(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):je(this.target,this.layout.layoutBox),na(this.target,this.targetDelta)):je(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const d=this.getClosestProjectingParent();d&&!!d.resumingFrom==!!this.resumingFrom&&!d.options.layoutScroll&&d.target&&this.animationProgress!==1?(this.relativeParent=d,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ue(),this.relativeTargetOrigin=ue(),nn(this.relativeTargetOrigin,this.target,d.target),je(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ks(this.parent.latestValues)||ta(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===ye.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;je(this.layoutCorrected,this.layout.layoutBox);const f=this.treeScale.x,d=this.treeScale.y;Xu(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=ue());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Pi(this.prevProjectionDelta.x,this.projectionDelta.x),Pi(this.prevProjectionDelta.y,this.projectionDelta.y)),tn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==f||this.treeScale.y!==d||!Vi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vi(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=Rt(),this.projectionDelta=Rt(),this.projectionDeltaWithTransform=Rt()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},f=Rt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const d=ue(),g=c?c.source:void 0,b=this.layout?this.layout.source:void 0,x=g!==b,S=this.getStack(),T=!S||S.members.length<=1,v=!!(x&&!T&&this.options.crossfade===!0&&!this.path.some(Ch));this.animationProgress=0;let y;this.mixTargetDelta=N=>{const M=N/1e3;Li(f.x,i.x,M),Li(f.y,i.y,M),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(nn(d,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Ph(this.relativeTarget,this.relativeTargetOrigin,d,M),y&&uh(this.relativeTarget,y)&&(this.isProjectionDirty=!1),y||(y=ue()),je(y,this.relativeTarget)),x&&(this.animationValues=l,rh(l,u,this.latestValues,M,v,T)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=M},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ot(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ne.update(()=>{Nn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Lt(0)),this.currentAnimation=Qd(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(fh),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&&ja(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||ue();const f=we(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+f;const d=we(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+d}je(a,c),Vt(a,l),tn(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new dh),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&&ls("z",i,u,this.animationValues);for(let l=0;l<cs.length;l++)ls(`rotate${cs[l]}`,i,u,this.animationValues),ls(`skew${cs[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=En(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=En(a?.pointerEvents)||""),this.hasProjected&&!xt(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let f=hh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(f=c(l,f)),i.transform=f;const{x:d,y:g}=this.projectionDelta;i.transformOrigin=`${d.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 b in un){if(l[b]===void 0)continue;const{correct:x,applyTo:S,isCSSVariable:T}=un[b],v=f==="none"?l[b]:x(l[b],u);if(S){const y=S.length;for(let N=0;N<y;N++)i[S[N]]=v}else T?this.options.visualElement.renderState.vars[b]=v:i[b]=v}this.options.layoutId&&(i.pointerEvents=u===this?En(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Ri),this.root.sharedNodes.clear()}}}function ph(e){e.updateLayout()}function gh(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"?ke(l=>{const f=o?t.measuredBox[l]:t.layoutBox[l],d=we(f);f.min=n[l].min,f.max=f.min+d}):ja(r,t.layoutBox,n)&&ke(l=>{const f=o?t.measuredBox[l]:t.layoutBox[l],d=we(n[l]);f.max=f.min+d,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[l].max=e.relativeTarget[l].min+d)});const i=Rt();tn(i,n,t.layoutBox);const a=Rt();o?tn(a,e.applyTransform(s,!0),t.measuredBox):tn(a,n,t.layoutBox);const c=!Sa(i);let u=!1;if(!e.resumeFrom){const l=e.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:f,layout:d}=l;if(f&&d){const g=ue();nn(g,t.layoutBox,f.layoutBox);const b=ue();nn(b,n,d.layoutBox),Aa(g,b)||(u=!0),l.options.layoutRoot&&(e.relativeTarget=b,e.relativeTargetOrigin=g,e.relativeParent=l)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function yh(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 xh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function vh(e){e.clearSnapshot()}function Ri(e){e.clearMeasurements()}function Ii(e){e.isLayoutDirty=!1}function bh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Oi(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function wh(e){e.resolveTargetDelta()}function Th(e){e.calcProjection()}function Sh(e){e.resetSkewAndRotation()}function Ah(e){e.removeLeadSnapshot()}function Li(e,t,n){e.translate=oe(t.translate,0,n),e.scale=oe(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Fi(e,t,n,s){e.min=oe(t.min,n.min,s),e.max=oe(t.max,n.max,s)}function Ph(e,t,n,s){Fi(e.x,t.x,n.x,s),Fi(e.y,t.y,n.y,s)}function Ch(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const jh={duration:.45,ease:[.4,0,.1,1]},$i=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Bi=$i("applewebkit/")&&!$i("chrome/")?Math.round:Ee;function zi(e){e.min=Bi(e.min),e.max=Bi(e.max)}function kh(e){zi(e.x),zi(e.y)}function ja(e,t,n){return e==="position"||e==="preserve-aspect"&&!Rd(Ni(t),Ni(n),.2)}function Mh(e){return e!==e.root&&e.scroll?.wasRoot}const Eh=Ca({attachResizeListener:(e,t)=>dn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),us={current:void 0},ka=Ca({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!us.current){const e=new Eh({});e.mount(window),e.setOptions({layoutScroll:!0}),us.current=e}return us.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Dh={pan:{Feature:Xd},drag:{Feature:Gd,ProjectionNode:ka,MeasureLayout:ba}};function Ui(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&&ne.postRender(()=>o(t,pn(t)))}class Nh extends ct{mount(){const{current:t}=this.node;t&&(this.unmount=eu(t,(n,s)=>(Ui(this.node,s,"Start"),r=>Ui(this.node,r,"End"))))}unmount(){}}class Vh extends ct{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=hn(dn(this.node.current,"focus",()=>this.onFocus()),dn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function _i(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&&ne.postRender(()=>o(t,pn(t)))}class Rh extends ct{mount(){const{current:t}=this.node;t&&(this.unmount=ru(t,(n,s)=>(_i(this.node,s,"Start"),(r,{success:o})=>_i(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Is=new WeakMap,ds=new WeakMap,Ih=e=>{const t=Is.get(e.target);t&&t(e)},Oh=e=>{e.forEach(Ih)};function Lh({root:e,...t}){const n=e||document;ds.has(n)||ds.set(n,{});const s=ds.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Oh,{root:e,...t})),s[r]}function Fh(e,t,n){const s=Lh(t);return Is.set(e,n),s.observe(e),()=>{Is.delete(e),s.unobserve(e)}}const $h={some:0,all:1};class Bh extends ct{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:$h[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:f}=this.node.getProps(),d=u?l:f;d&&d(c)};return Fh(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(zh(t,n))&&this.startObserver()}unmount(){}}function zh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Ma={inView:{Feature:Bh},tap:{Feature:Rh},focus:{Feature:Vh},hover:{Feature:Nh}},Uh={layout:{ProjectionNode:ka,MeasureLayout:ba}},_h={...ma,...Ma,...Dh,...Uh},Wh=qu(_h,ca),Kh={renderer:ca,...ma,...Ma};function Ea(e,t){return Dn(e,t)}const jn=Ea("div"),qh=Ea("p"),Be=Symbol.for("@arcteninc/core:originalName");function Hh(e,t){return e[Be]=t,e}function Gh(e,t,n,s){if(typeof e!="function")return null;const r=e[Be];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[Be]=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[Be]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(c=>!n.has(c.name)),i)return e[Be]=i.name,{fn:e,meta:i};return null}function Da(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=Hh(o,n,r,s);if(!i){const a=o.name,u=o[zt]||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 Xh({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(Vn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(ft.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Vn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(ft.X,{className:"h-3 w-3"})})]})]})})}function Gh({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 ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(ft.ChevronDown,{className:"h-3 w-3"}):d.jsx(ft.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(ft.X,{className:"h-3 w-3"}):s?d.jsx(ft.Zap,{className:"h-3 w-3"}):d.jsx(ft.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 Yh({...t}){return d.jsx(Os.Root,{"data-slot":"collapsible",...t})}function Jh({...t}){return d.jsx(Os.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function Zh({...t}){return d.jsx(Os.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const Qh=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),xr=m.memo(({className:t,...e})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(Qh,{className:mt("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);xr.displayName="Response";const tf=Object.freeze(Object.defineProperty({__proto__:null,Response:xr},Symbol.toStringTag,{value:"Module"})),ef=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=_h.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})},nf=m.memo(ef),Da=m.createContext(null),sf=()=>{const t=m.useContext(Da);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},rf=1e3,of=1e3,Na=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Pr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Pr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[x,b]=m.useState(null);m.useEffect(()=>{e?x===null&&b(Date.now()):x!==null&&(h(Math.ceil((Date.now()-x)/of)),b(null))},[e,x,h]),m.useEffect(()=>{if(s&&!e&&c&&!f){const y=setTimeout(()=>{u(!1),g(!0)},rf);return()=>clearTimeout(y)}},[e,c,s,u,f]);const j=y=>{u(y)};return d.jsx(Da.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(Yh,{className:mt("not-prose mb-4",t),onOpenChange:j,open:c,...a,children:i})})}),af=(t,e)=>t||e===0?d.jsx(nf,{duration:1,children:"Thinking..."}):e===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",e," seconds"]}),Va=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=sf();return d.jsx(Jh,{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(ft.BrainIcon,{className:"size-4"}),af(s,o),d.jsx(ft.ChevronDownIcon,{className:mt("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ra=m.memo(({className:t,children:e,...n})=>d.jsx(Zh,{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(xr,{className:"grid gap-2",children:e})}));Na.displayName="Reasoning";Va.displayName="ReasoningTrigger";Ra.displayName="ReasoningContent";function _i(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function cf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=_i(s.domain);return d.jsxs(Qt,{children:[d.jsx(te,{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(ee,{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=>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:i=>i.stopPropagation(),children:[d.jsx("img",{src:_i(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),d.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function lf({text:t,citations:e,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0}){const c=m.useRef(null),[u,l]=m.useState([]);m.useEffect(()=>{if(!a||!c.current||e.length===0||n.size===0){(n.size===0||!a)&&l([]);return}const f=c.current;let g,x=!1;const b=new WeakSet,j=()=>{if(!c.current||x)return;x=!0;const v=c.current,T=/\[(\d+)\]/g,S=document.createTreeWalker(v,NodeFilter.SHOW_TEXT,null),E=[];let R;for(;R=S.nextNode();)if(R.nodeType===Node.TEXT_NODE&&!b.has(R)){const k=R,W=k.textContent||"";let O=k.parentElement,et=!1;for(;O&&O!==v;){if(O.tagName==="A"||O.tagName==="CODE"||O.tagName==="PRE"){et=!0;break}O=O.parentElement}if(!et){const ct=Array.from(W.matchAll(T)).filter(yt=>{if(!yt[1])return!1;const dt=parseInt(yt[1],10);return n.has(dt)});ct.length>0&&E.push({node:k,matches:ct})}}if(E.length===0){x=!1;return}const C=[];E.forEach(({node:k,matches:W})=>{b.add(k);const O=k.textContent||"",et=document.createDocumentFragment();let Y=0;W.forEach(ct=>{if(!ct[1])return;ct.index!==void 0&&ct.index>Y&&et.appendChild(document.createTextNode(O.slice(Y,ct.index)));const yt=document.createElement("span");yt.className="inline-flex items-center citation-button-container";const dt=parseInt(ct[1],10);yt.setAttribute("data-citation",ct[1]),et.appendChild(yt),C.push({element:yt,citationNum:dt}),Y=(ct.index||0)+ct[0].length}),Y<O.length&&et.appendChild(document.createTextNode(O.slice(Y))),k.parentNode&&k.parentNode.replaceChild(et,k)}),C.length>0&&l(k=>{const W=new Set(k.map(Y=>Y.element)),O=k.filter(Y=>Y.element.isConnected),et=C.filter(Y=>!W.has(Y.element));return[...O,...et]}),x=!1},y=new MutationObserver(()=>{clearTimeout(g),g=setTimeout(j,100)});return y.observe(f,{childList:!0,subtree:!0,characterData:!0}),g=setTimeout(j,200),()=>{y.disconnect(),clearTimeout(g)}},[t,e,n,a]);const h=a&&(s||r)?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-2",children:"References"}),d.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:s&&s.length>0?s.map((f,g)=>{const x=f.numbers[0],b=f.anchor?`${f.baseUrl}#${f.anchor}`:f.url,j=f.anchor&&f.url!==b;return d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium whitespace-nowrap",children:["[",x,"]"]}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("a",{href:f.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:f.baseUrl}),j&&d.jsxs("span",{className:"text-stone-500 dark:text-stone-500 ml-1",children:["#",f.anchor]})]})]},`group-${g}`)}):Array.from(n.entries()).sort(([f],[g])=>f-g).map(([f,g])=>d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium",children:["[",f,"]"]}),d.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:g})]},f))})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:c,children:d.jsx(o,{children:t})}),a&&u.filter(({element:f})=>f.isConnected).map(({element:f,citationNum:g},x)=>{if(!e.find(y=>y.number===g))return null;const j=Array.from(new Map(e.map(y=>[y.url.replace(/\/+$/,""),{number:y.number,url:y.url,domain:uf(y.url)}])).values());return oc.createPortal(d.jsx(cf,{sources:j,citationNumber:g},`citation-${g}-${f}`),f,`citation-${g}-${x}`)}),h]})}function uf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function df(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 hf(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 v=s[1],T=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let S;for(;(S=T.exec(v))!==null;)if(S[1]&&S[2]){const E=parseInt(S[1],10),R=S[2].replace(/[.,;:!?]+$/,""),C=R.replace(/\/+$/,"");if(a.has(C)||a.set(C,R),i.has(C)||i.set(C,[]),i.get(C).push(E),!c.has(C))c.set(C,E);else{const k=c.get(C);E<k&&c.set(C,E)}}for(const[E,R]of i.entries()){const C=c.get(E);for(const k of R)k!==C&&u.set(k,C)}for(const[E,R]of c.entries()){const C=a.get(E)||E;r.set(R,C),o.push({number:R,url:C})}}let l,h=e;s&&s[0]&&(l=s[0],h=e.replace(n,""));const f=[];let g=0;const x=/```[\s\S]*?```|`[^`]+`/g;let b;for(;(b=x.exec(h))!==null;)b.index>g&&f.push({type:"text",content:h.slice(g,b.index),start:g,end:b.index}),f.push({type:"code",content:b[0],start:b.index,end:b.index+b[0].length}),g=b.index+b[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const j=f.map(v=>{if(v.type==="code")return v.content;let T=v.content;return T=T.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(E,R,C)=>{const k=parseInt(R,10),W=C.replace(/\/+$/,""),O=u.get(k)||k;return c.has(W)||(c.set(W,O),r.has(O)||(r.set(O,C),o.push({number:O,url:C}))),`[${O}]`}),T=T.replace(/\[(\d+)\]/g,(E,R)=>{const C=parseInt(R,10);return`[${u.get(C)||C}]`}),T}),y=[];for(const[v,T]of c.entries()){const S=a.get(v)||v,{baseUrl:E,anchor:R}=df(S);y.push({url:S,baseUrl:E,numbers:[T],anchor:R})}return y.sort((v,T)=>(v.numbers[0]||0)-(T.numbers[0]||0)),{processedText:j.join(""),citations:o.sort((v,T)=>v.number-T.number),citationMap:r,groupedCitations:y,referencesText:l}}function en(t){if(typeof t=="string")try{const e=JSON.parse(t);return en(e)}catch{return t}if(Array.isArray(t))return t.map(en);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=en(s);return e}return t}function ds(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return en(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?en(t):{}}function ff({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:x="/api/arcten/token",apiBaseUrl:b="https://api.arcten.com",user:j,state:y,onStateChange:v,allowStateEdits:T=!0,sources:S,ragConfig:E,showCitations:R=!0}){const C=m.useMemo(()=>E!==void 0?E:S&&S.length>0?{enabled:!0,organizationId:S[0],autoExecute:!0,filters:void 0}:{enabled:!1},[S,E]),[k,W]=m.useState(null),O=m.useRef(null),[et,Y]=m.useState(null),[ct,yt]=m.useState(null),dt=m.useRef(null),Z=y!==void 0,[ot,lt]=m.useState({}),tt=m.useRef({});Z&&y?tt.current=y:Z||(tt.current=ot);const[ht,oe]=m.useState(!1),[_n,we]=m.useState(null),Vt=m.useRef(!1),[bt,ae]=m.useState(u),[wt,Ft]=m.useState(i),[Rt,$t]=m.useState(600),[ce,Pt]=m.useState(!1),[J,Te]=m.useState(!1),[jt,Ht]=m.useState(!1),[Tt,Be]=m.useState({x:100,y:100}),[ze,kt]=m.useState(!1),[Ue,Se]=m.useState({x:0,y:0}),[_e,Wn]=m.useState(!1),Xt=m.useRef(null),Gt=m.useRef(null),[Ae,We]=m.useState(""),[mn,pn]=m.useState(null),[Kn,qn]=m.useState("Thinking..."),[Ke,Yt]=m.useState(new Set),[M,P]=m.useState(""),[N,F]=m.useState([]),[B,z]=m.useState(!1),[q,xt]=m.useState([]),[nt,Ct]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[X,Q]=m.useState(!1),[Ce,le]=m.useState(!1),[gf,gn]=m.useState([]),vr=m.useCallback(async(p,w=3)=>{if(!nt||!O.current)return;const D=async()=>{const V=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,I=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:nt,updates:p},format:"json"})});if(!I.ok){if(I.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const K=await I.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${I.status} ${K}`)}};for(let A=0;A<w;A++)try{await D(),we(null);return}catch(V){if(A===w-1){const K=V instanceof Error?V:new Error(String(V));throw we(K),console.error("Failed to sync state to Convex after retries:",V),K}await new Promise(K=>setTimeout(K,Math.pow(2,A)*100))}},[nt,b,O]),qe=m.useMemo(()=>function(){return tt.current},[]),He=m.useMemo(()=>async function(w){const D={...tt.current,...w};tt.current=D,Z||lt(D),v&&v(D);try{await vr(w)}catch(A){throw A}},[vr,v,Z]);m.useEffect(()=>{Z&&y&&(tt.current=y)},[Z,y]);const ue=m.useMemo(()=>C?.enabled?async function(w,D=20,A){if(S&&S.length>1){const K=S.map(U=>fetch(`${b}/search`,{method:"POST",headers:{"Content-Type":"application/json",...O.current?{Authorization:`Bearer ${O.current}`}:{}},body:JSON.stringify({q:w,k:Math.min(D,100),organizationId:U,...Object.keys(I).length>0?{filters:I}:{}})}).then(_=>_.ok?_.json():null)),$=await Promise.all(K),G=[];for(const U of $)U?.candidates&&G.push(...U.candidates);G.sort((U,_)=>{const St=U.scores?.rerank||U.scores?.dense||0;return(_.scores?.rerank||_.scores?.dense||0)-St});const H=G.slice(0,D).map((U,_)=>{const St=U.citation||U.url;return{rank:_+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:St,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:w,total:G.length,results:H,summary:`Found ${G.length} relevant results across ${S.length} source(s) for "${w}". Top result: ${H[0]?.title||"N/A"}`}}const V=C.organizationId&&C.organizationId!=="default"?C.organizationId:void 0,I={...C.filters,...A};try{const K={q:w,k:Math.min(D,100)};V&&(K.organizationId=V),Object.keys(I).length>0&&(K.filters=I);const $={"Content-Type":"application/json"};O.current&&($.Authorization=`Bearer ${O.current}`);const G=await fetch(`${b}/search`,{method:"POST",headers:$,body:JSON.stringify(K)});if(!G.ok){const _=await G.text();return{success:!1,error:`Search failed: ${G.status} ${_}`}}const H=await G.json(),U=H.candidates.map((_,St)=>{const wn=_.citation||_.url;return{rank:St+1,doc_id:_.doc_id,block_id:_.block_id,url:_.url,citation:wn,title:_.title||"Untitled",snippet:_.snippet,score:_.scores?.rerank||_.scores?.dense||0,metadata:{site:_.metadata?.site,lang:_.metadata?.lang,contentType:_.metadata?.content_type}}});return{success:!0,query:H.query,total:H.total,results:U,summary:`Found ${H.total} relevant results for "${w}". Top result: ${U[0]?.title||"N/A"}`}}catch(K){return{success:!1,error:K instanceof Error?K.message:"Unknown error occurred"}}}:null,[E,b,O]),de=m.useMemo(()=>C?.enabled?async function(w,D){const A=C.organizationId&&C.organizationId!=="default"?C.organizationId:S&&S.length>0?S[0]:void 0;try{const V={"Content-Type":"application/json"};O.current&&(V.Authorization=`Bearer ${O.current}`);const I=await fetch(`${b}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:w,block_ids:D,...A?{organizationId:A}:{}})});if(!I.ok){const $=await I.text();return{success:!1,error:`Fetch failed: ${I.status} ${$}`}}const K=await I.json();return{success:!0,blocks:K.blocks||[],fullContent:K.fullContent||"",pageUrl:K.pageUrl||"",pageTitle:K.pageTitle||"",summary:`Fetched ${K.blocks?.length||0} blocks from ${K.pageTitle||w}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[E,b,O]),he=m.useMemo(()=>{const p=[...l,...h,qe];return(!Z||T)&&p.push(He),C?.enabled&&(ue&&p.push(ue),de&&p.push(de)),p},[l,h,qe,He,ue,de,Z,T,C]),Hn=m.useMemo(()=>Ea(he,f),[he,f]),_t=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:[]}}];(!Z||T)&&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 w=[];return C?.enabled&&w.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"]}}),[...Hn,...p,...w]},[Hn,Z,T,C]),br=m.useMemo(()=>new Set(_t.map(p=>p.name)),[_t]),yn=m.useMemo(()=>_t.filter(p=>p.name==="getState"?!0:p.name==="setState"?!Z||T:br.has(p.name)),[_t,br,Z,T]),xn=m.useMemo(()=>{const p=new Map,w=new Map(Hn.map(D=>[D.name,D]));return p.set("getState",qe),(!Z||T)&&p.set("setState",He),C?.enabled&&(ue&&p.set("searchDocs",ue),de&&p.set("fetchDocContent",de)),he.forEach(D=>{if(D===qe||D===He||D===ue||D===de)return;const A=D[zt];if(A){const I=w.get(A);if(I){p.set(I.name,D);return}}const V=_t.find(I=>I.name===D.name);V&&p.set(V.name,D)}),p},[he,_t,qe,He,ue,de,Z,T,C]),Xe=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),C?.enabled&&C.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const w=new Map(_t.map(D=>[D.name,D]));return h.forEach(D=>{const A=D[zt];if(A&&w.has(A))p.add(A);else{const V=_t.find(I=>I.name===D.name);V&&p.add(V.name)}}),p},[h,_t,C]),wr=["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&&ae(JSON.parse(p));const w=localStorage.getItem("arcten-sidebar-width");w&&Ft(parseInt(w));const D=localStorage.getItem("arcten-sidebar-height");D&&$t(parseInt(D));const A=localStorage.getItem("arcten-sidebar-detached");A&&Te(JSON.parse(A));const V=localStorage.getItem("arcten-sidebar-position");if(V){const K=JSON.parse(V),$=50,G=Math.max($-i,Math.min(K.x,window.innerWidth-$)),H=Math.max(0,Math.min(K.y,window.innerHeight-$));Be({x:G,y:H})}const I=localStorage.getItem("arcten-sidebar-minimized");I&&Ht(JSON.parse(I)),Wn(!0)}},[]);const Jt=m.useMemo(()=>j,[j?.id]);m.useEffect(()=>((async()=>{try{const w=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!w.ok)throw new Error("Failed to fetch token");const D=await w.json();W(D.clientToken),O.current=D.clientToken,yt(D.expiresAt),Y(null)}catch(w){Y(w instanceof Error?w.message:"Failed to fetch token")}})(),()=>{dt.current&&clearTimeout(dt.current)}),[x,Jt]),m.useEffect(()=>{if(!ct)return;dt.current&&clearTimeout(dt.current);const p=Math.floor(Date.now()/1e3),w=ct-p,A=Math.max(0,w-5);return dt.current=setTimeout(async()=>{try{const V=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!V.ok)throw new Error("Failed to refresh token");const I=await V.json();W(I.clientToken),O.current=I.clientToken,yt(I.expiresAt),Y(null)}catch(V){console.error("Token refresh failed:",V),Y(V instanceof Error?V.message:"Failed to refresh token")}},A*1e3),()=>{dt.current&&clearTimeout(dt.current)}},[ct,x,Jt]),m.useEffect(()=>{(async()=>{if(he.length!==0)try{const w=he.map(A=>({name:A.name,code:A.toString()})),D=await fetch(`${b}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:w})});if(D.ok){const A=await D.json();F(A.tools)}}catch(w){console.error("Failed to fetch tool descriptions:",w)}})()},[he]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{pn(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{P(window.location.pathname)};p(),window.addEventListener("popstate",p);const w=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(w)}},[]);const Xn=m.useCallback(async()=>{if(!(!Jt?.id||!k)){le(!0);try{const w=await(await fetch(`${b}/conversations`,{headers:{Authorization:`Bearer ${k}`}})).json();xt(w.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{le(!1)}}},[Jt?.id,k,b]);m.useEffect(()=>{Jt?.id&&k&&Xn()},[Jt?.id,k,Xn]);function Ia(p){const w=Math.floor((Date.now()-p)/1e3);return w<60?"now":w<3600?`${Math.floor(w/60)}m`:w<86400?`${Math.floor(w/3600)}h`:`${Math.floor(w/86400)}d`}function Oa(){const p=crypto.randomUUID();Ct(p),bn([]),gn([]),Q(!1);const w=Z?y||{}:{};tt.current=w,Z||lt(w),v&&v(w),Vt.current=!1}async function La(p){if(k)try{await fetch(`${b}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${k}`}}),xt(q.filter(w=>w._id!==p)),p===nt&&Oa()}catch(w){console.error("Failed to delete conversation:",w)}}async function Fa(p){Ct(p.chatId),Q(!1),le(!0);try{const w=await fetch(`${b}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${O.current}`}});if(!w.ok)throw new Error(`Failed to fetch messages: ${w.statusText}`);const A=(await w.json()).messages||[];bn(A),gn(A)}catch(w){console.error("Failed to load conversation messages:",w);const D=p.messages||[];bn(D),gn(D)}finally{le(!1)}}const $a=async(p,w={})=>{const D=w.headers?new Headers(w.headers):new Headers;return D.delete("user-agent"),D.delete("User-Agent"),fetch(p,{...w,headers:D})},{messages:Zt,sendMessage:Ba,status:Bt,error:Tr,stop:vn,addToolResult:fe,setMessages:bn}=Wi.useChat({id:nt||void 0,transport:new Nn.DefaultChatTransport({api:`${b}/chat`,fetch:$a,headers:()=>{const p={};return O.current&&(p.Authorization=`Bearer ${O.current}`),p},body:()=>({tools:yn.map(w=>({name:w.name,description:w.description,inputSchema:w.jsonSchema})),systemPrompt:g,currentRoute:M,state:tt.current})}),sendAutomaticallyWhen:Nn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Zt[Zt.length-1];if(!p||p.role!=="assistant")return;const w=p.parts?.filter(D=>D.type?.startsWith("tool-")&&D.state==="input-available"&&typeof D.toolCallId=="string"&&D.input!==void 0)||[];for(const D of w){const A=D,V=A.type?.replace("tool-","")||"",I=A.toolCallId;if(Xe.has(V)){if(Ke.has(I))continue;Yt($=>$.has(I)?$:new Set($).add(I)),(async()=>{try{const $=xn.get(V);if(!$){console.warn(`[ArctenAgent] Tool ${V} not found in toolsMap. Available tools:`,Array.from(xn.keys())),fe({toolCallId:I,tool:V,output:`Error: Tool ${V} not found`}),Yt(_=>{const St=new Set(_);return St.delete(I),St});return}const G=ds(A.input),H=yn.find(_=>_.name===V);let U;if(H&&H.jsonSchema?.properties){const St=Object.keys(H.jsonSchema.properties).map(wn=>G[wn]);console.log(`[ArctenAgent] Executing safe tool ${V} with args:`,St),U=await $(...St)}else if(V==="getState")U=$();else if(V==="setState"){const _=G.updates||G;U=await $(_)}else U=await $(...Object.values(G));console.log(`[ArctenAgent] Tool ${V} completed, result:`,U),fe({toolCallId:I,tool:V,output:U}),Yt(_=>{const St=new Set(_);return St.delete(I),St})}catch($){console.error(`[ArctenAgent] Error executing safe tool ${V}:`,$),fe({toolCallId:I,tool:V,output:`Error: ${$ instanceof Error?$.message:String($)}`}),Yt(G=>{const H=new Set(G);return H.delete(I),H})}})()}}},[Zt,Xe,xn,yn,fe]),m.useEffect(()=>{if(!nt||!O.current)return;(async()=>{oe(!0),we(null);try{const D=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,A=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:nt},format:"json"})});if(!A.ok){if(A.status===404||A.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${A.status}), using empty state`);const H=Z?y||{}:{};tt.current=H,Z||lt(H),v&&v(H),Vt.current=!0,oe(!1);return}const G=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${G}`)}const I=(await A.json())?.value||{},K=!Vt.current;let $;K?($={...Z?y||{}:{},...I},Vt.current=!0):$=I,tt.current=$,Z||lt($),v&&v($)}catch(w){w instanceof TypeError&&w.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",w):console.error("[ArctenAgent] Failed to fetch state:",w);const A=w instanceof Error?w:new Error(String(w));if(we(A),!Vt.current){const V=Z?y||{}:{};tt.current=V,Z||lt(V),v&&v(V),Vt.current=!0}}finally{oe(!1)}})()},[nt,b,Z,y,v]),m.useEffect(()=>{bt&&Gt.current&&Gt.current.focus()},[bt,Zt]);function za(){ae(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ua(){ae(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[bt]),m.useEffect(()=>{Xt.current&&Xt.current.scrollIntoView({behavior:"smooth"})},[Zt]),m.useEffect(()=>{function p(w){w.key==="Escape"&&(Bt==="streaming"||Bt==="submitted")&&(w.preventDefault(),vn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Bt,vn]);function _a(){const p=crypto.randomUUID();Ct(p),bn([]),gn([]),Q(!1)}function Sr(p){if(p.preventDefault(),!Ae.trim())return;(Bt==="streaming"||Bt==="submitted")&&vn();const w=wr[Math.floor(Math.random()*wr.length)]||"Thinking...";qn(w),Ba({text:Ae}),We("")}function Wa(p){const w=p.target.value;We(w)}m.useEffect(()=>{if(!ce)return;function p(D){if(J){const A=D.clientX-Tt.x,V=D.clientY-Tt.y;A>=a&&A<=c&&Ft(A),V>=400&&V<=1e3&&$t(V)}else{const A=window.innerWidth-D.clientX;A>=a&&A<=c&&Ft(A)}}function w(){Pt(!1),localStorage.setItem("arcten-sidebar-width",wt.toString()),localStorage.setItem("arcten-sidebar-height",Rt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[ce,wt,Rt,J,Tt,a,c]);function Ka(p){p.preventDefault(),Pt(!0)}function qa(){Te(!0),Ht(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ha(){Te(!1),Ht(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ar(){Ht(!jt),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!jt))}function Xa(p){J&&(kt(!0),Se({x:p.clientX-Tt.x,y:p.clientY-Tt.y}))}return m.useEffect(()=>{if(!J)return;function p(){Be(w=>{const A=window.innerWidth-50,V=window.innerHeight-50,I=50-wt,K=0,$=Math.max(I,Math.min(w.x,A)),G=Math.max(K,Math.min(w.y,V));if($!==w.x||G!==w.y){const H={x:$,y:G};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(H)),H}return w})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[J,wt]),m.useEffect(()=>{if(!ze)return;function p(D){const A=D.clientX-Ue.x,V=D.clientY-Ue.y,I=50,K=window.innerWidth-I,$=window.innerHeight-I,G=I-wt,H=0,U=Math.max(G,Math.min(A,K)),_=Math.max(H,Math.min(V,$));Be({x:U,y:_})}function w(){kt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Tt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[ze,Ue,Tt,wt]),_e?et?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: ",et]})}):k?d.jsx(mu,{features:Wh,children:d.jsx(Pn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"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
- ${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
- ${J?"border border-border":"border-l border-border"}
23
- ${bt?"":"w-[30px]"}
24
- `,style:bt?J?{width:`${wt}px`,height:jt?"auto":`${Rt}px`,left:`${Tt.x}px`,top:`${Tt.y}px`}:{width:`${wt}px`}:void 0,onClick:bt?void 0:za,children:bt?d.jsxs(d.Fragment,{children:[!J&&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:Ka,children:d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&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(),Pt(!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(),kt(!0),Se({x:p.clientX-Tt.x,y:p.clientY-Tt.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(),Pt(!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 ${J?"cursor-move":""}`,onMouseDown:J?Xa:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${J&&jt?"cursor-pointer":""}`,onClick:J&&jt?p=>{p.stopPropagation(),Ar()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:_a,"aria-label":"New chat",children:d.jsx(ft.Plus,{className:"h-4 w-4"})})}),d.jsx(ee,{children:"Start a new conversation"})]}),d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ha:qa,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?d.jsx(ft.Dock,{className:"h-4 w-4"}):d.jsx(ft.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(ee,{children:J?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ar:Ua,"aria-label":J?jt?"Maximize":"Minimize":"Close sidebar",children:J?jt?d.jsx(ft.Maximize2,{className:"h-4 w-4"}):d.jsx(ft.Minimize2,{className:"h-4 w-4"}):d.jsx(ft.X,{className:"h-4 w-4"})})}),d.jsx(ee,{children:J?jt?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!jt&&d.jsxs(d.Fragment,{children:[j&&q.length>0&&d.jsxs("div",{className:`border-b border-border ${X?"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(Vn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{X||Xn(),Q(!X)},children:X?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${X?"flex-1 overflow-y-auto":""}`,children:q.slice(0,X?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs("button",{type:"button",className:mt(pe({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Fa(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:Ia(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:w=>{w.stopPropagation(),La(p._id)},"aria-label":"Delete conversation",children:d.jsx(ft.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:Zt.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?"}),N.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:[(B?N:N.slice(0,10)).map(p=>d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{We(p.sampleUsage),Gt.current?.focus()},children:p.friendlyName})}),d.jsx(ee,{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)),N.length>10&&!B&&d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsxs(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>z(!0),children:["+",N.length-10," more"]})}),d.jsx(ee,{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:N.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"})]})})]}),B&&N.length>10&&d.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>z(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[Zt.map(p=>{const D=p.parts.filter(A=>A.type==="text").map(A=>A.text).join("");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(Kh,{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:D}):d.jsx("div",{className:"space-y-2",children:p.parts.map((A,V)=>{if(A.type?.startsWith("tool-")){const I=A.type?.replace("tool-","")||"",K=yn.find(H=>H.name===I),$=A.state==="input-available",G=A.state==="output-available";if($&&Xe.has(I),$){if(Xe.has(I))return null;const H=ds(A.input);return d.jsx(Pn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(Xh,{toolName:I,description:K?.description||"",args:H,onApprove:async()=>{if(Ke.has(A.toolCallId))return;Yt(_=>new Set(_).add(A.toolCallId));const U=xn.get(I);if(U)try{const _=await U(...Object.values(H));fe({toolCallId:A.toolCallId,tool:I,output:_})}catch(_){fe({toolCallId:A.toolCallId,tool:I,output:`Error: ${_}`})}},onDeny:async()=>{Ke.has(A.toolCallId)||(Yt(U=>new Set(U).add(A.toolCallId)),fe({toolCallId:A.toolCallId,tool:I,output:"User denied tool execution"}))}})},`${A.toolCallId}-${V}`)}else if(G){const H=A.output==="User denied tool execution",U=ds(A.input);return d.jsx(Gh,{toolName:I,args:U,isDenied:H,isSafe:Xe.has(I)},`${A.toolCallId}-${V}`)}return null}if(A.type==="text"&&A.text&&mn){const{processedText:I,citations:K,citationMap:$,groupedCitations:G,referencesText:H}=hf(A.text);return d.jsx(lf,{text:I,citations:K,citationMap:$,groupedCitations:G,referencesText:H,ResponseComponent:mn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:R},`${p.id}-${V}`)}return A.type==="reasoning"&&A.text?d.jsxs(Na,{className:"w-full",isStreaming:Bt==="streaming"&&V===p.parts.length-1&&p.id===Zt.at(-1)?.id,children:[d.jsx(Va,{}),d.jsx(Ra,{children:A.text})]},`${p.id}-${V}`):null})})})},p.id)}),d.jsx("div",{ref:Xt})]})}),Tr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Tr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(fu,{mode:"wait",children:(Bt==="streaming"||Bt==="submitted")&&d.jsxs(Pn,{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(Pn,{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:Kn})]})}),d.jsxs("form",{onSubmit:Sr,className:"relative",children:[d.jsx(Hi,{ref:Gt,value:Ae,onChange:Wa,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(),Sr(p))}}),Bt==="streaming"||Bt==="submitted"?d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:vn,children:d.jsx(ft.Square,{className:"h-4 w-4"})})}),d.jsxs(ee,{children:[d.jsx(jr,{children:"Escape"})," to stop"]})]}):d.jsxs(Qt,{children:[d.jsx(te,{asChild:!0,children:d.jsx("button",{type:"submit",className:mt(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Ae.trim(),children:d.jsx(ft.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(ee,{children:[d.jsx(jr,{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(ft.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 nn(t){if(typeof t=="string")try{const e=JSON.parse(t);return nn(e)}catch{return t}if(Array.isArray(t))return t.map(nn);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=nn(s);return e}return t}function mf(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return nn(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?nn(t):{}}function pf({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,initialState:h={},onToolCall:f,onFinish:g,sources:x,ragConfig:b,ragFilters:j}={}){const y=m.useMemo(()=>b!==void 0?b:j?{enabled:!0,filters:j}:x&&x.length>0?{enabled:!0,organizationId:x[0],autoExecute:!0,filters:void 0}:{enabled:!1},[x,b,j]),[v,T]=m.useState(n||null),S=m.useRef(n||null),[E,R]=m.useState(null),[C,k]=m.useState(null),W=m.useRef(null),[O,et]=m.useState([]),[Y,ct]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[yt,dt]=m.useState(!1),[Z,ot]=m.useState(new Set),[lt,tt]=m.useState(h),ht=m.useRef(h),[oe,_n]=m.useState(!1),[we,Vt]=m.useState(null),bt=m.useRef(!1),ae=m.useCallback(async(M,P=3)=>{if(!Y||!S.current)return;const N=async()=>{const B=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,z=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Y,updates:M},format:"json"})});if(!z.ok){if(z.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await z.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${z.status} ${q}`)}};for(let F=0;F<P;F++)try{await N(),Vt(null);return}catch(B){if(F===P-1){const q=B instanceof Error?B:new Error(String(B));throw Vt(q),console.error("Failed to sync state to Convex after retries:",B),q}await new Promise(q=>setTimeout(q,Math.pow(2,F)*100))}},[Y,t,S]),wt=m.useMemo(()=>function(){return ht.current},[]),Ft=m.useMemo(()=>async function(P){const N={...ht.current,...P};ht.current=N,tt(N);try{await ae(P)}catch(F){throw F}},[ae]),Rt=m.useMemo(()=>y?.enabled?async function(P,N=20,F){const B={...y.filters,...F};if(x&&x.length>1){const q=x.map(X=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...S.current?{Authorization:`Bearer ${S.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(N,100),organizationId:X,...Object.keys(B).length>0?{filters:B}:{}})}).then(Q=>Q.ok?Q.json():null)),xt=await Promise.all(q),nt=[];for(const X of xt)X?.candidates&&nt.push(...X.candidates);nt.sort((X,Q)=>{const Ce=X.scores?.rerank||X.scores?.dense||0;return(Q.scores?.rerank||Q.scores?.dense||0)-Ce});const Ct=nt.slice(0,N).map((X,Q)=>{const Ce=X.citation||X.url;return{rank:Q+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:Ce,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:P,total:nt.length,results:Ct,summary:`Found ${nt.length} relevant results across ${x.length} source(s) for "${P}". Top result: ${Ct[0]?.title||"N/A"}`}}const z=y.organizationId&&y.organizationId!=="default"?y.organizationId:x&&x.length>0?x[0]:void 0;try{const q={q:P,k:Math.min(N,100)};z&&(q.organizationId=z),Object.keys(B).length>0&&(q.filters=B);const xt={"Content-Type":"application/json"};S.current&&(xt.Authorization=`Bearer ${S.current}`);const nt=await fetch(`${t}/search`,{method:"POST",headers:xt,body:JSON.stringify(q)});if(!nt.ok){const Q=await nt.text();return{success:!1,error:`Search failed: ${nt.status} ${Q}`}}const Ct=await nt.json(),X=Ct.candidates.map((Q,Ce)=>{const le=Q.citation||Q.url;return{rank:Ce+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:le,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:Ct.query,total:Ct.total,results:X,summary:`Found ${Ct.total} relevant results for "${P}". Top result: ${X[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[y,t,S]),$t=m.useMemo(()=>y?.enabled?async function(P,N){const F=y.organizationId&&y.organizationId!=="default"?y.organizationId:x&&x.length>0?x[0]:void 0;try{const B={"Content-Type":"application/json"};S.current&&(B.Authorization=`Bearer ${S.current}`);const z=await fetch(`${t}/fetch`,{method:"POST",headers:B,body:JSON.stringify({doc_id:P,block_ids:N,...F?{organizationId:F}:{}})});if(!z.ok){const xt=await z.text();return{success:!1,error:`Fetch failed: ${z.status} ${xt}`}}const q=await z.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(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error occurred"}}}:null,[y,t,S]),ce=m.useMemo(()=>{const M=[...o,...i,wt,Ft];return y?.enabled&&(Rt&&M.push(Rt),$t&&M.push($t)),M},[o,i,wt,Ft,Rt,$t,y]),Pt=m.useMemo(()=>Ea(ce,a),[ce,a]),J=m.useMemo(()=>{const M=new Map,P=new Map(Pt.map(N=>[N.name,N]));return M.set("getState",wt),M.set("setState",Ft),y?.enabled&&(Rt&&M.set("searchDocs",Rt),$t&&M.set("fetchDocContent",$t)),ce.forEach(N=>{if(N===wt||N===Ft||N===Rt||N===$t)return;const F=N[zt];if(F){const z=P.get(F);if(z){M.set(z.name,N);return}}const B=Pt.find(z=>z.name===N.name);B&&M.set(B.name,N)}),M},[ce,Pt,wt,Ft,Rt,$t,y]),Te=m.useMemo(()=>new Set(Pt.map(M=>M.name)),[Pt]),jt=m.useMemo(()=>{const M=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}},{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"]}}],P=[];return y?.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"]}}),[...Pt,...M,...P]},[Pt,y]),Ht=m.useMemo(()=>jt.filter(M=>M.name==="getState"||M.name==="setState"?!0:Te.has(M.name)),[jt,Te]),Tt=m.useMemo(()=>{const M=new Set;return M.add("getState"),M.add("setState"),y?.enabled&&y.autoExecute!==!1&&(M.add("searchDocs"),M.add("fetchDocContent")),i.forEach(P=>{for(const[N,F]of J.entries())if(F===P){M.add(N);break}}),M},[i,J,y]);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 N=await P.json();T(N.clientToken),S.current=N.clientToken,k(N.expiresAt),R(null)}catch(P){console.error("[useAgent] Token fetch failed:",P),R(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{W.current&&clearTimeout(W.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!C||s||n)return;W.current&&clearTimeout(W.current);const M=Math.floor(Date.now()/1e3),P=C-M,F=Math.max(0,P-5);return W.current=setTimeout(async()=>{try{const B=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!B.ok)throw new Error("Failed to refresh token");const z=await B.json();T(z.clientToken),S.current=z.clientToken,k(z.expiresAt),R(null)}catch(B){console.error("[useAgent] Token refresh failed:",B),R(B instanceof Error?B.message:"Failed to refresh token")}},F*1e3),()=>{W.current&&clearTimeout(W.current)}},[C,e,JSON.stringify(r),s,n]);const Be=async(M,P={})=>{const N=P.headers?new Headers(P.headers):new Headers;N.delete("user-agent"),N.delete("User-Agent"),console.log("[useAgent] Making request to:",M),console.log("[useAgent] Method:",P.method||"GET"),console.log("[useAgent] Has Authorization header:",N.has("Authorization")),console.log("[useAgent] Client token available:",!!S.current);try{const F=await fetch(M,{...P,headers:N});if(!F.ok){console.error("[useAgent] Request failed:",F.status,F.statusText);const B=await F.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",B)}return F}catch(F){throw console.error("[useAgent] Fetch error:",F),F}},ze=`${t}/chat`;console.log("[useAgent] Chat API URL:",ze);const{messages:kt,sendMessage:Ue,status:Se,error:_e,stop:Wn,addToolResult:Xt,setMessages:Gt}=Wi.useChat({id:Y||void 0,messages:u,transport:new Nn.DefaultChatTransport({api:ze,fetch:Be,headers:()=>{const M={};return S.current?(M.Authorization=`Bearer ${S.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),M},body:()=>{const M=Ht.map(N=>({name:N.name,description:N.description,inputSchema:N.jsonSchema})),P=M.filter(N=>N.name==="getState"||N.name==="setState").map(N=>N.name);return P.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",P),{tools:M,systemPrompt:c,state:ht.current,...j&&{ragFilters:j}}}}),sendAutomaticallyWhen:Nn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{kt.forEach(M=>{M.role==="assistant"&&M.parts.forEach(P=>{if(!P.type?.startsWith("tool-")||P.state!=="input-available")return;const N=P.type.replace("tool-",""),F=P.toolCallId;if(Z.has(F))return;ot(z=>new Set(z).add(F));const B=mf(P.input);if(Tt.has(N)){const z=J.get(N);z?(async()=>{try{const q=Ht.find(nt=>nt.name===N);let xt;if(q&&q.jsonSchema?.properties){const Ct=Object.keys(q.jsonSchema.properties).map(X=>B[X]);xt=await z(...Ct)}else if(N==="getState")xt=z();else if(N==="setState"){const nt=B.updates||B;xt=await z(nt)}else xt=await z(...Object.values(B));Xt({toolCallId:F,tool:N,output:xt})}catch(q){console.error(`[useAgent] Error executing tool ${N}:`,q),Xt({toolCallId:F,tool:N,output:`Error: ${q}`})}})():console.warn(`[useAgent] Tool ${N} not found in toolsMap`)}else f&&f({toolCall:{toolCallId:F,toolName:N,args:B}})})})},[kt,Tt,J,f,Xt,Z,Ft,Ht]),m.useEffect(()=>{if(Se==="ready"&&kt.length>0&&g){const M=kt[kt.length-1];M&&M.role==="assistant"&&g({message:M,messages:kt,isAbort:!1,isDisconnect:!1,isError:!!_e})}},[Se,kt,_e,g]);async function Ae(){if(!(!r?.id||!v)){dt(!0);try{const P=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${v}`}})).json();et(P.conversations||[])}catch(M){console.error("Failed to fetch conversations:",M)}finally{dt(!1)}}}m.useEffect(()=>{r?.id&&v&&Ae()},[JSON.stringify(r),v,t]),m.useEffect(()=>{if(!Y||!S.current)return;(async()=>{_n(!0),Vt(null);try{const P=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Y},format:"json"})});if(!P.ok){const q=await P.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${P.status} ${q}`)}const F=(await P.json())?.value||{},B=!bt.current;let z;B?(z={...h,...F},bt.current=!0):z=F,ht.current=z,tt(z)}catch(P){console.error("Failed to fetch state:",P);const N=P instanceof Error?P:new Error(String(P));Vt(N),bt.current||(ht.current=h,tt(h),bt.current=!0)}finally{_n(!1)}})()},[Y,t]);async function We(M){ct(M),dt(!0);try{const P=await fetch(`${t}/conversations/${M}/messages`,{headers:{Authorization:`Bearer ${S.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const F=(await P.json()).messages||[];Gt(F)}catch(P){console.error("Failed to load conversation messages:",P)}finally{dt(!1)}}async function mn(M){if(v)try{await fetch(`${t}/conversations/${M}`,{method:"DELETE",headers:{Authorization:`Bearer ${v}`}}),et(O.filter(P=>P._id!==M)),M===Y&&pn()}catch(P){console.error("Failed to delete conversation:",P)}}function pn(){const M=crypto.randomUUID();ct(M),Gt([]),ot(new Set),ht.current=h,tt(h),bt.current=!1}function Kn(M){Xt(M)}async function qn(M){const P={...ht.current,...M};ht.current=P,tt(P);try{await ae(M)}catch(N){throw N}}async function Ke(){if(!r?.id||!S.current)throw new Error("User authentication required to share state");const M=`shared_${crypto.randomUUID()}`;try{return await fetch(`${t.replace("/chat","")}/convex/api/mutation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.current}`},body:JSON.stringify({path:"sharedStates:create",args:{stateId:M,state:ht.current,projectId:"default",createdBy:r.id},format:"json"})}),M}catch(P){throw console.error("Failed to share state:",P),P}}async function Yt(M){if(!S.current)throw new Error("Authentication required to import state");try{const P=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.current}`},body:JSON.stringify({path:"sharedStates:getByStateId",args:{stateId:M},format:"json"})});if(!P.ok)throw new Error("Failed to fetch shared state");const F=(await P.json())?.value||{};ht.current=F,tt(F)}catch(P){throw console.error("Failed to import state:",P),P}}return{id:Y,messages:kt,status:Se,error:_e,sendMessage:Ue,stop:Wn,addToolOutput:Kn,setMessages:Gt,conversations:O,loadConversation:We,deleteConversation:mn,startNewConversation:pn,isLoadingConversations:yt,clientToken:v,tokenError:E,state:lt,setState:qn,shareState:Ke,importState:Yt,isStateLoading:oe,stateError:we}}exports.verifyToken=ac.verifyToken;exports.ARCTEN_ORIGINAL_NAME=zt;exports.ArctenAgent=ff;exports.preserveToolName=qh;exports.useAgent=pf;
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=Gh(o,n,r,s);if(!i){const a=o.name,u=o[Be]||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 Xh({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return h.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:h.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&h.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),h.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.jsxs(Rn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(fe.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Rn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:h.jsx(fe.X,{className:"h-3 w-3"})})]})]})})}function Yh({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=m.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))),c=Object.keys(a).length>0;return h.jsxs("div",{className:"my-1",children:[h.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&h.jsx("span",{className:"transition-transform duration-200",children:r?h.jsx(fe.ChevronDown,{className:"h-3 w-3"}):h.jsx(fe.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(fe.X,{className:"h-3 w-3"}):s?h.jsx(fe.Zap,{className:"h-3 w-3"}):h.jsx(fe.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&c&&h.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:h.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function Jh({...e}){return h.jsx(Ls.Root,{"data-slot":"collapsible",...e})}function Zh({...e}){return h.jsx(Ls.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Qh({...e}){return h.jsx(Ls.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const ef=m.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),vr=m.memo(({className:e,...t})=>typeof window>"u"?null:h.jsx(m.Suspense,{fallback:null,children:h.jsx(ef,{className:me("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);vr.displayName="Response";const tf=Object.freeze(Object.defineProperty({__proto__:null,Response:vr},Symbol.toStringTag,{value:"Module"})),nf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Wh.create(t),i=m.useMemo(()=>(e?.length??0)*r,[e,r]);return h.jsx(o,{animate:{backgroundPosition:"0% center"},className:me("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})},sf=m.memo(nf),Na=m.createContext(null),rf=()=>{const e=m.useContext(Na);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},of=1e3,af=1e3,Va=m.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=jr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,f]=jr.useControllableState({prop:o,defaultProp:0}),[d,g]=m.useState(!1),[b,x]=m.useState(null);m.useEffect(()=>{t?b===null&&x(Date.now()):b!==null&&(f(Math.ceil((Date.now()-b)/af)),x(null))},[t,b,f]),m.useEffect(()=>{if(s&&!t&&c&&!d){const T=setTimeout(()=>{u(!1),g(!0)},of);return()=>clearTimeout(T)}},[t,c,s,u,d]);const S=T=>{u(T)};return h.jsx(Na.Provider,{value:{isStreaming:t,isOpen:c,setIsOpen:u,duration:l},children:h.jsx(Jh,{className:me("not-prose mb-4",e),onOpenChange:S,open:c,...a,children:i})})}),cf=(e,t)=>e||t===0?h.jsx(sf,{duration:1,children:"Thinking..."}):t===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",t," seconds"]}),Ra=m.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=rf();return h.jsx(Zh,{className:me("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??h.jsxs(h.Fragment,{children:[h.jsx(fe.BrainIcon,{className:"size-4"}),cf(s,o),h.jsx(fe.ChevronDownIcon,{className:me("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ia=m.memo(({className:e,children:t,...n})=>h.jsx(Qh,{className:me("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:h.jsx(vr,{className:"grid gap-2",children:t})}));Va.displayName="Reasoning";Ra.displayName="ReasoningTrigger";Ia.displayName="ReasoningContent";function Wi(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function lf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=Wi(s.domain);return h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsxs("button",{className:me("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:[h.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),h.jsx("span",{className:"leading-none",children:s.domain})]})}),h.jsx(rt,{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:h.jsxs("div",{className:"space-y-1.5",children:[h.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=>h.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:me("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:i=>i.stopPropagation(),children:[h.jsx("img",{src:Wi(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),h.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function uf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0}){const c=m.useRef(null),[u,l]=m.useState([]);m.useEffect(()=>{if(!a||!c.current||t.length===0||n.size===0){(n.size===0||!a)&&l([]);return}const d=c.current;let g,b=!1;const x=new WeakSet,S=()=>{if(!c.current||b)return;b=!0;const v=c.current,y=/\[(\d+)\]/g,N=document.createTreeWalker(v,NodeFilter.SHOW_TEXT,null),M=[];let k;for(;k=N.nextNode();)if(k.nodeType===Node.TEXT_NODE&&!x.has(k)){const j=k,q=j.textContent||"";let L=j.parentElement,Y=!1;for(;L&&L!==v;){if(L.tagName==="A"||L.tagName==="CODE"||L.tagName==="PRE"){Y=!0;break}L=L.parentElement}if(!Y){const de=Array.from(q.matchAll(y)).filter(re=>{if(!re[1])return!1;const pe=parseInt(re[1],10);return n.has(pe)});de.length>0&&M.push({node:j,matches:de})}}if(M.length===0){b=!1;return}const P=[];M.forEach(({node:j,matches:q})=>{x.add(j);const L=j.textContent||"",Y=document.createDocumentFragment();let se=0;q.forEach(de=>{if(!de[1])return;de.index!==void 0&&de.index>se&&Y.appendChild(document.createTextNode(L.slice(se,de.index)));const re=document.createElement("span");re.className="inline-flex items-center citation-button-container";const pe=parseInt(de[1],10);re.setAttribute("data-citation",de[1]),Y.appendChild(re),P.push({element:re,citationNum:pe}),se=(de.index||0)+de[0].length}),se<L.length&&Y.appendChild(document.createTextNode(L.slice(se))),j.parentNode&&j.parentNode.replaceChild(Y,j)}),P.length>0&&l(j=>{const q=new Set(j.map(se=>se.element)),L=j.filter(se=>se.element.isConnected),Y=P.filter(se=>!q.has(se.element));return[...L,...Y]}),b=!1},T=new MutationObserver(()=>{clearTimeout(g),g=setTimeout(S,100)});return T.observe(d,{childList:!0,subtree:!0,characterData:!0}),g=setTimeout(S,200),()=>{T.disconnect(),clearTimeout(g)}},[e,t,n,a]);const f=a&&(s||r)?h.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[h.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-2",children:"References"}),h.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:s&&s.length>0?s.map((d,g)=>{const b=d.numbers[0],x=d.anchor?`${d.baseUrl}#${d.anchor}`:d.url,S=d.anchor&&d.url!==x;return h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium whitespace-nowrap",children:["[",b,"]"]}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("a",{href:d.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:d.baseUrl}),S&&h.jsxs("span",{className:"text-stone-500 dark:text-stone-500 ml-1",children:["#",d.anchor]})]})]},`group-${g}`)}):Array.from(n.entries()).sort(([d],[g])=>d-g).map(([d,g])=>h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium",children:["[",d,"]"]}),h.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:g})]},d))})]}):null;return h.jsxs("div",{className:i,children:[h.jsx("div",{ref:c,children:h.jsx(o,{children:e})}),a&&u.filter(({element:d})=>d.isConnected).map(({element:d,citationNum:g},b)=>{if(!t.find(T=>T.number===g))return null;const S=Array.from(new Map(t.map(T=>[T.url.replace(/\/+$/,""),{number:T.number,url:T.url,domain:df(T.url)}])).values());return ac.createPortal(h.jsx(lf,{sources:S,citationNumber:g},`citation-${g}-${d}`),d,`citation-${g}-${b}`)}),f]})}function df(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}function hf(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 ff(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,c=new Map,u=new Map;if(s&&s[1]){const v=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let N;for(;(N=y.exec(v))!==null;)if(N[1]&&N[2]){const M=parseInt(N[1],10),k=N[2].replace(/[.,;:!?]+$/,""),P=k.replace(/\/+$/,"");if(a.has(P)||a.set(P,k),i.has(P)||i.set(P,[]),i.get(P).push(M),!c.has(P))c.set(P,M);else{const j=c.get(P);M<j&&c.set(P,M)}}for(const[M,k]of i.entries()){const P=c.get(M);for(const j of k)j!==P&&u.set(j,P)}for(const[M,k]of c.entries()){const P=a.get(M)||M;r.set(k,P),o.push({number:k,url:P})}}let l,f=t;s&&s[0]&&(l=s[0],f=t.replace(n,""));const d=[];let g=0;const b=/```[\s\S]*?```|`[^`]+`/g;let x;for(;(x=b.exec(f))!==null;)x.index>g&&d.push({type:"text",content:f.slice(g,x.index),start:g,end:x.index}),d.push({type:"code",content:x[0],start:x.index,end:x.index+x[0].length}),g=x.index+x[0].length;g<f.length&&d.push({type:"text",content:f.slice(g),start:g,end:f.length});const S=d.map(v=>{if(v.type==="code")return v.content;let y=v.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(M,k,P)=>{const j=parseInt(k,10),q=P.replace(/\/+$/,""),L=u.get(j)||j;return c.has(q)||(c.set(q,L),r.has(L)||(r.set(L,P),o.push({number:L,url:P}))),`[${L}]`}),y=y.replace(/\[(\d+)\]/g,(M,k)=>{const P=parseInt(k,10);return`[${u.get(P)||P}]`}),y}),T=[];for(const[v,y]of c.entries()){const N=a.get(v)||v,{baseUrl:M,anchor:k}=hf(N);T.push({url:N,baseUrl:M,numbers:[y],anchor:k})}return T.sort((v,y)=>(v.numbers[0]||0)-(y.numbers[0]||0)),{processedText:S.join(""),citations:o.sort((v,y)=>v.number-y.number),citationMap:r,groupedCitations:T,referencesText:l}}function sn(e){if(typeof e=="string")try{const t=JSON.parse(e);return sn(t)}catch{return e}if(Array.isArray(e))return e.map(sn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=sn(s);return t}return e}function hs(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return sn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?sn(e):{}}function mf({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:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:f=[],toolMetadata:d,systemPrompt:g="",tokenEndpoint:b="/api/arcten/token",apiBaseUrl:x="https://api.arcten.com",user:S,state:T,onStateChange:v,allowStateEdits:y=!0,sources:N,ragConfig:M,showCitations:k=!0}){const P=m.useMemo(()=>M!==void 0?M:N&&N.length>0?{enabled:!0,organizationId:N[0],autoExecute:!0,filters:void 0}:{enabled:!1},[N,M]),[j,q]=m.useState(null),L=m.useRef(null),[Y,se]=m.useState(null),[de,re]=m.useState(null),pe=m.useRef(null),Q=T!==void 0,[te,le]=m.useState({}),ae=m.useRef({});Q&&T?ae.current=T:Q||(ae.current=te);const[J,He]=m.useState(!1),[St,ge]=m.useState(null),Ge=m.useRef(!1),[Oe,At]=m.useState(u),[Le,Xe]=m.useState(i),[Ye,Pt]=m.useState(600),[Je,De]=m.useState(!1),[G,Ne]=m.useState(!1),[Te,Ce]=m.useState(!1),[xe,Ct]=m.useState({x:100,y:100}),[_t,lt]=m.useState(!1),[jt,gn]=m.useState({x:0,y:0}),[yn,Fe]=m.useState(!1),Wt=m.useRef(null),Ze=m.useRef(null),[Qe,Kt]=m.useState(""),[ut,qt]=m.useState(null),[Wn,Kn]=m.useState("Thinking..."),[Ht,Ue]=m.useState(new Set),[qn,Hn]=m.useState(""),[C,E]=m.useState([]),[I,O]=m.useState(!1),[B,H]=m.useState([]),[_,ve]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ce,Se]=m.useState(!1),[ee,Z]=m.useState(!1),[kt,dt]=m.useState([]),br=m.useCallback(async(p,w=3)=>{if(!_||!L.current)return;const D=async()=>{const V=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:_,updates:p},format:"json"})});if(!R.ok){if(R.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const W=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${W}`)}};for(let A=0;A<w;A++)try{await D(),ge(null);return}catch(V){if(A===w-1){const W=V instanceof Error?V:new Error(String(V));throw ge(W),console.error("Failed to sync state to Convex after retries:",V),W}await new Promise(W=>setTimeout(W,Math.pow(2,A)*100))}},[_,x,L]),Gt=m.useMemo(()=>function(){return ae.current},[]),Xt=m.useMemo(()=>async function(w){const D={...ae.current,...w};ae.current=D,Q||le(D),v&&v(D);try{await br(w)}catch(A){throw A}},[br,v,Q]);m.useEffect(()=>{Q&&T&&(ae.current=T)},[Q,T]);const ht=m.useMemo(()=>P?.enabled?async function(w,D=20,A){if(N&&N.length>1){const W=N.map(z=>fetch(`${x}/search`,{method:"POST",headers:{"Content-Type":"application/json",...L.current?{Authorization:`Bearer ${L.current}`}:{}},body:JSON.stringify({q:w,k:Math.min(D,100),organizationId:z,...Object.keys(R).length>0?{filters:R}:{}})}).then(U=>U.ok?U.json():null)),$=await Promise.all(W),X=[];for(const z of $)z?.candidates&&X.push(...z.candidates);X.sort((z,U)=>{const Ae=z.scores?.rerank||z.scores?.dense||0;return(U.scores?.rerank||U.scores?.dense||0)-Ae});const K=X.slice(0,D).map((z,U)=>{const Ae=z.citation||z.url;return{rank:U+1,doc_id:z.doc_id,block_id:z.block_id,url:z.url,citation:Ae,title:z.title||"Untitled",snippet:z.snippet,score:z.scores?.rerank||z.scores?.dense||0,metadata:{site:z.metadata?.site,lang:z.metadata?.lang,contentType:z.metadata?.content_type}}});return{success:!0,query:w,total:X.length,results:K,summary:`Found ${X.length} relevant results across ${N.length} source(s) for "${w}". Top result: ${K[0]?.title||"N/A"}`}}const V=P.organizationId&&P.organizationId!=="default"?P.organizationId:void 0,R={...P.filters,...A};try{const W={q:w,k:Math.min(D,100)};V&&(W.organizationId=V),Object.keys(R).length>0&&(W.filters=R);const $={"Content-Type":"application/json"};L.current&&($.Authorization=`Bearer ${L.current}`);const X=await fetch(`${x}/search`,{method:"POST",headers:$,body:JSON.stringify(W)});if(!X.ok){const U=await X.text();return{success:!1,error:`Search failed: ${X.status} ${U}`}}const K=await X.json(),z=K.candidates.map((U,Ae)=>{const Tn=U.citation||U.url;return{rank:Ae+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:Tn,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:K.query,total:K.total,results:z,summary:`Found ${K.total} relevant results for "${w}". Top result: ${z[0]?.title||"N/A"}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[M,x,L]),ft=m.useMemo(()=>P?.enabled?async function(w,D){const A=P.organizationId&&P.organizationId!=="default"?P.organizationId:N&&N.length>0?N[0]:void 0;try{const V={"Content-Type":"application/json"};L.current&&(V.Authorization=`Bearer ${L.current}`);const R=await fetch(`${x}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:w,block_ids:D,...A?{organizationId:A}:{}})});if(!R.ok){const $=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${$}`}}const W=await R.json();return{success:!0,blocks:W.blocks||[],fullContent:W.fullContent||"",pageUrl:W.pageUrl||"",pageTitle:W.pageTitle||"",summary:`Fetched ${W.blocks?.length||0} blocks from ${W.pageTitle||w}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[M,x,L]),mt=m.useMemo(()=>{const p=[...l,...f,Gt];return(!Q||y)&&p.push(Xt),P?.enabled&&(ht&&p.push(ht),ft&&p.push(ft)),p},[l,f,Gt,Xt,ht,ft,Q,y,P]),Gn=m.useMemo(()=>Da(mt,d),[mt,d]),_e=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:[]}}];(!Q||y)&&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 w=[];return P?.enabled&&w.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"]}}),[...Gn,...p,...w]},[Gn,Q,y,P]),wr=m.useMemo(()=>new Set(_e.map(p=>p.name)),[_e]),xn=m.useMemo(()=>_e.filter(p=>p.name==="getState"?!0:p.name==="setState"?!Q||y:wr.has(p.name)),[_e,wr,Q,y]),vn=m.useMemo(()=>{const p=new Map,w=new Map(Gn.map(D=>[D.name,D]));return p.set("getState",Gt),(!Q||y)&&p.set("setState",Xt),P?.enabled&&(ht&&p.set("searchDocs",ht),ft&&p.set("fetchDocContent",ft)),mt.forEach(D=>{if(D===Gt||D===Xt||D===ht||D===ft)return;const A=D[Be];if(A){const R=w.get(A);if(R){p.set(R.name,D);return}}const V=_e.find(R=>R.name===D.name);V&&p.set(V.name,D)}),p},[mt,_e,Gt,Xt,ht,ft,Q,y,P]),Yt=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),P?.enabled&&P.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const w=new Map(_e.map(D=>[D.name,D]));return f.forEach(D=>{const A=D[Be];if(A&&w.has(A))p.add(A);else{const V=_e.find(R=>R.name===D.name);V&&p.add(V.name)}}),p},[f,_e,P]),Tr=["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&&At(JSON.parse(p));const w=localStorage.getItem("arcten-sidebar-width");w&&Xe(parseInt(w));const D=localStorage.getItem("arcten-sidebar-height");D&&Pt(parseInt(D));const A=localStorage.getItem("arcten-sidebar-detached");A&&Ne(JSON.parse(A));const V=localStorage.getItem("arcten-sidebar-position");if(V){const W=JSON.parse(V),$=50,X=Math.max($-i,Math.min(W.x,window.innerWidth-$)),K=Math.max(0,Math.min(W.y,window.innerHeight-$));Ct({x:X,y:K})}const R=localStorage.getItem("arcten-sidebar-minimized");R&&Ce(JSON.parse(R)),Fe(!0)}},[]);const et=m.useMemo(()=>S,[S?.id]);m.useEffect(()=>((async()=>{try{const w=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:et})});if(!w.ok)throw new Error("Failed to fetch token");const D=await w.json();q(D.clientToken),L.current=D.clientToken,re(D.expiresAt),se(null)}catch(w){se(w instanceof Error?w.message:"Failed to fetch token")}})(),()=>{pe.current&&clearTimeout(pe.current)}),[b,et]),m.useEffect(()=>{if(!de)return;pe.current&&clearTimeout(pe.current);const p=Math.floor(Date.now()/1e3),w=de-p,A=Math.max(0,w-5);return pe.current=setTimeout(async()=>{try{const V=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:et})});if(!V.ok)throw new Error("Failed to refresh token");const R=await V.json();q(R.clientToken),L.current=R.clientToken,re(R.expiresAt),se(null)}catch(V){console.error("Token refresh failed:",V),se(V instanceof Error?V.message:"Failed to refresh token")}},A*1e3),()=>{pe.current&&clearTimeout(pe.current)}},[de,b,et]),m.useEffect(()=>{(async()=>{if(mt.length!==0)try{const w=mt.map(A=>({name:A.name,code:A.toString()})),D=await fetch(`${x}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:w})});if(D.ok){const A=await D.json();E(A.tools)}}catch(w){console.error("Failed to fetch tool descriptions:",w)}})()},[mt]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{qt(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Hn(window.location.pathname)};p(),window.addEventListener("popstate",p);const w=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(w)}},[]);const Xn=m.useCallback(async()=>{if(!(!et?.id||!j)){Z(!0);try{const w=await(await fetch(`${x}/conversations`,{headers:{Authorization:`Bearer ${j}`}})).json();H(w.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{Z(!1)}}},[et?.id,j,x]);m.useEffect(()=>{et?.id&&j&&Xn()},[et?.id,j,Xn]);function Oa(p){const w=Math.floor((Date.now()-p)/1e3);return w<60?"now":w<3600?`${Math.floor(w/60)}m`:w<86400?`${Math.floor(w/3600)}h`:`${Math.floor(w/86400)}d`}function La(){const p=crypto.randomUUID();ve(p),wn([]),dt([]),Se(!1);const w=Q?T||{}:{};ae.current=w,Q||le(w),v&&v(w),Ge.current=!1}async function Fa(p){if(j)try{await fetch(`${x}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${j}`}}),H(B.filter(w=>w._id!==p)),p===_&&La()}catch(w){console.error("Failed to delete conversation:",w)}}async function $a(p){ve(p.chatId),Se(!1),Z(!0);try{const w=await fetch(`${x}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${L.current}`}});if(!w.ok)throw new Error(`Failed to fetch messages: ${w.statusText}`);const A=(await w.json()).messages||[];wn(A),dt(A)}catch(w){console.error("Failed to load conversation messages:",w);const D=p.messages||[];wn(D),dt(D)}finally{Z(!1)}}const Ba=async(p,w={})=>{const D=w.headers?new Headers(w.headers):new Headers;return D.delete("user-agent"),D.delete("User-Agent"),fetch(p,{...w,headers:D})},{messages:tt,sendMessage:za,status:$e,error:Sr,stop:bn,addToolResult:pt,setMessages:wn}=Ki.useChat({id:_||void 0,transport:new Vn.DefaultChatTransport({api:`${x}/chat`,fetch:Ba,headers:()=>{const p={};return L.current&&(p.Authorization=`Bearer ${L.current}`),p},body:()=>({tools:xn.map(w=>({name:w.name,description:w.description,inputSchema:w.jsonSchema})),systemPrompt:g,currentRoute:qn,state:ae.current})}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=tt[tt.length-1];if(!p||p.role!=="assistant")return;const w=p.parts?.filter(D=>D.type?.startsWith("tool-")&&D.state==="input-available"&&typeof D.toolCallId=="string"&&D.input!==void 0)||[];for(const D of w){const A=D,V=A.type?.replace("tool-","")||"",R=A.toolCallId;if(Yt.has(V)){if(Ht.has(R))continue;Ue($=>$.has(R)?$:new Set($).add(R)),(async()=>{try{const $=vn.get(V);if(!$){console.warn(`[ArctenAgent] Tool ${V} not found in toolsMap. Available tools:`,Array.from(vn.keys())),pt({toolCallId:R,tool:V,output:`Error: Tool ${V} not found`}),Ue(U=>{const Ae=new Set(U);return Ae.delete(R),Ae});return}const X=hs(A.input),K=xn.find(U=>U.name===V);let z;if(K&&K.jsonSchema?.properties){const Ae=Object.keys(K.jsonSchema.properties).map(Tn=>X[Tn]);console.log(`[ArctenAgent] Executing safe tool ${V} with args:`,Ae),z=await $(...Ae)}else if(V==="getState")z=$();else if(V==="setState"){const U=X.updates||X;z=await $(U)}else z=await $(...Object.values(X));console.log(`[ArctenAgent] Tool ${V} completed, result:`,z),pt({toolCallId:R,tool:V,output:z}),Ue(U=>{const Ae=new Set(U);return Ae.delete(R),Ae})}catch($){console.error(`[ArctenAgent] Error executing safe tool ${V}:`,$),pt({toolCallId:R,tool:V,output:`Error: ${$ instanceof Error?$.message:String($)}`}),Ue(X=>{const K=new Set(X);return K.delete(R),K})}})()}}},[tt,Yt,vn,xn,pt]),m.useEffect(()=>{if(!_||!L.current)return;(async()=>{He(!0),ge(null);try{const D=`${x.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,A=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:_},format:"json"})});if(!A.ok){if(A.status===404||A.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${A.status}), using empty state`);const K=Q?T||{}:{};ae.current=K,Q||le(K),v&&v(K),Ge.current=!0,He(!1);return}const X=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${X}`)}const R=(await A.json())?.value||{},W=!Ge.current;let $;W?($={...Q?T||{}:{},...R},Ge.current=!0):$=R,ae.current=$,Q||le($),v&&v($)}catch(w){w instanceof TypeError&&w.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",w):console.error("[ArctenAgent] Failed to fetch state:",w);const A=w instanceof Error?w:new Error(String(w));if(ge(A),!Ge.current){const V=Q?T||{}:{};ae.current=V,Q||le(V),v&&v(V),Ge.current=!0}}finally{He(!1)}})()},[_,x,Q,T,v]),m.useEffect(()=>{Oe&&Ze.current&&Ze.current.focus()},[Oe,tt]);function Ua(){At(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function _a(){At(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Oe]),m.useEffect(()=>{Wt.current&&Wt.current.scrollIntoView({behavior:"smooth"})},[tt]),m.useEffect(()=>{function p(w){w.key==="Escape"&&($e==="streaming"||$e==="submitted")&&(w.preventDefault(),bn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[$e,bn]);function Wa(){const p=crypto.randomUUID();ve(p),wn([]),dt([]),Se(!1)}function Ar(p){if(p.preventDefault(),!Qe.trim())return;($e==="streaming"||$e==="submitted")&&bn();const w=Tr[Math.floor(Math.random()*Tr.length)]||"Thinking...";Kn(w),za({text:Qe}),Kt("")}function Ka(p){const w=p.target.value;Kt(w)}m.useEffect(()=>{if(!Je)return;function p(D){if(G){const A=D.clientX-xe.x,V=D.clientY-xe.y;A>=a&&A<=c&&Xe(A),V>=400&&V<=1e3&&Pt(V)}else{const A=window.innerWidth-D.clientX;A>=a&&A<=c&&Xe(A)}}function w(){De(!1),localStorage.setItem("arcten-sidebar-width",Le.toString()),localStorage.setItem("arcten-sidebar-height",Ye.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[Je,Le,Ye,G,xe,a,c]);function qa(p){p.preventDefault(),De(!0)}function Ha(){Ne(!0),Ce(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ga(){Ne(!1),Ce(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Pr(){Ce(!Te),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Te))}function Xa(p){G&&(lt(!0),gn({x:p.clientX-xe.x,y:p.clientY-xe.y}))}return m.useEffect(()=>{if(!G)return;function p(){Ct(w=>{const A=window.innerWidth-50,V=window.innerHeight-50,R=50-Le,W=0,$=Math.max(R,Math.min(w.x,A)),X=Math.max(W,Math.min(w.y,V));if($!==w.x||X!==w.y){const K={x:$,y:X};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(K)),K}return w})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[G,Le]),m.useEffect(()=>{if(!_t)return;function p(D){const A=D.clientX-jt.x,V=D.clientY-jt.y,R=50,W=window.innerWidth-R,$=window.innerHeight-R,X=R-Le,K=0,z=Math.max(X,Math.min(A,W)),U=Math.max(K,Math.min(V,$));Ct({x:z,y:U})}function w(){lt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(xe))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[_t,jt,xe,Le]),yn?Y?h.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:h.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",Y]})}):j?h.jsx(pu,{features:Kh,children:h.jsx(jn,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:G?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:G?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
+ ${G?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
+ ${Oe?"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
+ ${G?"border border-border":"border-l border-border"}
23
+ ${Oe?"":"w-[30px]"}
24
+ `,style:Oe?G?{width:`${Le}px`,height:Te?"auto":`${Ye}px`,left:`${xe.x}px`,top:`${xe.y}px`}:{width:`${Le}px`}:void 0,onClick:Oe?void 0:Ua,children:Oe?h.jsxs(h.Fragment,{children:[!G&&h.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:qa,children:h.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),G&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),De(!0)}}),h.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(),lt(!0),gn({x:p.clientX-xe.x,y:p.clientY-xe.y})},children:h.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"})}),h.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),De(!0)}})]}),h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${G?"cursor-move":""}`,onMouseDown:G?Xa:void 0,children:[h.jsx("h2",{className:`text-base font-semibold ${G&&Te?"cursor-pointer":""}`,onClick:G&&Te?p=>{p.stopPropagation(),Pr()}:void 0,children:r}),h.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx("button",{type:"button",className:me(yt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Wa,"aria-label":"New chat",children:h.jsx(fe.Plus,{className:"h-4 w-4"})})}),h.jsx(rt,{children:"Start a new conversation"})]}),h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx("button",{type:"button",className:me(yt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:G?Ga:Ha,"aria-label":G?"Dock sidebar":"Float sidebar",children:G?h.jsx(fe.Dock,{className:"h-4 w-4"}):h.jsx(fe.PictureInPicture2,{className:"h-4 w-4"})})}),h.jsx(rt,{children:G?"Dock to sidebar":"Undock to floating window"})]}),h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx("button",{type:"button",className:me(yt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:G?Pr:_a,"aria-label":G?Te?"Maximize":"Minimize":"Close sidebar",children:G?Te?h.jsx(fe.Maximize2,{className:"h-4 w-4"}):h.jsx(fe.Minimize2,{className:"h-4 w-4"}):h.jsx(fe.X,{className:"h-4 w-4"})})}),h.jsx(rt,{children:G?Te?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Te&&h.jsxs(h.Fragment,{children:[S&&B.length>0&&h.jsxs("div",{className:`border-b border-border ${ce?"flex flex-col flex-1":""}`,children:[h.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[h.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),h.jsx(Rn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ce||Xn(),Se(!ce)},children:ce?"Show less":"View all"})]}),h.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ce?"flex-1 overflow-y-auto":""}`,children:B.slice(0,ce?void 0:3).map(p=>h.jsxs("div",{className:"group relative",children:[h.jsxs("button",{type:"button",className:me(yt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>$a(p),children:[h.jsx("span",{className:"text-xs truncate",children:p.title}),h.jsx("div",{className:"ml-2 flex items-center",children:h.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Oa(p.updatedAt)})})]}),h.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:w=>{w.stopPropagation(),Fa(p._id)},"aria-label":"Delete conversation",children:h.jsx(fe.X,{className:"h-3 w-3"})})]},p._id))})]}),h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[h.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:tt.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&h.jsx("div",{className:"mb-6",children:o}),h.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),C.length>0&&h.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:h.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(I?C:C.slice(0,10)).map(p=>h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx(Yn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Kt(p.sampleUsage),Ze.current?.focus()},children:p.friendlyName})}),h.jsx(rt,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium",children:p.description}),h.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[h.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&h.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[h.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),C.length>10&&!I&&h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsxs(Yn,{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"]})}),h.jsx(rt,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),h.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:C.slice(10).map(p=>h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),h.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),h.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),I&&C.length>10&&h.jsx(Yn,{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"})]})})]}):h.jsxs(h.Fragment,{children:[tt.map(p=>{const D=p.parts.filter(A=>A.type==="text").map(A=>A.text).join("");return h.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:h.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?h.jsx(qh,{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:D}):h.jsx("div",{className:"space-y-2",children:p.parts.map((A,V)=>{if(A.type?.startsWith("tool-")){const R=A.type?.replace("tool-","")||"",W=xn.find(K=>K.name===R),$=A.state==="input-available",X=A.state==="output-available";if($&&Yt.has(R),$){if(Yt.has(R))return null;const K=hs(A.input);return h.jsx(jn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:h.jsx(Xh,{toolName:R,description:W?.description||"",args:K,onApprove:async()=>{if(Ht.has(A.toolCallId))return;Ue(U=>new Set(U).add(A.toolCallId));const z=vn.get(R);if(z)try{const U=await z(...Object.values(K));pt({toolCallId:A.toolCallId,tool:R,output:U})}catch(U){pt({toolCallId:A.toolCallId,tool:R,output:`Error: ${U}`})}},onDeny:async()=>{Ht.has(A.toolCallId)||(Ue(z=>new Set(z).add(A.toolCallId)),pt({toolCallId:A.toolCallId,tool:R,output:"User denied tool execution"}))}})},`${A.toolCallId}-${V}`)}else if(X){const K=A.output==="User denied tool execution",z=hs(A.input);return h.jsx(Yh,{toolName:R,args:z,isDenied:K,isSafe:Yt.has(R)},`${A.toolCallId}-${V}`)}return null}if(A.type==="text"&&A.text&&ut){const{processedText:R,citations:W,citationMap:$,groupedCitations:X,referencesText:K}=ff(A.text);return h.jsx(uf,{text:R,citations:W,citationMap:$,groupedCitations:X,referencesText:K,ResponseComponent:ut,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:k},`${p.id}-${V}`)}return A.type==="reasoning"&&A.text?h.jsxs(Va,{className:"w-full",isStreaming:$e==="streaming"&&V===p.parts.length-1&&p.id===tt.at(-1)?.id,children:[h.jsx(Ra,{}),h.jsx(Ia,{children:A.text})]},`${p.id}-${V}`):null})})})},p.id)}),h.jsx("div",{ref:Wt})]})}),Sr&&h.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Sr.message]}),h.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[h.jsx(mu,{mode:"wait",children:($e==="streaming"||$e==="submitted")&&h.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:[h.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]}}),h.jsx("p",{className:"text-xs text-muted-foreground",children:Wn})]})}),h.jsxs("form",{onSubmit:Ar,className:"relative",children:[h.jsx(Gi,{ref:Ze,value:Qe,onChange:Ka,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(),Ar(p))}}),$e==="streaming"||$e==="submitted"?h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx("button",{type:"button",className:me(yt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:bn,children:h.jsx(fe.Square,{className:"h-4 w-4"})})}),h.jsxs(rt,{children:[h.jsx(kr,{children:"Escape"})," to stop"]})]}):h.jsxs(nt,{children:[h.jsx(st,{asChild:!0,children:h.jsx("button",{type:"submit",className:me(yt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Qe.trim(),children:h.jsx(fe.ArrowRight,{className:"h-4 w-4"})})}),h.jsxs(rt,{children:[h.jsx(kr,{children:"Enter"})," to send"]})]})]})]})]}),h.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:[h.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),h.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),h.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):h.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[h.jsx(fe.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),h.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):h.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:h.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return rn(t)}catch{return e}if(Array.isArray(e))return e.map(rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=rn(s);return t}return e}function pf(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?rn(e):{}}function gf({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:f,onStateChange:d,allowStateEdits:g=!0,onToolCall:b,onFinish:x,sources:S,ragConfig:T,ragFilters:v}={}){const y=m.useMemo(()=>T!==void 0?T:v?{enabled:!0,filters:v}:S&&S.length>0?{enabled:!0,organizationId:S[0],autoExecute:!0,filters:void 0}:{enabled:!1},[S,T,v]),[N,M]=m.useState(n||null),k=m.useRef(n||null),[P,j]=m.useState(null),[q,L]=m.useState(null),Y=m.useRef(null),[se,de]=m.useState([]),[re,pe]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[Q,te]=m.useState(!1),[le,ae]=m.useState(new Set),J=f!==void 0,[He,St]=m.useState({}),ge=m.useRef({}),Ge=J?f||{}:He;J&&f?ge.current=f:J||(ge.current=He);const[Oe,At]=m.useState(!1),[Le,Xe]=m.useState(null),Ye=m.useRef(!1),Pt=m.useCallback(async(C,E=3)=>{if(!re||!k.current)return;const I=async()=>{const B=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,H=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${k.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:re,updates:C},format:"json"})});if(!H.ok){if(H.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const _=await H.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${H.status} ${_}`)}};for(let O=0;O<E;O++)try{await I(),Xe(null);return}catch(B){if(O===E-1){const _=B instanceof Error?B:new Error(String(B));throw Xe(_),console.error("Failed to sync state to Convex after retries:",B),_}await new Promise(_=>setTimeout(_,Math.pow(2,O)*100))}},[re,e,k]),Je=m.useMemo(()=>function(){return ge.current},[]),De=m.useMemo(()=>async function(E){const I={...ge.current,...E};ge.current=I,J||St(I),d&&d(I);try{await Pt(E)}catch(O){throw O}},[Pt,d,J]);m.useEffect(()=>{J&&f&&(ge.current=f)},[J,f]);const G=m.useMemo(()=>y?.enabled?async function(E,I=20,O){const B={...y.filters,...O};if(S&&S.length>1){const _=S.map(ee=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...k.current?{Authorization:`Bearer ${k.current}`}:{}},body:JSON.stringify({q:E,k:Math.min(I,100),organizationId:ee,...Object.keys(B).length>0?{filters:B}:{}})}).then(Z=>Z.ok?Z.json():null)),ve=await Promise.all(_),ce=[];for(const ee of ve)ee?.candidates&&ce.push(...ee.candidates);ce.sort((ee,Z)=>{const kt=ee.scores?.rerank||ee.scores?.dense||0;return(Z.scores?.rerank||Z.scores?.dense||0)-kt});const Se=ce.slice(0,I).map((ee,Z)=>{const kt=ee.citation||ee.url;return{rank:Z+1,doc_id:ee.doc_id,block_id:ee.block_id,url:ee.url,citation:kt,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:E,total:ce.length,results:Se,summary:`Found ${ce.length} relevant results across ${S.length} source(s) for "${E}". Top result: ${Se[0]?.title||"N/A"}`}}const H=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const _={q:E,k:Math.min(I,100)};H&&(_.organizationId=H),Object.keys(B).length>0&&(_.filters=B);const ve={"Content-Type":"application/json"};k.current&&(ve.Authorization=`Bearer ${k.current}`);const ce=await fetch(`${e}/search`,{method:"POST",headers:ve,body:JSON.stringify(_)});if(!ce.ok){const Z=await ce.text();return{success:!1,error:`Search failed: ${ce.status} ${Z}`}}const Se=await ce.json(),ee=Se.candidates.map((Z,kt)=>{const dt=Z.citation||Z.url;return{rank:kt+1,doc_id:Z.doc_id,block_id:Z.block_id,url:Z.url,citation:dt,title:Z.title||"Untitled",snippet:Z.snippet,score:Z.scores?.rerank||Z.scores?.dense||0,metadata:{site:Z.metadata?.site,lang:Z.metadata?.lang,contentType:Z.metadata?.content_type}}});return{success:!0,query:Se.query,total:Se.total,results:ee,summary:`Found ${Se.total} relevant results for "${E}". Top result: ${ee[0]?.title||"N/A"}`}}catch(_){return{success:!1,error:_ instanceof Error?_.message:"Unknown error occurred"}}}:null,[y,e,k]),Ne=m.useMemo(()=>y?.enabled?async function(E,I){const O=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const B={"Content-Type":"application/json"};k.current&&(B.Authorization=`Bearer ${k.current}`);const H=await fetch(`${e}/fetch`,{method:"POST",headers:B,body:JSON.stringify({doc_id:E,block_ids:I,...O?{organizationId:O}:{}})});if(!H.ok){const ve=await H.text();return{success:!1,error:`Fetch failed: ${H.status} ${ve}`}}const _=await H.json();return{success:!0,blocks:_.blocks||[],fullContent:_.fullContent||"",pageUrl:_.pageUrl||"",pageTitle:_.pageTitle||"",summary:`Fetched ${_.blocks?.length||0} blocks from ${_.pageTitle||E}`}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error occurred"}}}:null,[y,e,k]),Te=m.useMemo(()=>{const C=[...o,...i,Je];return(!J||g)&&C.push(De),y?.enabled&&(G&&C.push(G),Ne&&C.push(Ne)),C},[o,i,Je,De,G,Ne,y,J,g]),Ce=m.useMemo(()=>Da(Te,a),[Te,a]),xe=m.useMemo(()=>{const C=new Map,E=new Map(Ce.map(I=>[I.name,I]));return C.set("getState",Je),(!J||g)&&C.set("setState",De),y?.enabled&&(G&&C.set("searchDocs",G),Ne&&C.set("fetchDocContent",Ne)),Te.forEach(I=>{if(I===Je||I===De||I===G||I===Ne)return;const O=I[Be];if(O){const H=E.get(O);if(H){C.set(H.name,I);return}}const B=Ce.find(H=>H.name===I.name);B&&C.set(B.name,I)}),C},[Te,Ce,Je,De,G,Ne,y,J,g]),Ct=m.useMemo(()=>new Set(Ce.map(C=>C.name)),[Ce]),_t=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:[]}}];(!J||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 E=[];return y?.enabled&&E.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"]}}),[...Ce,...C,...E]},[Ce,y,J,g]),lt=m.useMemo(()=>_t.filter(C=>C.name==="getState"?!0:C.name==="setState"?!J||g:y?.enabled&&(C.name==="searchDocs"||C.name==="fetchDocContent")?!0:Ct.has(C.name)),[_t,Ct,J,g,y]),jt=m.useMemo(()=>{const C=new Set;return C.add("getState"),C.add("setState"),y?.enabled&&y.autoExecute!==!1&&(C.add("searchDocs"),C.add("fetchDocContent")),i.forEach(E=>{for(const[I,O]of xe.entries())if(O===E){C.add(I);break}}),C},[i,xe,y]);m.useEffect(()=>s||n?void 0:((async()=>{try{const E=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!E.ok)throw new Error("Failed to fetch token");const I=await E.json();M(I.clientToken),k.current=I.clientToken,L(I.expiresAt),j(null)}catch(E){console.error("[useAgent] Token fetch failed:",E),j(E instanceof Error?E.message:"Failed to fetch token")}})(),()=>{Y.current&&clearTimeout(Y.current)}),[t,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!q||s||n)return;Y.current&&clearTimeout(Y.current);const C=Math.floor(Date.now()/1e3),E=q-C,O=Math.max(0,E-5);return Y.current=setTimeout(async()=>{try{const B=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!B.ok)throw new Error("Failed to refresh token");const H=await B.json();M(H.clientToken),k.current=H.clientToken,L(H.expiresAt),j(null)}catch(B){console.error("[useAgent] Token refresh failed:",B),j(B instanceof Error?B.message:"Failed to refresh token")}},O*1e3),()=>{Y.current&&clearTimeout(Y.current)}},[q,t,JSON.stringify(r),s,n]);const gn=async(C,E={})=>{const I=E.headers?new Headers(E.headers):new Headers;I.delete("user-agent"),I.delete("User-Agent"),console.log("[useAgent] Making request to:",C),console.log("[useAgent] Method:",E.method||"GET"),console.log("[useAgent] Has Authorization header:",I.has("Authorization")),console.log("[useAgent] Client token available:",!!k.current);try{const O=await fetch(C,{...E,headers:I});if(!O.ok){console.error("[useAgent] Request failed:",O.status,O.statusText);const B=await O.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",B)}return O}catch(O){throw console.error("[useAgent] Fetch error:",O),O}},yn=`${e}/chat`;console.log("[useAgent] Chat API URL:",yn);const{messages:Fe,sendMessage:Wt,status:Ze,error:Qe,stop:Kt,addToolResult:ut,setMessages:qt}=Ki.useChat({id:re||void 0,messages:u,transport:new Vn.DefaultChatTransport({api:yn,fetch:gn,headers:()=>{const C={};return k.current?(C.Authorization=`Bearer ${k.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),C},body:()=>{const C=lt.map(O=>({name:O.name,description:O.description,inputSchema:O.jsonSchema})),E=C.filter(O=>O.name==="getState"||O.name==="setState").map(O=>O.name),I=C.filter(O=>O.name==="searchDocs"||O.name==="fetchDocContent").map(O=>O.name);return E.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",E),I.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",I):y?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:C,systemPrompt:c,state:ge.current,...v&&{ragFilters:v}}}}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Fe.forEach(C=>{C.role==="assistant"&&C.parts.forEach(E=>{if(!E.type?.startsWith("tool-")||E.state!=="input-available")return;const I=E.type.replace("tool-",""),O=E.toolCallId;if(le.has(O))return;ae(H=>new Set(H).add(O));const B=pf(E.input);if(jt.has(I)){const H=xe.get(I);H?(async()=>{try{const _=lt.find(ce=>ce.name===I);let ve;if(_&&_.jsonSchema?.properties){const Se=Object.keys(_.jsonSchema.properties).map(ee=>B[ee]);ve=await H(...Se)}else if(I==="getState")ve=H();else if(I==="setState"){const ce=B.updates||B;ve=await H(ce)}else ve=await H(...Object.values(B));ut({toolCallId:O,tool:I,output:ve})}catch(_){console.error(`[useAgent] Error executing tool ${I}:`,_),ut({toolCallId:O,tool:I,output:`Error: ${_}`})}})():console.warn(`[useAgent] Tool ${I} not found in toolsMap`)}else b&&b({toolCall:{toolCallId:O,toolName:I,args:B}})})})},[Fe,jt,xe,b,ut,le,De,lt]),m.useEffect(()=>{if(Ze==="ready"&&Fe.length>0&&x){const C=Fe[Fe.length-1];C&&C.role==="assistant"&&x({message:C,messages:Fe,isAbort:!1,isDisconnect:!1,isError:!!Qe})}},[Ze,Fe,Qe,x]);async function Wn(){if(!(!r?.id||!N)){te(!0);try{const E=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();de(E.conversations||[])}catch(C){console.error("Failed to fetch conversations:",C)}finally{te(!1)}}}m.useEffect(()=>{r?.id&&N&&Wn()},[JSON.stringify(r),N,e]),m.useEffect(()=>{if(!re||!k.current)return;(async()=>{At(!0),Xe(null);try{const E=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${k.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:re},format:"json"})});if(!E.ok){const B=await E.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${E.status} ${B}`)}const O=(await E.json())?.value||{};ge.current=O,J||St(O),d&&d(O),Ye.current=!0}catch(E){console.error("Failed to fetch state:",E);const I=E instanceof Error?E:new Error(String(E));Xe(I),Ye.current||(ge.current={},J?d&&d({}):(St({}),d&&d({})),Ye.current=!0)}finally{At(!1)}})()},[re,e,J,d]);async function Kn(C){pe(C),te(!0);try{const E=await fetch(`${e}/conversations/${C}/messages`,{headers:{Authorization:`Bearer ${k.current}`}});if(!E.ok)throw new Error(`Failed to fetch messages: ${E.statusText}`);const O=(await E.json()).messages||[];qt(O)}catch(E){console.error("Failed to load conversation messages:",E)}finally{te(!1)}}async function Ht(C){if(N)try{await fetch(`${e}/conversations/${C}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),de(se.filter(E=>E._id!==C)),C===re&&Ue()}catch(E){console.error("Failed to delete conversation:",E)}}function Ue(){const C=crypto.randomUUID();pe(C),qt([]),ae(new Set),ge.current={},J?d&&d({}):(St({}),d&&d({})),Ye.current=!1}function qn(C){ut(C)}async function Hn(C){const E={...ge.current,...C};ge.current=E,J||St(E),d&&d(E);try{await Pt(C)}catch(I){throw I}}return{id:re,messages:Fe,status:Ze,error:Qe,sendMessage:Wt,stop:Kt,addToolOutput:qn,setMessages:qt,conversations:se,loadConversation:Kn,deleteConversation:Ht,startNewConversation:Ue,isLoadingConversations:Q,clientToken:N,tokenError:P,state:Ge,setState:Hn,isStateLoading:Oe,stateError:Le}}exports.verifyToken=cc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Be;exports.ArctenAgent=mf;exports.preserveToolName=Hh;exports.useAgent=gf;