@arcteninc/core 0.0.81 → 0.0.82

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 h=require("react/jsx-runtime"),m=require("react"),dt=require("lucide-react"),Wi=require("@ai-sdk/react"),Vn=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 Vt=Is(m),Me=Is(rc),Os=Is(ic);function ht(...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"}}),Nn=Vt.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Ki.Slot:"button";return h.jsx(i,{ref:o,"data-slot":"button",className:ht(pe({variant:e,size:n,className:t})),...r})});Nn.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 h.jsx(r,{"data-slot":"badge",className:ht(cc({variant:e}),t),...s})}const lc=({textAreaRef:t,triggerAutoSize:e,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Vt.useState(!0);Vt.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=Vt.forwardRef(({maxHeight:t=Number.MAX_SAFE_INTEGER,minHeight:e=52,className:n,onChange:s,value:r,...o},i)=>{const a=Vt.useRef(null),[c,u]=Vt.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})),Vt.useEffect(()=>{u(r)},[o?.defaultValue,r]),h.jsx("textarea",{...o,value:r,ref:a,className:ht("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 h.jsx(Me.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function ee({...t}){return h.jsx(uc,{children:h.jsx(Me.Root,{"data-slot":"tooltip",...t})})}function ne({...t}){return h.jsx(Me.Trigger,{"data-slot":"tooltip-trigger",...t})}function se({className:t,sideOffset:e=0,children:n,...s}){return h.jsx(Me.Portal,{children:h.jsxs(Me.Content,{"data-slot":"tooltip-content",sideOffset:e,className:ht("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,h.jsx(Me.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 h.jsx("kbd",{"data-slot":"kbd",className:ht("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 qt=(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 Ne=()=>{},Ht=()=>{};process.env.NODE_ENV!=="production"&&(Ne=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(hs(e,n))},Ht=(t,e,n)=>{if(!t)throw new Error(hs(e,n))});const Xt={},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 Mt=t=>t,dc=(t,e)=>n=>e(t(n)),an=(...t)=>t.reduce(dc),tn=(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 Nt=t=>t*1e3,kt=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 cn(t,e,n,s){if(t===e&&n===s)return Mt;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=cn(.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=cn(.42,0,1,1),gc=cn(0,0,.58,1),ao=cn(.42,0,.58,1),yc=t=>Array.isArray(t)&&typeof t[0]!="number",co=t=>Array.isArray(t)&&typeof t[0]=="number",Mr={linear:Mt,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)){Ht(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,s,r]=t;return cn(e,n,s,r)}else if(xc(t))return Ht(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,d=!1,f=!1)=>{const y=f&&r?n:s;return d&&i.add(l),y.has(l)||y.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((A,C)=>(A[C]=vc(o),A),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:d,preRender:f,render:g,postRender:y}=i,b=()=>{const A=Xt.useManualTiming?r.timestamp:performance.now();n=!1,Xt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(A-r.timestamp,bc),1)),r.timestamp=A,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),d.process(r),f.process(r),g.process(r),y.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(b))},P=()=>{n=!0,s=!0,r.isProcessing||t(b)};return{schedule:Tn.reduce((A,C)=>{const R=i[C];return A[C]=(k,O=!1,D=!1)=>(n||P(),R.schedule(k,O,D)),A},{}),cancel:A=>{for(let C=0;C<Tn.length;C++)i[Tn[C]].cancel(A)},state:r,steps:i}}const{schedule:nt,cancel:ie,state:ft,steps:Yn}=lo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Mt,!0);let jn;function wc(){jn=void 0}const bt={now:()=>(jn===void 0&&bt.set(ft.isProcessing||Xt.useManualTiming?ft.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,Re={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},en={...Re,transform:t=>qt(0,1,t)},Sn={...Re,default:1},Xe=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=>qt(0,255,t),Jn={...Re,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)+", "+Xe(en.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},ln=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),re=ln("deg"),Bt=ln("%"),L=ln("px"),kc=ln("vh"),Mc=ln("vw"),Dr={...Bt,parse:t=>Bt.parse(t)/100,transform:t=>Bt.transform(t*100)},Se={test:Ys("hsl","hue"),parse:ho("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+Bt.transform(Xe(e))+", "+Bt.transform(Xe(n))+", "+Xe(en.transform(s))+")"},lt={test:t=>ye.test(t)||fs.test(t)||Se.test(t),parse:t=>ye.test(t)?ye.parse(t):Se.test(t)?Se.parse(t):fs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ye.transform(t):Se.transform(t),getAnimatableNone:t=>{const e=lt.parse(t);return e.alpha=0,lt.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",Vc="var",Nc="var(",Vr="${}",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 nn(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=e.replace(Rc,c=>(lt.test(c)?(s.color.push(o),r.push(mo),n.push(lt.parse(c))):c.startsWith(Nc)?(s.var.push(o),r.push(Vc),n.push(c)):(s.number.push(o),r.push(fo),n.push(parseFloat(c))),++o,Vr)).split(Vr);return{values:n,split:a,indexes:s,types:r}}function po(t){return nn(t).values}function go(t){const{split:e,types:n}=nn(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+=Xe(r[i]):a===mo?o+=lt.transform(r[i]):o+=r[i]}return o}}const Ic=t=>typeof t=="number"?0:lt.test(t)?lt.getAnimatableNone(t):t;function Oc(t){const e=po(t);return go(t)(e.map(Ic))}const oe={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,Se],$c=t=>Fc.find(e=>e.test(t));function Nr(t){const e=$c(t);if(Ne(!!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===Se&&(n=Lc(n)),n}const Rr=(t,e)=>{const n=Nr(t),s=Nr(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:lt.test(t)?Rr:Wc:Array.isArray(t)?yo:typeof t=="object"?lt.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=oe.createTransformer(e),s=nn(t),r=nn(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):an(yo(_c(s,r),r.values),n):(Ne(!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)=>nt.update(e,n),stop:()=>ie(e),now:()=>ft.isProcessing?ft.timestamp:bt.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:kt(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;Ne(t<=Nt(rt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-e;i=qt(rt.minDamping,rt.maxDamping,i),t=qt(rt.minDuration,rt.maxDuration,kt(t)),i<1?(r=u=>{const l=u*i,d=l*t,f=l-n,g=ps(u,i),y=Math.exp(-d);return ts-f/g*y},o=u=>{const d=u*i*t,f=d*n+n,g=Math.pow(i,2)*Math.pow(u,2)*t,y=Math.exp(-d),b=ps(Math.pow(u,2),i);return(-r(u)+ts>0?-1:1)*((f-g)*y)/b}):(r=u=>{const l=Math.exp(-u*t),d=(u-n)*t+1;return-ts+l*d},o=u=>{const l=Math.exp(-u*t),d=(n-u)*(t*t);return l*d});const a=5/t,c=Yc(r,o,a);if(t=Nt(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*qt(.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:d,velocity:f,isResolvedFromDuration:g}=Qc({...n,velocity:-kt(n.velocity||0)}),y=f||0,b=u/(2*Math.sqrt(c*l)),P=i-o,x=kt(Math.sqrt(c/l)),w=Math.abs(P)<5;s||(s=w?rt.restSpeed.granular:rt.restSpeed.default),r||(r=w?rt.restDelta.granular:rt.restDelta.default);let A;if(b<1){const R=ps(x,b);A=k=>{const O=Math.exp(-b*x*k);return i-O*((y+b*x*P)/R*Math.sin(R*k)+P*Math.cos(R*k))}}else if(b===1)A=R=>i-Math.exp(-x*R)*(P+(y+x*P)*R);else{const R=x*Math.sqrt(b*b-1);A=k=>{const O=Math.exp(-b*x*k),D=Math.min(R*k,300);return i-O*((y+b*x*P)*Math.sinh(D)+R*P*Math.cosh(D))/R}}const C={calculatedDuration:g&&d||null,next:R=>{const k=A(R);if(g)a.done=R>=d;else{let O=R===0?y:0;b<1&&(O=R===0?Nt(y):bo(A,R,k));const D=Math.abs(O)<=s,I=Math.abs(i-k)<=r;a.done=D&&I}return a.value=a.done?i:k,a},toString:()=>{const R=Math.min(Zs(C),In),k=vo(O=>C.next(R*O).value,R,30);return R+"ms "+k},toTransition:()=>{}};return C}On.applyToOptions=t=>{const e=qc(t,100,On);return t.ease=e.ease,t.duration=Nt(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 d=t[0],f={done:!1,value:d},g=D=>a!==void 0&&D<a||c!==void 0&&D>c,y=D=>a===void 0?c:c===void 0||Math.abs(a-D)<Math.abs(c-D)?a:c;let b=n*e;const P=d+b,x=i===void 0?P:i(P);x!==P&&(b=x-d);const w=D=>-b*Math.exp(-D/s),A=D=>x+w(D),C=D=>{const I=w(D),K=A(D);f.done=Math.abs(I)<=u,f.value=f.done?x:K};let R,k;const O=D=>{g(f.value)&&(R=D,k=On({keyframes:[f.value,y(f.value)],velocity:bo(A,D,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return O(0),{calculatedDuration:null,next:D=>{let I=!1;return!k&&R===void 0&&(I=!0,C(D),O(D)),R!==void 0&&D>=R?k.next(D-R):(!I&&C(D),f)}}}function tl(t,e,n){const s=[],r=n||Xt.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]||Mt:e;a=an(c,a)}s.push(a)}return s}function el(t,e,{clamp:n=!0,ease:s,mixer:r}={}){const o=t.length;if(Ht(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 d=0;if(c>1)for(;d<t.length-2&&!(l<t[d+1]);d++);const f=tn(t[d],t[d+1],l);return a[d](f)};return n?l=>u(qt(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=tn(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 Ae({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:Ae,keyframes:Ae,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!==bt.now()&&this.tick(bt.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=Ae,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=e;let{keyframes:a}=e;const c=n||Ae;process.env.NODE_ENV!=="production"&&c!==Ae&&Ht(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Ae&&typeof a[0]!="number"&&(this.mixKeyframes=an(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:d,repeatType:f,repeatDelay:g,type:y,onUpdate:b,finalKeyframe:P}=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 x=this.currentTime-u*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?x<0:x>r;this.currentTime=Math.max(x,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let A=this.currentTime,C=s;if(d){const D=Math.min(this.currentTime,r)/a;let I=Math.floor(D),K=D%1;!K&&D>=1&&(K=1),K===1&&I--,I=Math.min(I,d+1),!!(I%2)&&(f==="reverse"?(K=1-K,g&&(K-=g/a)):f==="mirror"&&(C=i)),A=qt(0,1,K)*a}const R=w?{done:!1,value:l[0]}:C.next(A);o&&(R.value=o(R.value));let{done:k}=R;!w&&c!==null&&(k=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const O=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return O&&y!==gs&&(R.value=Qs(l,this.options,P,this.speed)),b&&b(R.value),O&&this.finish(),R}then(e,n){return this.finished.then(e,n)}get duration(){return kt(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+kt(e)}get time(){return kt(this.currentTime)}set time(e){e=Nt(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(bt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=kt(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(bt.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 Ie=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Oe=new Set(Ie),$r=t=>t===Re||t===L,ml=new Set(["x","y","z"]),pl=Ie.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,nt.read(So),nt.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"),He=([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:He([0,.65,.55,1]),circOut:He([.55,0,1,.45]),backIn:He([.31,.01,.66,-.59]),backOut:He([.33,1.53,.69,.99])};function Co(t,e){if(t)return typeof t=="function"?Ao()?vo(t,e):"ease-out":co(t)?He(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 d=Co(a,r);Array.isArray(d)&&(l.easing=d);const f={delay:s,duration:r,easing:Array.isArray(d)?"linear":d,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,Ht(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 kt(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+kt(e)}get time(){return kt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=Nt(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,Mt):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=Nt(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"&&(oe.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 Ne(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"]),Vl=Us(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Nl(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 Vl()&&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,...d}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=bt.now();const f={autoplay:e,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...d},g=l?.KeyframeResolver||nr;this.keyframeResolver=new g(a,(y,b,P)=>this.onKeyframesResolved(y,b,f,!P),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=bt.now(),El(e,o,i,a)||((Xt.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&&Nl(f)?new kl({...f,element:f.motionValue.owner.current}):new er(f);g.finished.then(()=>this.notifyFinished()).catch(Mt),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){Ht(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",...Ie]),$l={test:t=>t==="auto",parse:t=>t},Eo=t=>e=>e.test(t),Do=[Re,L,Bt,re,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={...oe,getAnimatableNone:t=>{const e=t.match(_l);return e?e.map(Ul).join(" "):t}},Wr={...Re,transform:Math.round},Wl={rotate:re,rotateX:re,rotateY:re,rotateZ:re,scale:Sn,scaleX:Sn,scaleY:Sn,scaleZ:Sn,skew:re,skewX:re,skewY:re,distance:L,translateX:L,translateY:L,translateZ:L,x:L,y:L,z:L,perspective:L,transformPerspective:L,opacity:en,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:en,strokeOpacity:en,numOctaves:Wr},Kl={...rr,color:lt,backgroundColor:lt,outlineColor:lt,fill:lt,stroke:lt,borderColor:lt,borderTopColor:lt,borderRightColor:lt,borderBottomColor:lt,borderLeftColor:lt,filter:Cs,WebkitFilter:Cs},Vo=t=>Kl[t];function No(t,e){let n=Vo(t);return n!==Cs&&(n=oe),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)&&nn(o).values.length&&(r=t[s]),s++}if(r&&n)for(const o of e)t[o]=No(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=bt.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=bt.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(),nt.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=bt.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 De(t,e){return new Jl(t,e)}const{schedule:ir}=lo(queueMicrotask,!1),Dt={x:!1,y:!1};function Oo(){return Dt.x||Dt.y}function Zl(t){return t==="x"||t==="y"?Dt[t]?null:(Dt[t]=!0,()=>{Dt[t]=!1}):Dt.x||Dt.y?null:(Dt.x=Dt.y=!0,()=>{Dt.x=Dt.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=d=>{qr(d)&&(u(d),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,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),kn.has(c)&&kn.delete(c),Xr(g)&&typeof u=="function"&&u(g,{success:y})},d=g=>{l(g,c===window||c===document||n.useGlobalTarget||Fo(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",d,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 pt=t=>!!(t&&t.getVelocity),iu=[...Do,lt,oe],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 Vt.useCallback(au(...t),t)}class lu extends Vt.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:d,left:f,right:g}=i.current;if(e||!o.current||!u||!l)return;const y=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const P=s??document.head;return P.appendChild(b),b.sheet&&b.sheet.insertRule(`
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 h=require("react/jsx-runtime"),m=require("react"),dt=require("lucide-react"),Wi=require("@ai-sdk/react"),Vn=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),Ve=Is(rc),Os=Is(ic);function ht(...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"}}),Nn=Ot.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Ki.Slot:"button";return h.jsx(i,{ref:o,"data-slot":"button",className:ht(pe({variant:e,size:n,className:t})),...r})});Nn.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 h.jsx(r,{"data-slot":"badge",className:ht(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,l]=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(()=>{l(r)},[o?.defaultValue,r]),h.jsx("textarea",{...o,value:r,ref:a,className:ht("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:u=>{l(u.target.value),s?.(u)}})});Hi.displayName="AutosizeTextarea";function uc({delayDuration:t=0,...e}){return h.jsx(Ve.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function Qt({...t}){return h.jsx(uc,{children:h.jsx(Ve.Root,{"data-slot":"tooltip",...t})})}function te({...t}){return h.jsx(Ve.Trigger,{"data-slot":"tooltip-trigger",...t})}function ee({className:t,sideOffset:e=0,children:n,...s}){return h.jsx(Ve.Portal,{children:h.jsxs(Ve.Content,{"data-slot":"tooltip-content",sideOffset:e,className:ht("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,h.jsx(Ve.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 h.jsx("kbd",{"data-slot":"kbd",className:ht("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 Dt=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,Et=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 Dt;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:Dt,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(u){i.has(u)&&(l.schedule(u),t()),u(a)}const l={schedule:(u,d=!1,f=!1)=>{const y=f&&r?n:s;return d&&i.add(u),y.has(u)||y.add(u),u},cancel:u=>{s.delete(u),i.delete(u)},process:u=>{if(a=u,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,l.process(u))}};return l}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((S,P)=>(S[P]=vc(o),S),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:g,postRender:y}=i,v=()=>{const S=qt.useManualTiming?r.timestamp:performance.now();n=!1,qt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(S-r.timestamp,bc),1)),r.timestamp=S,r.isProcessing=!0,a.process(r),c.process(r),l.process(r),u.process(r),d.process(r),f.process(r),g.process(r),y.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(v))},C=()=>{n=!0,s=!0,r.isProcessing||t(v)};return{schedule:Tn.reduce((S,P)=>{const V=i[P];return S[P]=(I,k=!1,N=!1)=>(n||C(),V.schedule(I,k,N)),S},{}),cancel:S=>{for(let P=0;P<Tn.length;P++)i[Tn[P]].cancel(S)},state:r,steps:i}}const{schedule:st,cancel:se,state:ft,steps:Yn}=lo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Dt,!0);let jn;function wc(){jn=void 0}const St={now:()=>(jn===void 0&&St.set(ft.isProcessing||qt.useManualTiming?ft.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("%"),O=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))+")"},lt={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=lt.parse(t);return e.alpha=0,lt.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",Vc="var",Nc="var(",Vr="${}",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=>(lt.test(c)?(s.color.push(o),r.push(mo),n.push(lt.parse(c))):c.startsWith(Nc)?(s.var.push(o),r.push(Vc),n.push(c)):(s.number.push(o),r.push(fo),n.push(parseFloat(c))),++o,Vr)).split(Vr);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+=lt.transform(r[i]):o+=r[i]}return o}}const Ic=t=>typeof t=="number"?0:lt.test(t)?lt.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 Nr(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=Nr(t),s=Nr(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:lt.test(t)?Rr:Wc:Array.isArray(t)?yo:typeof t=="object"?lt.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:()=>ft.isProcessing?ft.timestamp:St.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:Et(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,Et(t)),i<1?(r=l=>{const u=l*i,d=u*t,f=u-n,g=ps(l,i),y=Math.exp(-d);return ts-f/g*y},o=l=>{const d=l*i*t,f=d*n+n,g=Math.pow(i,2)*Math.pow(l,2)*t,y=Math.exp(-d),v=ps(Math.pow(l,2),i);return(-r(l)+ts>0?-1:1)*((f-g)*y)/v}):(r=l=>{const u=Math.exp(-l*t),d=(l-n)*t+1;return-ts+u*d},o=l=>{const u=Math.exp(-l*t),d=(n-l)*(t*t);return u*d});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 l=Math.pow(c,2)*s;return{stiffness:l,damping:i*2*Math.sqrt(s*l),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:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:g}=Qc({...n,velocity:-Et(n.velocity||0)}),y=f||0,v=l/(2*Math.sqrt(c*u)),C=i-o,x=Et(Math.sqrt(c/u)),w=Math.abs(C)<5;s||(s=w?rt.restSpeed.granular:rt.restSpeed.default),r||(r=w?rt.restDelta.granular:rt.restDelta.default);let S;if(v<1){const V=ps(x,v);S=I=>{const k=Math.exp(-v*x*I);return i-k*((y+v*x*C)/V*Math.sin(V*I)+C*Math.cos(V*I))}}else if(v===1)S=V=>i-Math.exp(-x*V)*(C+(y+x*C)*V);else{const V=x*Math.sqrt(v*v-1);S=I=>{const k=Math.exp(-v*x*I),N=Math.min(V*I,300);return i-k*((y+v*x*C)*Math.sinh(N)+V*C*Math.cosh(N))/V}}const P={calculatedDuration:g&&d||null,next:V=>{const I=S(V);if(g)a.done=V>=d;else{let k=V===0?y:0;v<1&&(k=V===0?Lt(y):bo(S,V,I));const N=Math.abs(k)<=s,$=Math.abs(i-I)<=r;a.done=N&&$}return a.value=a.done?i:I,a},toString:()=>{const V=Math.min(Zs(P),In),I=vo(k=>P.next(V*k).value,V,30);return V+"ms "+I},toTransition:()=>{}};return P}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:l=.5,restSpeed:u}){const d=t[0],f={done:!1,value:d},g=N=>a!==void 0&&N<a||c!==void 0&&N>c,y=N=>a===void 0?c:c===void 0||Math.abs(a-N)<Math.abs(c-N)?a:c;let v=n*e;const C=d+v,x=i===void 0?C:i(C);x!==C&&(v=x-d);const w=N=>-v*Math.exp(-N/s),S=N=>x+w(N),P=N=>{const $=w(N),L=S(N);f.done=Math.abs($)<=l,f.value=f.done?x:L};let V,I;const k=N=>{g(f.value)&&(V=N,I=On({keyframes:[f.value,y(f.value)],velocity:bo(S,N,f.value),damping:r,stiffness:o,restDelta:l,restSpeed:u}))};return k(0),{calculatedDuration:null,next:N=>{let $=!1;return!I&&V===void 0&&($=!0,P(N),k(N)),V!==void 0&&N>=V?I.next(N-V):(!$&&P(N),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]||Dt: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,l=u=>{if(i&&u<t[0])return e[0];let d=0;if(c>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const f=sn(t[d],t[d+1],u);return a[d](f)};return n?u=>l(Wt(t[0],t[o-1],u)):l}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!==St.now()&&this.tick(St.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 l=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-i})),l.calculatedDuration===null&&(l.calculatedDuration=Zs(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=l}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:l=0,keyframes:u,repeat:d,repeatType:f,repeatDelay:g,type:y,onUpdate:v,finalKeyframe:C}=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 x=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?x<0:x>r;this.currentTime=Math.max(x,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let S=this.currentTime,P=s;if(d){const N=Math.min(this.currentTime,r)/a;let $=Math.floor(N),L=N%1;!L&&N>=1&&(L=1),L===1&&$--,$=Math.min($,d+1),!!($%2)&&(f==="reverse"?(L=1-L,g&&(L-=g/a)):f==="mirror"&&(P=i)),S=Wt(0,1,L)*a}const V=w?{done:!1,value:u[0]}:P.next(S);o&&(V.value=o(V.value));let{done:I}=V;!w&&c!==null&&(I=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&I);return k&&y!==gs&&(V.value=Qs(u,this.options,C,this.speed)),v&&v(V.value),k&&this.finish(),V}then(e,n){return this.finished.then(e,n)}get duration(){return Et(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Et(e)}get time(){return Et(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(St.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=Et(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(St.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===O,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}={},l=void 0){const u={[e]:n};c&&(u.offset=c);const d=Co(a,r);Array.isArray(d)&&(u.easing=d);const f={delay:s,duration:r,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return l&&(f.pseudoElement=l),t.animate(u,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 l=Al(e);this.animation=Sl(n,s,r,l,o),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Qs(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):vl(n,s,u),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 Et(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Et(e)}get time(){return Et(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,Dt):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"]),Vl=Us(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Nl(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:l}=e.owner.getProps();return Vl()&&n&&Dl.has(n)&&(n!=="transform"||!l)&&!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:l,element:u,...d}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=St.now();const f={autoplay:e,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:l,element:u,...d},g=u?.KeyframeResolver||nr;this.keyframeResolver=new g(a,(y,v,C)=>this.onKeyframesResolved(y,v,f,!C),c,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:l,onUpdate:u}=s;this.resolvedAt=St.now(),El(e,o,i,a)||((qt.instantAnimations||!c)&&u?.(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=!l&&Nl(f)?new kl({...f,element:f.motionValue.owner.current}):new er(f);g.finished.then(()=>this.notifyFinished()).catch(Dt),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,O,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:O,translateX:O,translateY:O,translateZ:O,x:O,y:O,z:O,perspective:O,transformPerspective:O,opacity:rn,originX:Dr,originY:Dr,originZ:O},rr={borderWidth:O,borderTopWidth:O,borderRightWidth:O,borderBottomWidth:O,borderLeftWidth:O,borderRadius:O,radius:O,borderTopLeftRadius:O,borderTopRightRadius:O,borderBottomRightRadius:O,borderBottomLeftRadius:O,width:O,maxWidth:O,height:O,maxHeight:O,top:O,right:O,bottom:O,left:O,padding:O,paddingTop:O,paddingRight:O,paddingBottom:O,paddingLeft:O,margin:O,marginTop:O,marginRight:O,marginBottom:O,marginLeft:O,backgroundPositionX:O,backgroundPositionY:O,...Wl,zIndex:Wr,fillOpacity:rn,strokeOpacity:rn,numOctaves:Wr},Kl={...rr,color:lt,backgroundColor:lt,outlineColor:lt,fill:lt,stroke:lt,borderColor:lt,borderTopColor:lt,borderRightColor:lt,borderBottomColor:lt,borderLeftColor:lt,filter:Cs,WebkitFilter:Cs},Vo=t=>Kl[t];function No(t,e){let n=Vo(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]=No(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 l=e[c];if(typeof l=="string"&&(l=l.trim(),Xs(l))){const u=ko(l,n.current);u!==void 0&&(e[c]=u),c===e.length-1&&(this.finalKeyframe=l)}}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 l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}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=St.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=St.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=St.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,l=e(c,a);if(typeof l!="function"||!c)return;const u=d=>{qr(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,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 l=e(c,a),u=(g,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),kn.has(c)&&kn.delete(c),Xr(g)&&typeof l=="function"&&l(g,{success:y})},d=g=>{u(g,c===window||c===document||n.useGlobalTarget||Fo(c,g.target))},f=g=>{u(g,!1)};window.addEventListener("pointerup",d,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),Io(a)&&(a.addEventListener("focus",l=>nu(l,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 pt=t=>!!(t&&t.getVelocity),iu=[...Do,lt,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:l,height:u,top:d,left:f,right:g}=i.current;if(e||!o.current||!l||!u)return;const y=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const v=document.createElement("style");a&&(v.nonce=a);const C=s??document.head;return C.appendChild(v),v.sheet&&v.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
- width: ${u}px !important;
5
- height: ${l}px !important;
4
+ width: ${l}px !important;
5
+ height: ${u}px !important;
6
6
  ${y}px !important;
7
7
  top: ${d}px !important;
8
8
  }
9
- `),()=>{P.contains(b)&&P.removeChild(b)}},[e]),h.jsx(lu,{isPresent:e,childRef:o,sizeRef:i,children:Vt.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 d=!0,f=m.useMemo(()=>(d=!1,{id:l,initial:e,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const y of u.values())if(!y)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&d&&(f={...f}),m.useMemo(()=>{u.forEach((g,y)=>u.set(y,!1))},[n]),Vt.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(t=h.jsx(uu,{isPresent:n,anchorX:a,root:c,children:t})),h.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),d=m.useMemo(()=>Yr(t),[t]),f=i&&!u?[]:d.map(An),g=m.useRef(!0),y=m.useRef(d),b=Fs(()=>new Map),[P,x]=m.useState(d),[w,A]=m.useState(d);Xi(()=>{g.current=!1,y.current=d;for(let k=0;k<w.length;k++){const O=An(w[k]);f.includes(O)?b.delete(O):b.get(O)!==!0&&b.set(O,!1)}},[w,f.length,f.join("-")]);const C=[];if(d!==P){let k=[...d];for(let O=0;O<w.length;O++){const D=w[O],I=An(D);f.includes(I)||(k.splice(O,0,D),C.push(D))}return o==="wait"&&C.length&&(k=C),A(Yr(k)),x(d),null}process.env.NODE_ENV!=="production"&&o==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:R}=m.useContext(Ls);return h.jsx(h.Fragment,{children:w.map(k=>{const O=An(k),D=i&&!u?!1:d===w||f.includes(O),I=()=>{if(b.has(O))b.set(O,!0);else return;let K=!0;b.forEach(Z=>{Z||(K=!1)}),K&&(R?.(),A(y.current),i&&l?.(),s&&s())};return h.jsx(du,{isPresent:D,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:D?void 0:I,anchorX:a,children:k},O)})})},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"]},Ve={};for(const t in Jr)Ve[t]={isEnabled:e=>Jr[t].some(n=>!!e[n])};function Ps(t){for(const e in t)Ve[e]={...Ve[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)})},[]),h.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 sn(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=>sn(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||sn(n)?n:void 0,animate:sn(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 rn={};function bu(t){for(const e in t)rn[e]=t[e],Hs(e)&&(rn[e].isCSSVariable=!0)}function _o(t,{layout:e,layoutId:n}){return Oe.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!rn[t]||t==="opacity")}const wu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Tu=Ie.length;function Su(t,e,n){let s="",r=!0;for(let o=0;o<Tu;o++){const i=Ie[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(Oe.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)!pt(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:d,style:f}=t;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),s!==void 0&&(d.scale=s),r!==void 0&&Mu(d,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 Vu(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,d=m.useMemo(()=>pt(l)?l.get():l,[l]);return m.createElement(t,{...u,children:d})}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 pt(t)?t.get():t}function Nu({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 d=l?a:i;if(d&&typeof d!="boolean"&&!zn(d)){const f=Array.isArray(d)?d:[d];for(let g=0;g<f.length;g++){const y=mr(t,f[g]);if(y){const{transitionEnd:b,transition:P,...x}=y;for(const w in x){let A=x[w];if(Array.isArray(A)){const C=l?A.length-1:0;A=A[C]}A!==null&&(r[w]=A)}for(const w in b)r[w]=b[w]}}}return r}const Xo=t=>(e,n)=>{const s=m.useContext(Bn),r=m.useContext($n),o=()=>Nu(t,e,s,r);return n?o():Fs(o)};function pr(t,e,n){const{style:s}=t,r={};for(const o in s)(pt(s[o])||e.style&&pt(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(pt(t[r])||pt(e[r])){const o=Ie.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 Ce(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):Ce(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,d=m.useContext(Jo);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&zu(u.current,n,r,d);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[Yo],y=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return Xi(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),y.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!y.current&&l.animationState&&l.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),y.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&&Ce(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:d}=l,f=vu(a),g=r(a,d);if(!d&&$s){_u(l,n);const y=Wu(l);u=y.MeasureLayout,f.visualElement=Bu(t,g,l,s,y.ProjectionNode)}return h.jsxs(Bn.Provider,{value:f,children:[u&&f.visualElement?h.jsx(u,{visualElement:f.visualElement,...l}):null,Vu(t,a,Fu(g,f.visualElement,c),g,d,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?Ne(!1,s,"lazy-strict-mode"):Ht(!1,s,"lazy-strict-mode")}}function Wu(t){const{drag:e,layout:n}=Ve;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&&je(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)&&je(t,o.latestValues))}e.x<si&&e.x>ni&&(e.x=1),e.y<si&&e.y>ni&&(e.y=1)}function Pe(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 je(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&&(Pe(s.x,r.offset.x),Pe(s.y,r.offset.y)),s}const ii=()=>({translate:0,scale:1,origin:0,originPoint:0}),ke=()=>({x:ii(),y:ii()}),oi=()=>({min:0,max:0}),ct=()=>({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(pt(r))t.addValue(s,r);else if(pt(o))t.addValue(s,De(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,De(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=bt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,nt.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,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const g=d[f];c[f]!==void 0&&pt(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(),ie(this.notifyUpdate),ie(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=Oe.has(e);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[e]=i,this.props.onUpdate&&nt.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 Ve){const n=Ve[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):ct()}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=De(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)&&oe.test(n)&&(s=No(e,n)),this.setBaseTarget(e,pt(s)?s.get():s)),pt(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&&!pt(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;pt(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(Oe.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=ct}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Oe.has(n)){const s=Vo(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 Ee(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,De(n))}function id(t){return Es(t)?t[t.length-1]||0:t}function od(t,e){const n=Ee(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!!(pt(t)&&t.add)}function Ds(t,e){const n=t.getValue("willChange");if(ad(n))return n.add(e);if(!n&&Xt.WillChange){const s=new Xt.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:Oe.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-Nt(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=Nt(l.duration)),l.repeatDelay&&(l.repeatDelay=Nt(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let d=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(As(l),l.delay===0&&(d=!0)),(Xt.instantAnimations||Xt.skipAnimations)&&(d=!0,As(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const f=ld(l.keyframes,a);if(f!==void 0){nt.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 d=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)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===y&&!g.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const x=ca(t);if(x){const w=window.MotionHandoffAnimation(x,l,nt);w!==null&&(g.startTime=w,b=!0)}}Ds(t,l),d.start(yr(l,d,f,t.shouldReduceMotion&&Mo.has(l)?{type:!1}:g,t,b));const P=d.animation;P&&c.push(P)}return i&&Promise.all(c).then(()=>{nt.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 Vs(t,e,n={}){const s=Ee(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:d}=r;return yd(t,e,c,u,l,d,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(Vs(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=>Vs(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Vs(t,e,n);else{const r=typeof e=="function"?Ee(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];(sn(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 d=Ee(t,l,c==="exit"?t.presenceContext?.custom:void 0);if(d){const{transition:f,transitionEnd:g,...y}=d;u={...u,...y,...g}}return u};function o(c){e=c(t)}function i(c){const{props:u}=t,l=ha(t.parent)||{},d=[],f=new Set;let g={},y=1/0;for(let P=0;P<wd;P++){const x=bd[P],w=n[x],A=u[x]!==void 0?u[x]:l[x],C=sn(A),R=x===c?w.isActive:null;R===!1&&(y=P);let k=A===l[x]&&A!==u[x]&&C;if(k&&s&&t.manuallyAnimateOnMount&&(k=!1),w.protectedKeys={...g},!w.isActive&&R===null||!A&&!w.prevProp||zn(A)||typeof A=="boolean")continue;const O=Ad(w.prevProp,A);let D=O||x===c&&w.isActive&&!k&&C||P>y&&C,I=!1;const K=Array.isArray(A)?A:[A];let Z=K.reduce(r(x),{});R===!1&&(Z={});const{prevResolvedValues:et={}}=w,Et={...et,...Z},Tt=Q=>{D=!0,f.has(Q)&&(I=!0,f.delete(Q)),w.needsAnimating[Q]=!0;const tt=t.getValue(Q);tt&&(tt.liveStyle=!1)};for(const Q in Et){const tt=Z[Q],gt=et[Q];if(g.hasOwnProperty(Q))continue;let ot=!1;Es(tt)&&Es(gt)?ot=!da(tt,gt):ot=tt!==gt,ot?tt!=null?Tt(Q):f.add(Q):tt!==void 0&&f.has(Q)?Tt(Q):w.protectedKeys[Q]=!0}w.prevProp=A,w.prevResolvedValues=Z,w.isActive&&(g={...g,...Z}),s&&t.blockInitialAnimation&&(D=!1);const G=k&&O;D&&(!G||I)&&d.push(...K.map(Q=>{const tt={type:x};if(typeof Q=="string"&&s&&!G&&t.manuallyAnimateOnMount&&t.parent){const{parent:gt}=t,ot=Ee(gt,Q);if(gt.enteringChildren&&ot){const{delayChildren:dn}=ot.transition||{};tt.delay=ua(gt.enteringChildren,t,dn)}}return{animation:Q,options:tt}}))}if(f.size){const P={};if(typeof u.initial!="boolean"){const x=Ee(t,Array.isArray(u.initial)?u.initial[0]:u.initial);x&&x.transition&&(P.transition=x.transition)}f.forEach(x=>{const w=t.getBaseTarget(x),A=t.getValue(x);A&&(A.liveStyle=!0),P[x]=w??null}),d.push({animation:P})}let b=!!d.length;return s&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(b=!1),s=!1,b?e(d):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();t.variantChildren?.forEach(d=>d.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const d in n)n[d].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 ae{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Cd extends ae{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 ae{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 on(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function un(t){return{point:{x:t.pageX,y:t.pageY}}}const kd=t=>e=>or(e)&&t(e,un(e));function Ge(t,e,n,s){return on(t,e,kd(n),s)}const ma=1e-4,Md=1-ma,Ed=1+ma,pa=.01,Dd=0-pa,Vd=0+pa;function xt(t){return t.max-t.min}function Nd(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=xt(n)/xt(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<=Vd||isNaN(t.translate))&&(t.translate=0)}function Ye(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+xt(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+xt(e)}function Je(t,e,n){di(t.x,e.x,n.x),di(t.y,e.y,n.y)}function jt(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,y=Id(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:b}=f,{timestamp:P}=ft;this.history.push({...b,timestamp:P});const{onStart:x,onMove:w}=this.handlers;g||(x&&x(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=rs(g,this.transformPagePoint),nt.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:y,onSessionEnd:b,resumeAnimation:P}=this.handlers;if(this.dragSnapToOrigin&&P&&P(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=is(f.type==="pointercancel"?this.lastMoveEventInfo:rs(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,x),b&&b(f,x)},!or(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=un(e),c=rs(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=ft;this.history=[{...u,timestamp:l}];const{onSessionStart:d}=n;d&&d(e,is(c,this.history)),this.removeListeners=an(Ge(this.contextWindow,"pointermove",this.handlePointerMove),Ge(this.contextWindow,"pointerup",this.handlePointerUp),Ge(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),ie(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>Nt(e)));)n--;if(!s)return{x:0,y:0};const o=kt(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=xt(t),r=xt(e);return r>s?n=tn(e.min,e.max-s,t.min):s>r&&(n=tn(t.min,t.max-r,e.min)),qt(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 Ns=.35;function _d(t=Ns){return t===!1?t=0:t===!0&&(t=Ns),{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=ct(),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=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(un(d).point)},i=(d,f)=>{const{drag:g,dragPropagation:y,onDragStart:b}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Zl(g),!this.openDragLock))return;this.latestPointerEvent=d,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),jt(x=>{let w=this.getAxisMotionValue(x).get()||0;if(Bt.test(w)){const{projection:A}=this.visualElement;if(A&&A.layout){const C=A.layout.layoutBox[x];C&&(w=xt(C)*(parseFloat(w)/100))}}this.originPoint[x]=w}),b&&nt.postRender(()=>b(d,f)),Ds(this.visualElement,"transform");const{animationState:P}=this.visualElement;P&&P.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:b,onDrag:P}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:x}=f;if(y&&this.currentDirection===null){this.currentDirection=qd(x),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",f.point,x),this.updateAxis("y",f.point,x),this.visualElement.render(),P&&P(d,f)},c=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>jt(d=>this.getAnimationState(d)==="paused"&&this.getAxisMotionValue(d).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&&nt.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&&Ce(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&&jt(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||!Ce(e))return!1;const s=e.current;Ht(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=jt(l=>{if(!Cn(l,n,this.currentDirection))return;let d=c&&c[l]||{};i&&(d={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,y={type:"inertia",velocity:s?e[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(l,y)});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(){jt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){jt(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){jt(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(!Ce(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};jt(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(),jt(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=Ge(e,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Ce(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()),nt.read(s);const i=on(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(jt(l=>{const d=this.getAxisMotionValue(l);d&&(this.originPoint[l]+=c[l].translate,d.set(d.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=Ns,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 ae{constructor(e){super(e),this.removeGroupControls=Mt,this.removeListeners=Mt,this.controls=new Kd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Mt}unmount(){this.removeGroupControls(),this.removeListeners()}}const xi=t=>(e,n)=>{t&&nt.postRender(()=>t(e,n))};class Xd extends ae{constructor(){super(...arguments),this.removePointerDownListener=Mt}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&&nt.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Ge(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 qe={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=oe.parse(t);if(r.length>5)return s;const o=oe.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()||nt.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 h.jsx(Yd,{...t,layoutGroup:s,switchLayoutGroup:m.useContext(Jo),isPresent:e,safeToRemove:n})}const Jd={borderRadius:{...qe,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:qe,borderTopRightRadius:qe,borderBottomLeftRadius:qe,borderBottomRightRadius:qe,boxShadow:Gd};function Zd(t,e,n){const s=pt(t)?t:De(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=bt.now(),s=({timestamp:r})=>{const o=r-n;o>=e&&(ie(s),t(o-e))};return nt.setup(s,!0),()=>ie(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),(Bt.test(u)||Bt.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,Mt);function wa(t,e,n){return s=>s<t?0:s>e?1:n(tn(t,e,s))}function Si(t,e){t.min=e.min,t.max=e.max}function Pt(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(Bt.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 xt(t.x)/xt(t.y)}function Vi(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:d,rotateY:f,skewX:g,skewY:y}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),d&&(s+=`rotateX(${d}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),y&&(s+=`skewY(${y}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",nt,!(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,d=0;const f=()=>this.root.updateBlockedByResize=!1;nt.read(()=>{d=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==d&&(d=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:d,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||u.getDefaultTransition()||Ph,{onLayoutAnimationStart:b,onLayoutAnimationComplete:P}=u.getProps(),x=!this.targetLayout||!Sa(this.targetLayout,g),w=!d&&f;if(this.options.layoutRoot||this.resumeFrom||w||d&&(x||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const A={...sr(y,"layout"),onPlay:b,onComplete:P};(u.shouldReduceMotion||this.options.layoutRoot)&&(A.delay=0,A.type=!1),this.startAnimation(A),this.setAnimationOrigin(l,w)}else d||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(),ie(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 d=this.path[l];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.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(Ni);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=bt.now();ft.delta=qt(0,1e3/60,a-ft.timestamp),ft.timestamp=a,ft.isProcessing=!0,Yn.update.process(ft),Yn.preRender.process(ft),Yn.render.process(ft),ft.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,nt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){nt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!xt(this.snapshot.measuredBox.x)&&!xt(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=ct(),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 ct();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(kh))){const{scroll:u}=this.root;u&&(Pe(a.x,u.offset.x),Pe(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ct();if(Pt(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:d}=u;u!==this.root&&l&&d.layoutScroll&&(l.wasRoot&&Pt(a,i),Pe(a.x,l.offset.x),Pe(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=ct();Pt(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&&je(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),ge(l.latestValues)&&je(c,l.latestValues)}return ge(this.latestValues)&&je(c,this.latestValues),c}removeTransform(i){const a=ct();Pt(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=ct(),d=u.measurePageBox();Pt(l,d),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!==ft.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:d}=this.options;if(!(!this.layout||!(l||d))){if(this.resolvedRelativeTargetAt=ft.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ct(),this.relativeTargetOrigin=ct(),Je(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Pt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ct(),this.targetWithTransforms=ct()),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):Pt(this.target,this.layout.layoutBox),ea(this.target,this.targetDelta)):Pt(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=ct(),this.relativeTargetOrigin=ct(),Je(this.relativeTargetOrigin,this.target,f.target),Pt(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===ft.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;Pt(this.layoutCorrected,this.layout.layoutBox);const d=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=ct());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)),Ye(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!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=ke(),this.projectionDelta=ke(),this.projectionDeltaWithTransform=ke()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},d=ke();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ct(),g=c?c.source:void 0,y=this.layout?this.layout.source:void 0,b=g!==y,P=this.getStack(),x=!P||P.members.length<=1,w=!!(b&&!x&&this.options.crossfade===!0&&!this.path.some(Ch));this.animationProgress=0;let A;this.mixTargetDelta=C=>{const R=C/1e3;Oi(d.x,i.x,R),Oi(d.y,i.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Je(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Ah(this.relativeTarget,this.relativeTargetOrigin,f,R),A&&lh(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=ct()),Pt(A,this.relativeTarget)),b&&(this.animationValues=l,sh(l,u,this.latestValues,R,w,x)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ie(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=nt.update(()=>{Dn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=De(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||ct();const d=xt(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+d;const f=xt(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Pt(a,c),je(a,l),Ye(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 d=dh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(d=c(l,d)),i.transform=d;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 y in rn){if(l[y]===void 0)continue;const{correct:b,applyTo:P,isCSSVariable:x}=rn[y],w=d==="none"?l[y]:b(l[y],u);if(P){const A=P.length;for(let C=0;C<A;C++)i[P[C]]=w}else x?this.options.visualElement.renderState.vars[y]=w:i[y]=w}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(Ni),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"?jt(l=>{const d=o?e.measuredBox[l]:e.layoutBox[l],f=xt(d);d.min=n[l].min,d.max=d.min+f}):Pa(r,e.layoutBox,n)&&jt(l=>{const d=o?e.measuredBox[l]:e.layoutBox[l],f=xt(n[l]);d.max=d.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[l].max=t.relativeTarget[l].min+f)});const i=ke();Ye(i,n,e.layoutBox);const a=ke();o?Ye(a,t.applyTransform(s,!0),e.measuredBox):Ye(a,n,e.layoutBox);const c=!Ta(i);let u=!1;if(!t.resumeFrom){const l=t.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:d,layout:f}=l;if(d&&f){const g=ct();Je(g,e.layoutBox,d.layoutBox);const y=ct();Je(y,n,f.layoutBox),Sa(g,y)||(u=!0),l.options.layoutRoot&&(t.relativeTarget=y,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 Ni(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:Mt;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"&&!Nd(Di(e),Di(n),.2)}function kh(t){return t!==t.root&&t.scroll?.wasRoot}const Mh=Ca({attachResizeListener:(t,e)=>on(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&&nt.postRender(()=>o(e,un(e)))}class Dh extends ae{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 Vh extends ae{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=an(on(this.node.current,"focus",()=>this.onFocus()),on(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&&nt.postRender(()=>o(e,un(e)))}class Nh extends ae{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 ae{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:d}=this.node.getProps(),f=u?l:d;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:Nh},focus:{Feature:Vh},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"),$t=Symbol.for("@arcteninc/core:originalName");function qh(t,e){return t[$t]=e,t}function Hh(t,e,n,s){if(typeof t!="function")return null;const r=t[$t];if(r){const a=e[r];if(a&&!n.has(a.name))return{fn:t,meta:a}}const o=t.name;let i;if(o&&(i=e[o],i&&!n.has(i.name)))return t[$t]=i.name,{fn:t,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=e[a],i))return t[$t]=i.name,{fn:t,meta:i}}else if(i=Object.values(e).find(c=>!n.has(c.name)),i)return t[$t]=i.name,{fn:t,meta:i};return null}function Ea(t,e){let n,s;if(!e)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{C.contains(v)&&C.removeChild(v)}},[e]),h.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 l=Fs(hu),u=m.useId();let d=!0,f=m.useMemo(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:r,onExitComplete:g=>{l.set(g,!0);for(const y of l.values())if(!y)return;s&&s()},register:g=>(l.set(g,!1),()=>l.delete(g))}),[n,l,s]);return o&&d&&(f={...f}),m.useMemo(()=>{l.forEach((g,y)=>l.set(y,!1))},[n]),Ot.useEffect(()=>{!n&&!l.size&&s&&s()},[n]),i==="popLayout"&&(t=h.jsx(uu,{isPresent:n,anchorX:a,root:c,children:t})),h.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[l,u]=Bo(i),d=m.useMemo(()=>Yr(t),[t]),f=i&&!l?[]:d.map(An),g=m.useRef(!0),y=m.useRef(d),v=Fs(()=>new Map),[C,x]=m.useState(d),[w,S]=m.useState(d);Xi(()=>{g.current=!1,y.current=d;for(let I=0;I<w.length;I++){const k=An(w[I]);f.includes(k)?v.delete(k):v.get(k)!==!0&&v.set(k,!1)}},[w,f.length,f.join("-")]);const P=[];if(d!==C){let I=[...d];for(let k=0;k<w.length;k++){const N=w[k],$=An(N);f.includes($)||(I.splice(k,0,N),P.push(N))}return o==="wait"&&P.length&&(I=P),S(Yr(I)),x(d),null}process.env.NODE_ENV!=="production"&&o==="wait"&&w.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:V}=m.useContext(Ls);return h.jsx(h.Fragment,{children:w.map(I=>{const k=An(I),N=i&&!l?!1:d===w||f.includes(k),$=()=>{if(v.has(k))v.set(k,!0);else return;let L=!0;v.forEach(Z=>{Z||(L=!1)}),L&&(V?.(),S(y.current),i&&u?.(),s&&s())};return h.jsx(du,{isPresent:N,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:N?void 0:$,anchorX:a,children:I},k)})})},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)})},[]),h.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 l=Ro(a,rr[i]);if(!c){r=!1;const u=wu[i]||i;s+=`${u}(${l}) `}n&&(e[i]=l)}}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 l=e[c];if($e.has(c)){i=!0;continue}else if(Hs(c)){r[c]=l;continue}else{const u=Ro(l,rr[c]);c.startsWith("origin")?(a=!0,o[c]=u):s[c]=u}}if(e.transform||(i||n?s.transform=Su(e,t.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:u=0}=o;s.transformOrigin=`${c} ${l} ${u}`}}const hr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Wo(t,e,n){for(const s in e)!pt(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]=O.transform(-s);const i=O.transform(e),a=O.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,l,u){if(dr(t,a,l),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:f}=t;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),s!==void 0&&(d.scale=s),r!==void 0&&Mu(d,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 Vu(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),l=t!==m.Fragment?{...c,...a,ref:n}:{},{children:u}=e,d=m.useMemo(()=>pt(u)?u.get():u,[u]);return m.createElement(t,{...l,children:d})}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 pt(t)?t.get():t}function Nu({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),l=Uo(t);e&&l&&!c&&t.inherit!==!1&&(i===void 0&&(i=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||i===!1;const d=u?a:i;if(d&&typeof d!="boolean"&&!zn(d)){const f=Array.isArray(d)?d:[d];for(let g=0;g<f.length;g++){const y=mr(t,f[g]);if(y){const{transitionEnd:v,transition:C,...x}=y;for(const w in x){let S=x[w];if(Array.isArray(S)){const P=u?S.length-1:0;S=S[P]}S!==null&&(r[w]=S)}for(const w in v)r[w]=v[w]}}}return r}const Xo=t=>(e,n)=>{const s=m.useContext(Bn),r=m.useContext($n),o=()=>Nu(t,e,s,r);return n?o():Fs(o)};function pr(t,e,n){const{style:s}=t,r={};for(const o in s)(pt(s[o])||e.style&&pt(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(pt(t[r])||pt(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,l=m.useRef(null);s=s||i.renderer,!l.current&&s&&(l.current=s(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=m.useContext(Jo);u&&!u.projection&&r&&(u.type==="html"||u.type==="svg")&&zu(l.current,n,r,d);const f=m.useRef(!1);m.useInsertionEffect(()=>{u&&f.current&&u.update(n,a)});const g=n[Yo],y=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return Xi(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),y.current&&u.animationState&&u.animationState.animateChanges())}),m.useEffect(()=>{u&&(!y.current&&u.animationState&&u.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),y.current=!1),u.enteringChildren=void 0)}),u}function zu(t,e,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=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:u,layoutScroll:c,layoutRoot:l})}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 l;const u={...m.useContext(ar),...a,layoutId:Uu(a)},{isStatic:d}=u,f=vu(a),g=r(a,d);if(!d&&$s){_u(u,n);const y=Wu(u);l=y.MeasureLayout,f.visualElement=Bu(t,g,u,s,y.ProjectionNode)}return h.jsxs(Bn.Provider,{value:f,children:[l&&f.visualElement?h.jsx(l,{visualElement:f.visualElement,...u}):null,Vu(t,a,Fu(g,f.visualElement,c),g,d,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(pt(r))t.addValue(s,r);else if(pt(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=St.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,st.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,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:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const g=d[f];c[f]!==void 0&&pt(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=No(e,n)),this.setBaseTarget(e,pt(s)?s.get():s)),pt(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&&!pt(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;pt(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=Vo(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 Ne(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=Ne(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!!(pt(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:l,...u}){return!!Object.keys(u).length}const yr=(t,e,n,s={},r,o)=>i=>{const a=sr(s,t)||{},c=a.delay||s.delay||0;let{elapsed:l=0}=s;l=l-Lt(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-l,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(u,md(t,u)),u.duration&&(u.duration=Lt(u.duration)),u.repeatDelay&&(u.repeatDelay=Lt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(As(u),u.delay===0&&(d=!0)),(qt.instantAnimations||qt.skipAnimations)&&(d=!0,As(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const f=ld(u.keyframes,a);if(f!==void 0){st.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new er(u):new Il(u)};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=[],l=r&&t.animationState&&t.animationState.getState()[r];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),f=a[u];if(f===void 0||l&&gd(l,u))continue;const g={delay:n,...sr(o||{},u)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===y&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const x=ca(t);if(x){const w=window.MotionHandoffAnimation(x,u,st);w!==null&&(g.startTime=w,v=!0)}}Ds(t,u),d.start(yr(u,d,f,t.shouldReduceMotion&&Mo.has(u)?{type:!1}:g,t,v));const C=d.animation;C&&c.push(C)}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((l,u)=>l.sortNodePosition(u)).indexOf(e),i=t.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Vs(t,e,n={}){const s=Ne(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:l=0,staggerChildren:u,staggerDirection:d}=r;return yd(t,e,c,l,u,d,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,l]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>l())}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(Vs(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=>Vs(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Vs(t,e,n);else{const r=typeof e=="function"?Ne(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=>(l,u)=>{const d=Ne(t,u,c==="exit"?t.presenceContext?.custom:void 0);if(d){const{transition:f,transitionEnd:g,...y}=d;l={...l,...y,...g}}return l};function o(c){e=c(t)}function i(c){const{props:l}=t,u=ha(t.parent)||{},d=[],f=new Set;let g={},y=1/0;for(let C=0;C<wd;C++){const x=bd[C],w=n[x],S=l[x]!==void 0?l[x]:u[x],P=an(S),V=x===c?w.isActive:null;V===!1&&(y=C);let I=S===u[x]&&S!==l[x]&&P;if(I&&s&&t.manuallyAnimateOnMount&&(I=!1),w.protectedKeys={...g},!w.isActive&&V===null||!S&&!w.prevProp||zn(S)||typeof S=="boolean")continue;const k=Ad(w.prevProp,S);let N=k||x===c&&w.isActive&&!I&&P||C>y&&P,$=!1;const L=Array.isArray(S)?S:[S];let Z=L.reduce(r(x),{});V===!1&&(Z={});const{prevResolvedValues:Y={}}=w,mt={...Y,...Z},Vt=ot=>{N=!0,f.has(ot)&&($=!0,f.delete(ot)),w.needsAnimating[ot]=!0;const ct=t.getValue(ot);ct&&(ct.liveStyle=!1)};for(const ot in mt){const ct=Z[ot],et=Y[ot];if(g.hasOwnProperty(ot))continue;let ut=!1;Es(ct)&&Es(et)?ut=!da(ct,et):ut=ct!==et,ut?ct!=null?Vt(ot):f.add(ot):ct!==void 0&&f.has(ot)?Vt(ot):w.protectedKeys[ot]=!0}w.prevProp=S,w.prevResolvedValues=Z,w.isActive&&(g={...g,...Z}),s&&t.blockInitialAnimation&&(N=!1);const gt=I&&k;N&&(!gt||$)&&d.push(...L.map(ot=>{const ct={type:x};if(typeof ot=="string"&&s&&!gt&&t.manuallyAnimateOnMount&&t.parent){const{parent:et}=t,ut=Ne(et,ot);if(et.enteringChildren&&ut){const{delayChildren:oe}=ut.transition||{};ct.delay=ua(et.enteringChildren,t,oe)}}return{animation:ot,options:ct}}))}if(f.size){const C={};if(typeof l.initial!="boolean"){const x=Ne(t,Array.isArray(l.initial)?l.initial[0]:l.initial);x&&x.transition&&(C.transition=x.transition)}f.forEach(x=>{const w=t.getBaseTarget(x),S=t.getValue(x);S&&(S.liveStyle=!0),C[x]=w??null}),d.push({animation:C})}let v=!!d.length;return s&&(l.initial===!1||l.initial===l.animate)&&!t.manuallyAnimateOnMount&&(v=!1),s=!1,v?e(d):Promise.resolve()}function a(c,l){if(n[c].isActive===l)return Promise.resolve();t.variantChildren?.forEach(d=>d.animationState?.setActive(c,l)),n[c].isActive=l;const u=i(c);for(const d in n)n[d].protectedKeys={};return u}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,Vd=0+pa;function xt(t){return t.max-t.min}function Nd(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=xt(n)/xt(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<=Vd||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+xt(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+xt(e)}function tn(t,e,n){di(t.x,e.x,n.x),di(t.y,e.y,n.y)}function Mt(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,y=Id(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:v}=f,{timestamp:C}=ft;this.history.push({...v,timestamp:C});const{onStart:x,onMove:w}=this.handlers;g||(x&&x(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),w&&w(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:y,onSessionEnd:v,resumeAnimation:C}=this.handlers;if(this.dragSnapToOrigin&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=is(f.type==="pointercancel"?this.lastMoveEventInfo:rs(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,x),v&&v(f,x)},!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:l}=c,{timestamp:u}=ft;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=n;d&&d(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=Et(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=xt(t),r=xt(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 Ns=.35;function _d(t=Ns){return t===!1?t=0:t===!0&&(t=Ns),{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=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(fn(d).point)},i=(d,f)=>{const{drag:g,dragPropagation:y,onDragStart:v}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Zl(g),!this.openDragLock))return;this.latestPointerEvent=d,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),Mt(x=>{let w=this.getAxisMotionValue(x).get()||0;if(Ut.test(w)){const{projection:S}=this.visualElement;if(S&&S.layout){const P=S.layout.layoutBox[x];P&&(w=xt(P)*(parseFloat(w)/100))}}this.originPoint[x]=w}),v&&st.postRender(()=>v(d,f)),Ds(this.visualElement,"transform");const{animationState:C}=this.visualElement;C&&C.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:v,onDrag:C}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:x}=f;if(y&&this.currentDirection===null){this.currentDirection=qd(x),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,x),this.updateAxis("y",f.point,x),this.visualElement.render(),C&&C(d,f)},c=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>Mt(d=>this.getAnimationState(d)==="paused"&&this.getAxisMotionValue(d).animation?.play()),{dragSnapToOrigin:u}=this.getProps();this.panSession=new ya(e,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,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&&Mt(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||{},l=Mt(u=>{if(!Cn(u,n,this.currentDirection))return;let d=c&&c[u]||{};i&&(d={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,y={type:"inertia",velocity:s?e[u]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,y)});return Promise.all(l).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(){Mt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Mt(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){Mt(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};Mt(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(),Mt(i=>{if(!Cn(i,e,null))return;const a=this.getAxisMotionValue(i),{min:c,max:l}=this.constraints[i];a.set(it(c,l,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:l,dragListener:u=!0}=this.getProps();l&&u&&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:l})=>{this.isDragging&&l&&(Mt(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].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=Ns,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=Dt,this.removeListeners=Dt,this.controls=new Kd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Dt}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=Dt}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(O.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 l=it(a,c,.5);return typeof r[2+i]=="number"&&(r[2+i]/=l),typeof r[3+i]=="number"&&(r[3+i]/=l),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 h.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=pt(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=St.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"||O.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),l=Ti(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||wi(c)===wi(l)?(t[a]=Math.max(it(bi(c),bi(l),s),0),(Ut.test(l)||Ut.test(c))&&(t[a]+="%")):t[a]=l}(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,Dt);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 kt(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 xt(t.x)/xt(t.y)}function Vi(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:l,rotate:u,rotateX:d,rotateY:f,skewX:g,skewY:y}=n;l&&(s=`perspective(${l}px) ${s}`),u&&(s+=`rotate(${u}deg) `),d&&(s+=`rotateX(${d}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),y&&(s+=`skewY(${y}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:l}=this.options;if(l&&!l.current&&l.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const f=()=>this.root.updateBlockedByResize=!1;st.read(()=>{d=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=eh(f,250),Dn.hasAnimatedSinceResize&&(Dn.hasAnimatedSinceResize=!1,this.nodes.forEach(Ii)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||l.getDefaultTransition()||Ph,{onLayoutAnimationStart:v,onLayoutAnimationComplete:C}=l.getProps(),x=!this.targetLayout||!Sa(this.targetLayout,g),w=!d&&f;if(this.options.layoutRoot||this.resumeFrom||w||d&&(x||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...sr(y,"layout"),onPlay:v,onComplete:C};(l.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,w)}else d||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 u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Ni);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=St.now();ft.delta=Wt(0,1e3/60,a-ft.timestamp),ft.timestamp=a,ft.isProcessing=!0,Yn.update.process(ft),Yn.preRender.process(ft),Yn.render.process(ft),ft.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&&!xt(this.snapshot.measuredBox.x)&&!xt(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(),l=c?c(this.latestValues,""):void 0,u=l!==this.prevTransformTemplateValue;i&&this.instance&&(a||ge(this.latestValues)||u)&&(r(this.instance,l),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:l}=this.root;l&&(Me(a.x,l.offset.x),Me(a.y,l.offset.y))}return a}removeElementScroll(i){const a=at();if(kt(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const l=this.path[c],{scroll:u,options:d}=l;l!==this.root&&u&&d.layoutScroll&&(u.wasRoot&&kt(a,i),Me(a.x,u.offset.x),Me(a.y,u.offset.y))}return a}applyTransform(i,a=!1){const c=at();kt(c,i);for(let l=0;l<this.path.length;l++){const u=this.path[l];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&Ee(c,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),ge(u.latestValues)&&Ee(c,u.latestValues)}return ge(this.latestValues)&&Ee(c,this.latestValues),c}removeTransform(i){const a=at();kt(a,i);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!ge(l.latestValues))continue;js(l.latestValues)&&l.updateSnapshot();const u=at(),d=l.measurePageBox();kt(u,d),ji(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,u)}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!==ft.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:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=ft.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),kt(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):kt(this.target,this.layout.layoutBox),ea(this.target,this.targetDelta)):kt(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),kt(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===ft.timestamp&&(c=!1),c)return;const{layout:l,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(l||u))return;kt(this.layoutCorrected,this.layout.layoutBox);const d=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!==d||this.treeScale.y!==f||!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=De(),this.projectionDelta=De(),this.projectionDeltaWithTransform=De()}setAnimationOrigin(i,a=!1){const c=this.snapshot,l=c?c.latestValues:{},u={...this.latestValues},d=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,y=this.layout?this.layout.source:void 0,v=g!==y,C=this.getStack(),x=!C||C.members.length<=1,w=!!(v&&!x&&this.options.crossfade===!0&&!this.path.some(Ch));this.animationProgress=0;let S;this.mixTargetDelta=P=>{const V=P/1e3;Oi(d.x,i.x,V),Oi(d.y,i.y,V),this.setTargetDelta(d),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,V),S&&lh(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=at()),kt(S,this.relativeTarget)),v&&(this.animationValues=u,sh(u,l,this.latestValues,V,w,x)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=V},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:l,latestValues:u}=i;if(!(!a||!c||!l)){if(this!==i&&this.layout&&l&&Pa(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||at();const d=xt(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+d;const f=xt(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}kt(a,c),Ee(a,u),Qe(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new uh),this.sharedNodes.get(i).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.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 l=this.getStack();l&&l.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 l={};c.z&&cs("z",i,l,this.animationValues);for(let u=0;u<as.length;u++)cs(`rotate${as[u]}`,i,l,this.animationValues),cs(`skew${as[u]}`,i,l,this.animationValues);i.render();for(const u in l)i.setStaticValue(u,l[u]),this.animationValues&&(this.animationValues[u]=l[u]);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 l=this.getLead();if(!this.projectionDelta||!this.layout||!l.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 u=l.animationValues||l.latestValues;this.applyTransformsToTarget();let d=dh(this.projectionDeltaWithTransform,this.treeScale,u);c&&(d=c(u,d)),i.transform=d;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,l.animationValues?i.opacity=l===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:i.opacity=l===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const y in cn){if(u[y]===void 0)continue;const{correct:v,applyTo:C,isCSSVariable:x}=cn[y],w=d==="none"?u[y]:v(u[y],l);if(C){const S=C.length;for(let P=0;P<S;P++)i[C[P]]=w}else x?this.options.visualElement.renderState.vars[y]=w:i[y]=w}this.options.layoutId&&(i.pointerEvents=l===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(Ni),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"?Mt(u=>{const d=o?e.measuredBox[u]:e.layoutBox[u],f=xt(d);d.min=n[u].min,d.max=d.min+f}):Pa(r,e.layoutBox,n)&&Mt(u=>{const d=o?e.measuredBox[u]:e.layoutBox[u],f=xt(n[u]);d.max=d.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].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 l=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:d,layout:f}=u;if(d&&f){const g=at();tn(g,e.layoutBox,d.layoutBox);const y=at();tn(y,n,f.layoutBox),Sa(g,y)||(l=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=g,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}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 Ni(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:Dt;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"&&!Nd(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 Vh 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 Nh 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:l}=c;if(this.isInView===l||(this.isInView=l,o&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),f=l?u:d;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:Nh},focus:{Feature:Vh},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!
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[$t]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${u}". This tool will be excluded.
19
- To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function Xh({toolName:t,description:e,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:t})}),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(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(dt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:h.jsx(dt.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 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(dt.ChevronDown,{className:"h-3 w-3"}):h.jsx(dt.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(dt.X,{className:"h-3 w-3"}):s?h.jsx(dt.Zap,{className:"h-3 w-3"}):h.jsx(dt.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),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 Yh({...t}){return h.jsx(Os.Root,{"data-slot":"collapsible",...t})}function Jh({...t}){return h.jsx(Os.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function Zh({...t}){return h.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:h.jsx(m.Suspense,{fallback:null,children:h.jsx(Qh,{className:ht("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 h.jsx(o,{animate:{backgroundPosition:"0% center"},className:ht("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,Va=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,d]=Pr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[y,b]=m.useState(null);m.useEffect(()=>{e?y===null&&b(Date.now()):y!==null&&(d(Math.ceil((Date.now()-y)/of)),b(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&c&&!f){const x=setTimeout(()=>{u(!1),g(!0)},rf);return()=>clearTimeout(x)}},[e,c,s,u,f]);const P=x=>{u(x)};return h.jsx(Da.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:u,duration:l},children:h.jsx(Yh,{className:ht("not-prose mb-4",t),onOpenChange:P,open:c,...a,children:i})})}),af=(t,e)=>t||e===0?h.jsx(nf,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Na=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=sf();return h.jsx(Jh,{className:ht("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??h.jsxs(h.Fragment,{children:[h.jsx(dt.BrainIcon,{className:"size-4"}),af(s,o),h.jsx(dt.ChevronDownIcon,{className:ht("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ra=m.memo(({className:t,children:e,...n})=>h.jsx(Zh,{className:ht("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:h.jsx(xr,{className:"grid gap-2",children:e})}));Va.displayName="Reasoning";Na.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 h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsxs("button",{className:ht("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(se,{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 • ",t.length]}),t.map(o=>h.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ht("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:_i(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 lf({text:t,citations:e,citationMap:n,referencesText:s,ResponseComponent:r,className:o}){const i=m.useRef(null),[a,c]=m.useState([]);m.useEffect(()=>{if(!i.current||e.length===0||n.size===0){n.size===0&&c([]);return}const l=i.current;let d,f=!1;const g=new WeakSet,y=()=>{if(!i.current||f)return;f=!0;const P=i.current,x=/\[(\d+)\]/g,w=document.createTreeWalker(P,NodeFilter.SHOW_TEXT,null),A=[];let C;for(;C=w.nextNode();)if(C.nodeType===Node.TEXT_NODE&&!g.has(C)){const k=C,O=k.textContent||"";let D=k.parentElement,I=!1;for(;D&&D!==P;){if(D.tagName==="A"||D.tagName==="CODE"||D.tagName==="PRE"){I=!0;break}D=D.parentElement}if(!I){const Z=Array.from(O.matchAll(x)).filter(et=>{if(!et[1])return!1;const Et=parseInt(et[1],10);return n.has(Et)});Z.length>0&&A.push({node:k,matches:Z})}}if(A.length===0){f=!1;return}const R=[];A.forEach(({node:k,matches:O})=>{g.add(k);const D=k.textContent||"",I=document.createDocumentFragment();let K=0;O.forEach(Z=>{if(!Z[1])return;Z.index!==void 0&&Z.index>K&&I.appendChild(document.createTextNode(D.slice(K,Z.index)));const et=document.createElement("span");et.className="inline-flex items-center citation-button-container";const Et=parseInt(Z[1],10);et.setAttribute("data-citation",Z[1]),I.appendChild(et),R.push({element:et,citationNum:Et}),K=(Z.index||0)+Z[0].length}),K<D.length&&I.appendChild(document.createTextNode(D.slice(K))),k.parentNode&&k.parentNode.replaceChild(I,k)}),R.length>0&&c(k=>{const O=new Set(k.map(K=>K.element)),D=k.filter(K=>K.element.isConnected),I=R.filter(K=>!O.has(K.element));return[...D,...I]}),f=!1},b=new MutationObserver(()=>{clearTimeout(d),d=setTimeout(y,100)});return b.observe(l,{childList:!0,subtree:!0,characterData:!0}),d=setTimeout(y,200),()=>{b.disconnect(),clearTimeout(d)}},[t,e,n]);const u=s?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:Array.from(n.entries()).sort(([l],[d])=>l-d).map(([l,d])=>h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium",children:["[",l,"]"]}),h.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:d})]},l))})]}):null;return h.jsxs("div",{className:o,children:[h.jsx("div",{ref:i,children:h.jsx(r,{children:t})}),a.filter(({element:l})=>l.isConnected).map(({element:l,citationNum:d},f)=>e.find(y=>y.number===d)?oc.createPortal(h.jsx(cf,{sources:e.map(y=>({number:y.number,url:y.url,domain:uf(y.url)})),citationNumber:d},`citation-${d}-${l}`),l,`citation-${d}-${f}`):null),u]})}function uf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function df(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=[];if(s&&s[1]){const g=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let b;for(;(b=y.exec(g))!==null;)if(b[1]&&b[2]){const P=parseInt(b[1],10),x=b[2].replace(/[.,;:!?]+$/,"");r.set(P,x),o.push({number:P,url:x})}}let i,a=e;s&&s[0]&&(i=s[0],a=e.replace(n,""));const c=[];let u=0;const l=/```[\s\S]*?```|`[^`]+`/g;let d;for(;(d=l.exec(a))!==null;)d.index>u&&c.push({type:"text",content:a.slice(u,d.index),start:u,end:d.index}),c.push({type:"code",content:d[0],start:d.index,end:d.index+d[0].length}),u=d.index+d[0].length;return u<a.length&&c.push({type:"text",content:a.slice(u),start:u,end:a.length}),{processedText:c.map(g=>{if(g.type==="code")return g.content;let y=g.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(P,x,w)=>{const A=parseInt(x,10);return r.has(A)||(r.set(A,w),o.push({number:A,url:w})),`[${A}]`}),y}).join(""),citations:o.sort((g,y)=>g.number-y.number),citationMap:r,referencesText:i}}function Ze(t){if(typeof t=="string")try{const e=JSON.parse(t);return Ze(e)}catch{return t}if(Array.isArray(t))return t.map(Ze);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=Ze(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 Ze(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?Ze(t):{}}function hf({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:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:b="https://api.arcten.com",user:P,state:x,onStateChange:w,allowStateEdits:A=!0,sources:C,ragConfig:R}){const k=m.useMemo(()=>R!==void 0?R:C&&C.length>0?{enabled:!0,organizationId:C[0],filters:void 0}:{enabled:!1},[C,R]),[O,D]=m.useState(null),I=m.useRef(null),[K,Z]=m.useState(null),[et,Et]=m.useState(null),Tt=m.useRef(null),G=x!==void 0,[Le,Q]=m.useState({}),tt=m.useRef({});G&&x?tt.current=x:G||(tt.current=Le);const[gt,ot]=m.useState(!1),[dn,ce]=m.useState(null),Gt=m.useRef(!1),[wt,zt]=m.useState(u),[St,Ut]=m.useState(i),[Rt,It]=m.useState(600),[Ot,_t]=m.useState(!1),[X,Yt]=m.useState(!1),[At,le]=m.useState(!1),[yt,we]=m.useState({x:100,y:100}),[hn,Te]=m.useState(!1),[Ct,fn]=m.useState({x:0,y:0}),[Fe,$e]=m.useState(!1),Be=m.useRef(null),Wt=m.useRef(null),[Jt,ze]=m.useState(""),[mn,_n]=m.useState(null),[pn,Wn]=m.useState("Thinking..."),[Ue,Zt]=m.useState(new Set),[Kn,j]=m.useState(""),[T,V]=m.useState([]),[F,B]=m.useState(!1),[z,q]=m.useState([]),[at,ut]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[mt,J]=m.useState(!1),[st,Lt]=m.useState(!1),[qn,gn]=m.useState([]),vr=m.useCallback(async(p,v=3)=>{if(!at||!I.current)return;const M=async()=>{const E=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,N=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:at,updates:p},format:"json"})});if(!N.ok){if(N.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const W=await N.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${N.status} ${W}`)}};for(let S=0;S<v;S++)try{await M(),ce(null);return}catch(E){if(S===v-1){const W=E instanceof Error?E:new Error(String(E));throw ce(W),console.error("Failed to sync state to Convex after retries:",E),W}await new Promise(W=>setTimeout(W,Math.pow(2,S)*100))}},[at,b,I]),_e=m.useMemo(()=>function(){return tt.current},[]),We=m.useMemo(()=>async function(v){const M={...tt.current,...v};tt.current=M,G||Q(M),w&&w(M);try{await vr(v)}catch(S){throw S}},[vr,w,G]);m.useEffect(()=>{G&&x&&(tt.current=x)},[G,x]);const ue=m.useMemo(()=>k?.enabled?async function(v,M=20,S){if(C&&C.length>1){const W=C.map(U=>fetch(`${b}/search`,{method:"POST",headers:{"Content-Type":"application/json",...I.current?{Authorization:`Bearer ${I.current}`}:{}},body:JSON.stringify({q:v,k:Math.min(M,100),organizationId:U,...Object.keys(N).length>0?{filters:N}:{}})}).then(_=>_.ok?_.json():null)),$=await Promise.all(W),Y=[];for(const U of $)U?.candidates&&Y.push(...U.candidates);Y.sort((U,_)=>{const vt=U.scores?.rerank||U.scores?.dense||0;return(_.scores?.rerank||_.scores?.dense||0)-vt});const H=Y.slice(0,M).map((U,_)=>{const vt=U.citation||U.url;return{rank:_+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:vt,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:v,total:Y.length,results:H,summary:`Found ${Y.length} relevant results across ${C.length} source(s) for "${v}". Top result: ${H[0]?.title||"N/A"}`}}const E=k.organizationId&&k.organizationId!=="default"?k.organizationId:void 0,N={...k.filters,...S};try{const W={q:v,k:Math.min(M,100)};E&&(W.organizationId=E),Object.keys(N).length>0&&(W.filters=N);const $={"Content-Type":"application/json"};I.current&&($.Authorization=`Bearer ${I.current}`);const Y=await fetch(`${b}/search`,{method:"POST",headers:$,body:JSON.stringify(W)});if(!Y.ok){const _=await Y.text();return{success:!1,error:`Search failed: ${Y.status} ${_}`}}const H=await Y.json(),U=H.candidates.map((_,vt)=>{const wn=_.citation||_.url;return{rank:vt+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 "${v}". Top result: ${U[0]?.title||"N/A"}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[R,b,I]),de=m.useMemo(()=>k?.enabled?async function(v,M){const S=k.organizationId&&k.organizationId!=="default"?k.organizationId:C&&C.length>0?C[0]:void 0;try{const E={"Content-Type":"application/json"};I.current&&(E.Authorization=`Bearer ${I.current}`);const N=await fetch(`${b}/fetch`,{method:"POST",headers:E,body:JSON.stringify({doc_id:v,block_ids:M,...S?{organizationId:S}:{}})});if(!N.ok){const $=await N.text();return{success:!1,error:`Fetch failed: ${N.status} ${$}`}}const W=await N.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||v}`}}catch(E){return{success:!1,error:E instanceof Error?E.message:"Unknown error occurred"}}}:null,[R,b,I]),he=m.useMemo(()=>{const p=[...l,...d,_e];return(!G||A)&&p.push(We),k?.enabled&&(ue&&p.push(ue),de&&p.push(de)),p},[l,d,_e,We,ue,de,G,A,k]),Hn=m.useMemo(()=>Ea(he,f),[he,f]),Kt=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:[]}}];(!G||A)&&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 v=[];return k?.enabled&&v.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,...v]},[Hn,G,A,k]),br=m.useMemo(()=>new Set(Kt.map(p=>p.name)),[Kt]),yn=m.useMemo(()=>Kt.filter(p=>p.name==="getState"?!0:p.name==="setState"?!G||A:br.has(p.name)),[Kt,br,G,A]),xn=m.useMemo(()=>{const p=new Map,v=new Map(Hn.map(M=>[M.name,M]));return p.set("getState",_e),(!G||A)&&p.set("setState",We),k?.enabled&&(ue&&p.set("searchDocs",ue),de&&p.set("fetchDocContent",de)),he.forEach(M=>{if(M===_e||M===We||M===ue||M===de)return;const S=M[$t];if(S){const N=v.get(S);if(N){p.set(N.name,M);return}}const E=Kt.find(N=>N.name===M.name);E&&p.set(E.name,M)}),p},[he,Kt,_e,We,ue,de,G,A,k]),Ke=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),k?.enabled&&(p.add("searchDocs"),p.add("fetchDocContent"));const v=new Map(Kt.map(M=>[M.name,M]));return d.forEach(M=>{const S=M[$t];if(S&&v.has(S))p.add(S);else{const E=Kt.find(N=>N.name===M.name);E&&p.add(E.name)}}),p},[d,Kt,k]),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&&zt(JSON.parse(p));const v=localStorage.getItem("arcten-sidebar-width");v&&Ut(parseInt(v));const M=localStorage.getItem("arcten-sidebar-height");M&&It(parseInt(M));const S=localStorage.getItem("arcten-sidebar-detached");S&&Yt(JSON.parse(S));const E=localStorage.getItem("arcten-sidebar-position");if(E){const W=JSON.parse(E),$=50,Y=Math.max($-i,Math.min(W.x,window.innerWidth-$)),H=Math.max(0,Math.min(W.y,window.innerHeight-$));we({x:Y,y:H})}const N=localStorage.getItem("arcten-sidebar-minimized");N&&le(JSON.parse(N)),$e(!0)}},[]);const Qt=m.useMemo(()=>P,[P?.id]);m.useEffect(()=>((async()=>{try{const v=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Qt})});if(!v.ok)throw new Error("Failed to fetch token");const M=await v.json();D(M.clientToken),I.current=M.clientToken,Et(M.expiresAt),Z(null)}catch(v){Z(v instanceof Error?v.message:"Failed to fetch token")}})(),()=>{Tt.current&&clearTimeout(Tt.current)}),[y,Qt]),m.useEffect(()=>{if(!et)return;Tt.current&&clearTimeout(Tt.current);const p=Math.floor(Date.now()/1e3),v=et-p,S=Math.max(0,v-5);return Tt.current=setTimeout(async()=>{try{const E=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Qt})});if(!E.ok)throw new Error("Failed to refresh token");const N=await E.json();D(N.clientToken),I.current=N.clientToken,Et(N.expiresAt),Z(null)}catch(E){console.error("Token refresh failed:",E),Z(E instanceof Error?E.message:"Failed to refresh token")}},S*1e3),()=>{Tt.current&&clearTimeout(Tt.current)}},[et,y,Qt]),m.useEffect(()=>{(async()=>{if(he.length!==0)try{const v=he.map(S=>({name:S.name,code:S.toString()})),M=await fetch(`${b}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:v})});if(M.ok){const S=await M.json();V(S.tools)}}catch(v){console.error("Failed to fetch tool descriptions:",v)}})()},[he]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{_n(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{j(window.location.pathname)};p(),window.addEventListener("popstate",p);const v=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(v)}},[]);const Xn=m.useCallback(async()=>{if(!(!Qt?.id||!O)){Lt(!0);try{const v=await(await fetch(`${b}/conversations`,{headers:{Authorization:`Bearer ${O}`}})).json();q(v.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{Lt(!1)}}},[Qt?.id,O,b]);m.useEffect(()=>{Qt?.id&&O&&Xn()},[Qt?.id,O,Xn]);function Ia(p){const v=Math.floor((Date.now()-p)/1e3);return v<60?"now":v<3600?`${Math.floor(v/60)}m`:v<86400?`${Math.floor(v/3600)}h`:`${Math.floor(v/86400)}d`}function Oa(){const p=crypto.randomUUID();ut(p),bn([]),gn([]),J(!1);const v=G?x||{}:{};tt.current=v,G||Q(v),w&&w(v),Gt.current=!1}async function La(p){if(O)try{await fetch(`${b}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${O}`}}),q(z.filter(v=>v._id!==p)),p===at&&Oa()}catch(v){console.error("Failed to delete conversation:",v)}}async function Fa(p){ut(p.chatId),J(!1),Lt(!0);try{const v=await fetch(`${b}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${I.current}`}});if(!v.ok)throw new Error(`Failed to fetch messages: ${v.statusText}`);const S=(await v.json()).messages||[];bn(S),gn(S)}catch(v){console.error("Failed to load conversation messages:",v);const M=p.messages||[];bn(M),gn(M)}finally{Lt(!1)}}const $a=async(p,v={})=>{const M=v.headers?new Headers(v.headers):new Headers;return M.delete("user-agent"),M.delete("User-Agent"),fetch(p,{...v,headers:M})},{messages:te,sendMessage:Ba,status:Ft,error:Tr,stop:vn,addToolResult:fe,setMessages:bn}=Wi.useChat({id:at||void 0,transport:new Vn.DefaultChatTransport({api:`${b}/chat`,fetch:$a,headers:()=>{const p={};return I.current&&(p.Authorization=`Bearer ${I.current}`),p},body:()=>({tools:yn.map(v=>({name:v.name,description:v.description,inputSchema:v.jsonSchema})),systemPrompt:g,currentRoute:Kn,state:tt.current})}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=te[te.length-1];if(!p||p.role!=="assistant")return;const v=p.parts?.filter(M=>M.type?.startsWith("tool-")&&M.state==="input-available"&&typeof M.toolCallId=="string"&&M.input!==void 0)||[];for(const M of v){const S=M,E=S.type?.replace("tool-","")||"",N=S.toolCallId;if(Ke.has(E)){if(Ue.has(N))continue;Zt($=>$.has(N)?$:new Set($).add(N)),(async()=>{try{const $=xn.get(E);if(!$){console.warn(`[ArctenAgent] Tool ${E} not found in toolsMap. Available tools:`,Array.from(xn.keys())),fe({toolCallId:N,tool:E,output:`Error: Tool ${E} not found`}),Zt(_=>{const vt=new Set(_);return vt.delete(N),vt});return}const Y=ds(S.input),H=yn.find(_=>_.name===E);let U;if(H&&H.jsonSchema?.properties){const vt=Object.keys(H.jsonSchema.properties).map(wn=>Y[wn]);console.log(`[ArctenAgent] Executing safe tool ${E} with args:`,vt),U=await $(...vt)}else if(E==="getState")U=$();else if(E==="setState"){const _=Y.updates||Y;U=await $(_)}else U=await $(...Object.values(Y));console.log(`[ArctenAgent] Tool ${E} completed, result:`,U),fe({toolCallId:N,tool:E,output:U}),Zt(_=>{const vt=new Set(_);return vt.delete(N),vt})}catch($){console.error(`[ArctenAgent] Error executing safe tool ${E}:`,$),fe({toolCallId:N,tool:E,output:`Error: ${$ instanceof Error?$.message:String($)}`}),Zt(Y=>{const H=new Set(Y);return H.delete(N),H})}})()}}},[te,Ke,xn,yn,fe]),m.useEffect(()=>{if(!at||!I.current)return;(async()=>{ot(!0),ce(null);try{const M=`${b.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,S=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:at},format:"json"})});if(!S.ok){if(S.status===404||S.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${S.status}), using empty state`);const H=G?x||{}:{};tt.current=H,G||Q(H),w&&w(H),Gt.current=!0,ot(!1);return}const Y=await S.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${S.status} ${Y}`)}const N=(await S.json())?.value||{},W=!Gt.current;let $;W?($={...G?x||{}:{},...N},Gt.current=!0):$=N,tt.current=$,G||Q($),w&&w($)}catch(v){v instanceof TypeError&&v.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",v):console.error("[ArctenAgent] Failed to fetch state:",v);const S=v instanceof Error?v:new Error(String(v));if(ce(S),!Gt.current){const E=G?x||{}:{};tt.current=E,G||Q(E),w&&w(E),Gt.current=!0}}finally{ot(!1)}})()},[at,b,G,x,w]),m.useEffect(()=>{wt&&Wt.current&&Wt.current.focus()},[wt,te]);function za(){zt(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ua(){zt(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[wt]),m.useEffect(()=>{Be.current&&Be.current.scrollIntoView({behavior:"smooth"})},[te]),m.useEffect(()=>{function p(v){v.key==="Escape"&&(Ft==="streaming"||Ft==="submitted")&&(v.preventDefault(),vn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ft,vn]);function _a(){const p=crypto.randomUUID();ut(p),bn([]),gn([]),J(!1)}function Sr(p){if(p.preventDefault(),!Jt.trim())return;(Ft==="streaming"||Ft==="submitted")&&vn();const v=wr[Math.floor(Math.random()*wr.length)]||"Thinking...";Wn(v),Ba({text:Jt}),ze("")}function Wa(p){const v=p.target.value;ze(v)}m.useEffect(()=>{if(!Ot)return;function p(M){if(X){const S=M.clientX-yt.x,E=M.clientY-yt.y;S>=a&&S<=c&&Ut(S),E>=400&&E<=1e3&&It(E)}else{const S=window.innerWidth-M.clientX;S>=a&&S<=c&&Ut(S)}}function v(){_t(!1),localStorage.setItem("arcten-sidebar-width",St.toString()),localStorage.setItem("arcten-sidebar-height",Rt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",v),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",v)}},[Ot,St,Rt,X,yt,a,c]);function Ka(p){p.preventDefault(),_t(!0)}function qa(){Yt(!0),le(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ha(){Yt(!1),le(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ar(){le(!At),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!At))}function Xa(p){X&&(Te(!0),fn({x:p.clientX-yt.x,y:p.clientY-yt.y}))}return m.useEffect(()=>{if(!X)return;function p(){we(v=>{const S=window.innerWidth-50,E=window.innerHeight-50,N=50-St,W=0,$=Math.max(N,Math.min(v.x,S)),Y=Math.max(W,Math.min(v.y,E));if($!==v.x||Y!==v.y){const H={x:$,y:Y};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(H)),H}return v})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[X,St]),m.useEffect(()=>{if(!hn)return;function p(M){const S=M.clientX-Ct.x,E=M.clientY-Ct.y,N=50,W=window.innerWidth-N,$=window.innerHeight-N,Y=N-St,H=0,U=Math.max(Y,Math.min(S,W)),_=Math.max(H,Math.min(E,$));we({x:U,y:_})}function v(){Te(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(yt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",v),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",v)}},[hn,Ct,yt,St]),Fe?K?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: ",K]})}):O?h.jsx(mu,{features:Wh,children:h.jsx(Pn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:X?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:X?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
- ${X?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
- ${wt?"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
- ${X?"border border-border":"border-l border-border"}
23
- ${wt?"":"w-[30px]"}
24
- `,style:wt?X?{width:`${St}px`,height:At?"auto":`${Rt}px`,left:`${yt.x}px`,top:`${yt.y}px`}:{width:`${St}px`}:void 0,onClick:wt?void 0:za,children:wt?h.jsxs(h.Fragment,{children:[!X&&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:Ka,children:h.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),X&&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(),_t(!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(),Te(!0),fn({x:p.clientX-yt.x,y:p.clientY-yt.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(),_t(!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 ${X?"cursor-move":""}`,onMouseDown:X?Xa:void 0,children:[h.jsx("h2",{className:`text-base font-semibold ${X&&At?"cursor-pointer":""}`,onClick:X&&At?p=>{p.stopPropagation(),Ar()}:void 0,children:r}),h.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:_a,"aria-label":"New chat",children:h.jsx(dt.Plus,{className:"h-4 w-4"})})}),h.jsx(se,{children:"Start a new conversation"})]}),h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:X?Ha:qa,"aria-label":X?"Dock sidebar":"Float sidebar",children:X?h.jsx(dt.Dock,{className:"h-4 w-4"}):h.jsx(dt.PictureInPicture2,{className:"h-4 w-4"})})}),h.jsx(se,{children:X?"Dock to sidebar":"Undock to floating window"})]}),h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:X?Ar:Ua,"aria-label":X?At?"Maximize":"Minimize":"Close sidebar",children:X?At?h.jsx(dt.Maximize2,{className:"h-4 w-4"}):h.jsx(dt.Minimize2,{className:"h-4 w-4"}):h.jsx(dt.X,{className:"h-4 w-4"})})}),h.jsx(se,{children:X?At?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!At&&h.jsxs(h.Fragment,{children:[P&&z.length>0&&h.jsxs("div",{className:`border-b border-border ${mt?"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(Nn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{mt||Xn(),J(!mt)},children:mt?"Show less":"View all"})]}),h.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${mt?"flex-1 overflow-y-auto":""}`,children:z.slice(0,mt?void 0:3).map(p=>h.jsxs("div",{className:"group relative",children:[h.jsxs("button",{type:"button",className:ht(pe({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Fa(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:Ia(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:v=>{v.stopPropagation(),La(p._id)},"aria-label":"Delete conversation",children:h.jsx(dt.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:te.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?"}),T.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:[(F?T:T.slice(0,10)).map(p=>h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.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:()=>{ze(p.sampleUsage),Wt.current?.focus()},children:p.friendlyName})}),h.jsx(se,{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)),T.length>10&&!F&&h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.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:()=>B(!0),children:["+",T.length-10," more"]})}),h.jsx(se,{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:T.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"})]})})]}),F&&T.length>10&&h.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:()=>B(!1),children:"Show less"})]})})]}):h.jsxs(h.Fragment,{children:[te.map(p=>{const M=p.parts.filter(S=>S.type==="text").map(S=>S.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(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:M}):h.jsx("div",{className:"space-y-2",children:p.parts.map((S,E)=>{if(S.type?.startsWith("tool-")){const N=S.type?.replace("tool-","")||"",W=yn.find(H=>H.name===N),$=S.state==="input-available",Y=S.state==="output-available";if($&&Ke.has(N),$){if(Ke.has(N))return null;const H=ds(S.input);return h.jsx(Pn,{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:N,description:W?.description||"",args:H,onApprove:async()=>{if(Ue.has(S.toolCallId))return;Zt(_=>new Set(_).add(S.toolCallId));const U=xn.get(N);if(U)try{const _=await U(...Object.values(H));fe({toolCallId:S.toolCallId,tool:N,output:_})}catch(_){fe({toolCallId:S.toolCallId,tool:N,output:`Error: ${_}`})}},onDeny:async()=>{Ue.has(S.toolCallId)||(Zt(U=>new Set(U).add(S.toolCallId)),fe({toolCallId:S.toolCallId,tool:N,output:"User denied tool execution"}))}})},`${S.toolCallId}-${E}`)}else if(Y){const H=S.output==="User denied tool execution",U=ds(S.input);return h.jsx(Gh,{toolName:N,args:U,isDenied:H,isSafe:Ke.has(N)},`${S.toolCallId}-${E}`)}return null}if(S.type==="text"&&S.text&&mn){const{processedText:N,citations:W,citationMap:$,referencesText:Y}=df(S.text);return h.jsx(lf,{text:N,citations:W,citationMap:$,referencesText:Y,ResponseComponent:mn,className:"text-sm prose prose-sm dark:prose-invert max-w-none"},`${p.id}-${E}`)}return S.type==="reasoning"&&S.text?h.jsxs(Va,{className:"w-full",isStreaming:Ft==="streaming"&&E===p.parts.length-1&&p.id===te.at(-1)?.id,children:[h.jsx(Na,{}),h.jsx(Ra,{children:S.text})]},`${p.id}-${E}`):null})})})},p.id)}),h.jsx("div",{ref:Be})]})}),Tr&&h.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Tr.message]}),h.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[h.jsx(fu,{mode:"wait",children:(Ft==="streaming"||Ft==="submitted")&&h.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:[h.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]}}),h.jsx("p",{className:"text-xs text-muted-foreground",children:pn})]})}),h.jsxs("form",{onSubmit:Sr,className:"relative",children:[h.jsx(Hi,{ref:Wt,value:Jt,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))}}),Ft==="streaming"||Ft==="submitted"?h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:vn,children:h.jsx(dt.Square,{className:"h-4 w-4"})})}),h.jsxs(se,{children:[h.jsx(jr,{children:"Escape"})," to stop"]})]}):h.jsxs(ee,{children:[h.jsx(ne,{asChild:!0,children:h.jsx("button",{type:"submit",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Jt.trim(),children:h.jsx(dt.ArrowRight,{className:"h-4 w-4"})})}),h.jsxs(se,{children:[h.jsx(jr,{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(dt.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 Qe(t){if(typeof t=="string")try{const e=JSON.parse(t);return Qe(e)}catch{return t}if(Array.isArray(t))return t.map(Qe);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=Qe(s);return e}return t}function ff(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return Qe(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?Qe(t):{}}function mf({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:d={},onToolCall:f,onFinish:g,sources:y,ragConfig:b,ragFilters:P}={}){const x=m.useMemo(()=>b!==void 0?b:P?{enabled:!0,filters:P}:y&&y.length>0?{enabled:!0,organizationId:y[0],filters:void 0}:{enabled:!1},[y,b,P]),[w,A]=m.useState(n||null),C=m.useRef(n||null),[R,k]=m.useState(null),[O,D]=m.useState(null),I=m.useRef(null),[K,Z]=m.useState([]),[et,Et]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[Tt,G]=m.useState(!1),[Le,Q]=m.useState(new Set),[tt,gt]=m.useState(d),ot=m.useRef(d),[dn,ce]=m.useState(!1),[Gt,wt]=m.useState(null),zt=m.useRef(!1),St=m.useCallback(async(j,T=3)=>{if(!et||!C.current)return;const V=async()=>{const B=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,z=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:et,updates:j},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<T;F++)try{await V(),wt(null);return}catch(B){if(F===T-1){const q=B instanceof Error?B:new Error(String(B));throw wt(q),console.error("Failed to sync state to Convex after retries:",B),q}await new Promise(q=>setTimeout(q,Math.pow(2,F)*100))}},[et,t,C]),Ut=m.useMemo(()=>function(){return ot.current},[]),Rt=m.useMemo(()=>async function(T){const V={...ot.current,...T};ot.current=V,gt(V);try{await St(T)}catch(F){throw F}},[St]),It=m.useMemo(()=>x?.enabled?async function(T,V=20,F){const B={...x.filters,...F};if(y&&y.length>1){const q=y.map(J=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...C.current?{Authorization:`Bearer ${C.current}`}:{}},body:JSON.stringify({q:T,k:Math.min(V,100),organizationId:J,...Object.keys(B).length>0?{filters:B}:{}})}).then(st=>st.ok?st.json():null)),at=await Promise.all(q),ut=[];for(const J of at)J?.candidates&&ut.push(...J.candidates);ut.sort((J,st)=>{const Lt=J.scores?.rerank||J.scores?.dense||0;return(st.scores?.rerank||st.scores?.dense||0)-Lt});const mt=ut.slice(0,V).map((J,st)=>{const Lt=J.citation||J.url;return{rank:st+1,doc_id:J.doc_id,block_id:J.block_id,url:J.url,citation:Lt,title:J.title||"Untitled",snippet:J.snippet,score:J.scores?.rerank||J.scores?.dense||0,metadata:{site:J.metadata?.site,lang:J.metadata?.lang,contentType:J.metadata?.content_type}}});return{success:!0,query:T,total:ut.length,results:mt,summary:`Found ${ut.length} relevant results across ${y.length} source(s) for "${T}". Top result: ${mt[0]?.title||"N/A"}`}}const z=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const q={q:T,k:Math.min(V,100)};z&&(q.organizationId=z),Object.keys(B).length>0&&(q.filters=B);const at={"Content-Type":"application/json"};C.current&&(at.Authorization=`Bearer ${C.current}`);const ut=await fetch(`${t}/search`,{method:"POST",headers:at,body:JSON.stringify(q)});if(!ut.ok){const st=await ut.text();return{success:!1,error:`Search failed: ${ut.status} ${st}`}}const mt=await ut.json(),J=mt.candidates.map((st,Lt)=>{const qn=st.citation||st.url;return{rank:Lt+1,doc_id:st.doc_id,block_id:st.block_id,url:st.url,citation:qn,title:st.title||"Untitled",snippet:st.snippet,score:st.scores?.rerank||st.scores?.dense||0,metadata:{site:st.metadata?.site,lang:st.metadata?.lang,contentType:st.metadata?.content_type}}});return{success:!0,query:mt.query,total:mt.total,results:J,summary:`Found ${mt.total} relevant results for "${T}". Top result: ${J[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[x,t,C]),Ot=m.useMemo(()=>x?.enabled?async function(T,V){const F=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const B={"Content-Type":"application/json"};C.current&&(B.Authorization=`Bearer ${C.current}`);const z=await fetch(`${t}/fetch`,{method:"POST",headers:B,body:JSON.stringify({doc_id:T,block_ids:V,...F?{organizationId:F}:{}})});if(!z.ok){const at=await z.text();return{success:!1,error:`Fetch failed: ${z.status} ${at}`}}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||T}`}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error occurred"}}}:null,[x,t,C]),_t=m.useMemo(()=>{const j=[...o,...i,Ut,Rt];return x?.enabled&&(It&&j.push(It),Ot&&j.push(Ot)),j},[o,i,Ut,Rt,It,Ot,x]),X=m.useMemo(()=>Ea(_t,a),[_t,a]),Yt=m.useMemo(()=>{const j=new Map,T=new Map(X.map(V=>[V.name,V]));return j.set("getState",Ut),j.set("setState",Rt),x?.enabled&&(It&&j.set("searchDocs",It),Ot&&j.set("fetchDocContent",Ot)),_t.forEach(V=>{if(V===Ut||V===Rt||V===It||V===Ot)return;const F=V[$t];if(F){const z=T.get(F);if(z){j.set(z.name,V);return}}const B=X.find(z=>z.name===V.name);B&&j.set(B.name,V)}),j},[_t,X,Ut,Rt,It,Ot,x]),At=m.useMemo(()=>new Set(X.map(j=>j.name)),[X]),le=m.useMemo(()=>{const j=[{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"]}}],T=[];return x?.enabled&&T.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"]}}),[...X,...j,...T]},[X,x]),yt=m.useMemo(()=>le.filter(j=>j.name==="getState"||j.name==="setState"?!0:At.has(j.name)),[le,At]),we=m.useMemo(()=>{const j=new Set;return j.add("getState"),j.add("setState"),x?.enabled&&(j.add("searchDocs"),j.add("fetchDocContent")),i.forEach(T=>{for(const[V,F]of Yt.entries())if(F===T){j.add(V);break}}),j},[i,Yt]);m.useEffect(()=>s||n?void 0:((async()=>{try{const T=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!T.ok)throw new Error("Failed to fetch token");const V=await T.json();A(V.clientToken),C.current=V.clientToken,D(V.expiresAt),k(null)}catch(T){console.error("[useAgent] Token fetch failed:",T),k(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{I.current&&clearTimeout(I.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!O||s||n)return;I.current&&clearTimeout(I.current);const j=Math.floor(Date.now()/1e3),T=O-j,F=Math.max(0,T-5);return I.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();A(z.clientToken),C.current=z.clientToken,D(z.expiresAt),k(null)}catch(B){console.error("[useAgent] Token refresh failed:",B),k(B instanceof Error?B.message:"Failed to refresh token")}},F*1e3),()=>{I.current&&clearTimeout(I.current)}},[O,e,JSON.stringify(r),s,n]);const hn=async(j,T={})=>{const V=T.headers?new Headers(T.headers):new Headers;V.delete("user-agent"),V.delete("User-Agent"),console.log("[useAgent] Making request to:",j),console.log("[useAgent] Method:",T.method||"GET"),console.log("[useAgent] Has Authorization header:",V.has("Authorization")),console.log("[useAgent] Client token available:",!!C.current);try{const F=await fetch(j,{...T,headers:V});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}},Te=`${t}/chat`;console.log("[useAgent] Chat API URL:",Te);const{messages:Ct,sendMessage:fn,status:Fe,error:$e,stop:Be,addToolResult:Wt,setMessages:Jt}=Wi.useChat({id:et||void 0,messages:u,transport:new Vn.DefaultChatTransport({api:Te,fetch:hn,headers:()=>{const j={};return C.current?(j.Authorization=`Bearer ${C.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),j},body:()=>{const j=yt.map(V=>({name:V.name,description:V.description,inputSchema:V.jsonSchema})),T=j.filter(V=>V.name==="getState"||V.name==="setState").map(V=>V.name);return T.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",T),{tools:j,systemPrompt:c,state:ot.current,...P&&{ragFilters:P}}}}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ct.forEach(j=>{j.role==="assistant"&&j.parts.forEach(T=>{if(!T.type?.startsWith("tool-")||T.state!=="input-available")return;const V=T.type.replace("tool-",""),F=T.toolCallId;if(Le.has(F))return;Q(z=>new Set(z).add(F));const B=ff(T.input);if(we.has(V)){const z=Yt.get(V);z?(async()=>{try{const q=yt.find(ut=>ut.name===V);let at;if(q&&q.jsonSchema?.properties){const mt=Object.keys(q.jsonSchema.properties).map(J=>B[J]);at=await z(...mt)}else if(V==="getState")at=z();else if(V==="setState"){const ut=B.updates||B;at=await z(ut)}else at=await z(...Object.values(B));Wt({toolCallId:F,tool:V,output:at})}catch(q){console.error(`[useAgent] Error executing tool ${V}:`,q),Wt({toolCallId:F,tool:V,output:`Error: ${q}`})}})():console.warn(`[useAgent] Tool ${V} not found in toolsMap`)}else f&&f({toolCall:{toolCallId:F,toolName:V,args:B}})})})},[Ct,we,Yt,f,Wt,Le,Rt,yt]),m.useEffect(()=>{if(Fe==="ready"&&Ct.length>0&&g){const j=Ct[Ct.length-1];j&&j.role==="assistant"&&g({message:j,messages:Ct,isAbort:!1,isDisconnect:!1,isError:!!$e})}},[Fe,Ct,$e,g]);async function ze(){if(!(!r?.id||!w)){G(!0);try{const T=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${w}`}})).json();Z(T.conversations||[])}catch(j){console.error("Failed to fetch conversations:",j)}finally{G(!1)}}}m.useEffect(()=>{r?.id&&w&&ze()},[JSON.stringify(r),w,t]),m.useEffect(()=>{if(!et||!C.current)return;(async()=>{ce(!0),wt(null);try{const T=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:et},format:"json"})});if(!T.ok){const q=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${q}`)}const F=(await T.json())?.value||{},B=!zt.current;let z;B?(z={...d,...F},zt.current=!0):z=F,ot.current=z,gt(z)}catch(T){console.error("Failed to fetch state:",T);const V=T instanceof Error?T:new Error(String(T));wt(V),zt.current||(ot.current=d,gt(d),zt.current=!0)}finally{ce(!1)}})()},[et,t]);async function mn(j){Et(j),G(!0);try{const T=await fetch(`${t}/conversations/${j}/messages`,{headers:{Authorization:`Bearer ${C.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const F=(await T.json()).messages||[];Jt(F)}catch(T){console.error("Failed to load conversation messages:",T)}finally{G(!1)}}async function _n(j){if(w)try{await fetch(`${t}/conversations/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${w}`}}),Z(K.filter(T=>T._id!==j)),j===et&&pn()}catch(T){console.error("Failed to delete conversation:",T)}}function pn(){const j=crypto.randomUUID();Et(j),Jt([]),Q(new Set),ot.current=d,gt(d),zt.current=!1}function Wn(j){Wt(j)}async function Ue(j){const T={...ot.current,...j};ot.current=T,gt(T);try{await St(j)}catch(V){throw V}}async function Zt(){if(!r?.id||!C.current)throw new Error("User authentication required to share state");const j=`shared_${crypto.randomUUID()}`;try{return await fetch(`${t.replace("/chat","")}/convex/api/mutation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"sharedStates:create",args:{stateId:j,state:ot.current,projectId:"default",createdBy:r.id},format:"json"})}),j}catch(T){throw console.error("Failed to share state:",T),T}}async function Kn(j){if(!C.current)throw new Error("Authentication required to import state");try{const T=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"sharedStates:getByStateId",args:{stateId:j},format:"json"})});if(!T.ok)throw new Error("Failed to fetch shared state");const F=(await T.json())?.value||{};ot.current=F,gt(F)}catch(T){throw console.error("Failed to import state:",T),T}}return{id:et,messages:Ct,status:Fe,error:$e,sendMessage:fn,stop:Be,addToolOutput:Wn,setMessages:Jt,conversations:K,loadConversation:mn,deleteConversation:_n,startNewConversation:pn,isLoadingConversations:Tt,clientToken:w,tokenError:R,state:tt,setState:Ue,shareState:Zt,importState:Kn,isStateLoading:dn,stateError:Gt}}exports.verifyToken=ac.verifyToken;exports.ARCTEN_ORIGINAL_NAME=$t;exports.ArctenAgent=hf;exports.preserveToolName=qh;exports.useAgent=mf;
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,l=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 "${l}". This tool will be excluded.
19
+ To fix: Run "arcten-extract-types ." and ensure "${l}" 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 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:t})}),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(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(dt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:h.jsx(dt.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(([l])=>!i.includes(l))),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(dt.ChevronDown,{className:"h-3 w-3"}):h.jsx(dt.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(dt.X,{className:"h-3 w-3"}):s?h.jsx(dt.Zap,{className:"h-3 w-3"}):h.jsx(dt.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),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(([l,u])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[l,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof u=="string"?u:JSON.stringify(u)})]},l))})})]})}function Yh({...t}){return h.jsx(Os.Root,{"data-slot":"collapsible",...t})}function Jh({...t}){return h.jsx(Os.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function Zh({...t}){return h.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:h.jsx(m.Suspense,{fallback:null,children:h.jsx(Qh,{className:ht("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 h.jsx(o,{animate:{backgroundPosition:"0% center"},className:ht("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,Va=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,l]=Pr.useControllableState({prop:n,defaultProp:s,onChange:r}),[u,d]=Pr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[y,v]=m.useState(null);m.useEffect(()=>{e?y===null&&v(Date.now()):y!==null&&(d(Math.ceil((Date.now()-y)/of)),v(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&c&&!f){const x=setTimeout(()=>{l(!1),g(!0)},rf);return()=>clearTimeout(x)}},[e,c,s,l,f]);const C=x=>{l(x)};return h.jsx(Da.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:l,duration:u},children:h.jsx(Yh,{className:ht("not-prose mb-4",t),onOpenChange:C,open:c,...a,children:i})})}),af=(t,e)=>t||e===0?h.jsx(nf,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Na=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=sf();return h.jsx(Jh,{className:ht("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??h.jsxs(h.Fragment,{children:[h.jsx(dt.BrainIcon,{className:"size-4"}),af(s,o),h.jsx(dt.ChevronDownIcon,{className:ht("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ra=m.memo(({className:t,children:e,...n})=>h.jsx(Zh,{className:ht("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:h.jsx(xr,{className:"grid gap-2",children:e})}));Va.displayName="Reasoning";Na.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 h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsxs("button",{className:ht("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(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: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 • ",t.length]}),t.map(o=>h.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ht("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:_i(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 lf({text:t,citations:e,citationMap:n,referencesText:s,ResponseComponent:r,className:o,showCitations:i=!0}){const a=m.useRef(null),[c,l]=m.useState([]);m.useEffect(()=>{if(!i||!a.current||e.length===0||n.size===0){(n.size===0||!i)&&l([]);return}const d=a.current;let f,g=!1;const y=new WeakSet,v=()=>{if(!a.current||g)return;g=!0;const x=a.current,w=/\[(\d+)\]/g,S=document.createTreeWalker(x,NodeFilter.SHOW_TEXT,null),P=[];let V;for(;V=S.nextNode();)if(V.nodeType===Node.TEXT_NODE&&!y.has(V)){const k=V,N=k.textContent||"";let $=k.parentElement,L=!1;for(;$&&$!==x;){if($.tagName==="A"||$.tagName==="CODE"||$.tagName==="PRE"){L=!0;break}$=$.parentElement}if(!L){const Y=Array.from(N.matchAll(w)).filter(mt=>{if(!mt[1])return!1;const Vt=parseInt(mt[1],10);return n.has(Vt)});Y.length>0&&P.push({node:k,matches:Y})}}if(P.length===0){g=!1;return}const I=[];P.forEach(({node:k,matches:N})=>{y.add(k);const $=k.textContent||"",L=document.createDocumentFragment();let Z=0;N.forEach(Y=>{if(!Y[1])return;Y.index!==void 0&&Y.index>Z&&L.appendChild(document.createTextNode($.slice(Z,Y.index)));const mt=document.createElement("span");mt.className="inline-flex items-center citation-button-container";const Vt=parseInt(Y[1],10);mt.setAttribute("data-citation",Y[1]),L.appendChild(mt),I.push({element:mt,citationNum:Vt}),Z=(Y.index||0)+Y[0].length}),Z<$.length&&L.appendChild(document.createTextNode($.slice(Z))),k.parentNode&&k.parentNode.replaceChild(L,k)}),I.length>0&&l(k=>{const N=new Set(k.map(Z=>Z.element)),$=k.filter(Z=>Z.element.isConnected),L=I.filter(Z=>!N.has(Z.element));return[...$,...L]}),g=!1},C=new MutationObserver(()=>{clearTimeout(f),f=setTimeout(v,100)});return C.observe(d,{childList:!0,subtree:!0,characterData:!0}),f=setTimeout(v,200),()=>{C.disconnect(),clearTimeout(f)}},[t,e,n,i]);const u=i&&s?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:Array.from(n.entries()).sort(([d],[f])=>d-f).map(([d,f])=>h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium",children:["[",d,"]"]}),h.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:f})]},d))})]}):null;return h.jsxs("div",{className:o,children:[h.jsx("div",{ref:a,children:h.jsx(r,{children:t})}),i&&c.filter(({element:d})=>d.isConnected).map(({element:d,citationNum:f},g)=>e.find(v=>v.number===f)?oc.createPortal(h.jsx(cf,{sources:e.map(v=>({number:v.number,url:v.url,domain:uf(v.url)})),citationNumber:f},`citation-${f}-${d}`),d,`citation-${f}-${g}`):null),u]})}function uf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function df(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=[];if(s&&s[1]){const g=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let v;for(;(v=y.exec(g))!==null;)if(v[1]&&v[2]){const C=parseInt(v[1],10),x=v[2].replace(/[.,;:!?]+$/,"");r.set(C,x),o.push({number:C,url:x})}}let i,a=e;s&&s[0]&&(i=s[0],a=e.replace(n,""));const c=[];let l=0;const u=/```[\s\S]*?```|`[^`]+`/g;let d;for(;(d=u.exec(a))!==null;)d.index>l&&c.push({type:"text",content:a.slice(l,d.index),start:l,end:d.index}),c.push({type:"code",content:d[0],start:d.index,end:d.index+d[0].length}),l=d.index+d[0].length;return l<a.length&&c.push({type:"text",content:a.slice(l),start:l,end:a.length}),{processedText:c.map(g=>{if(g.type==="code")return g.content;let y=g.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(C,x,w)=>{const S=parseInt(x,10);return r.has(S)||(r.set(S,w),o.push({number:S,url:w})),`[${S}]`}),y}).join(""),citations:o.sort((g,y)=>g.number-y.number),citationMap:r,referencesText:i}}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 hf({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:l=!1,tools:u=[],safeTools:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:C,state:x,onStateChange:w,allowStateEdits:S=!0,sources:P,ragConfig:V,showCitations:I=!0}){const k=m.useMemo(()=>V!==void 0?V:P&&P.length>0?{enabled:!0,organizationId:P[0],filters:void 0}:{enabled:!1},[P,V]),[N,$]=m.useState(null),L=m.useRef(null),[Z,Y]=m.useState(null),[mt,Vt]=m.useState(null),gt=m.useRef(null),Q=x!==void 0,[ot,ct]=m.useState({}),et=m.useRef({});Q&&x?et.current=x:Q||(et.current=ot);const[ut,oe]=m.useState(!1),[_n,we]=m.useState(null),Nt=m.useRef(!1),[vt,ae]=m.useState(l),[bt,Ft]=m.useState(i),[Rt,$t]=m.useState(600),[ce,Ct]=m.useState(!1),[J,Te]=m.useState(!1),[Pt,Ht]=m.useState(!1),[wt,Be]=m.useState({x:100,y:100}),[ze,jt]=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),[j,A]=m.useState(""),[M,F]=m.useState([]),[z,U]=m.useState(!1),[q,yt]=m.useState([]),[nt,At]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[X,tt]=m.useState(!1),[Ce,le]=m.useState(!1),[pf,gn]=m.useState([]),vr=m.useCallback(async(p,b=3)=>{if(!nt||!L.current)return;const E=async()=>{const D=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:nt,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 K=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${K}`)}};for(let T=0;T<b;T++)try{await E(),we(null);return}catch(D){if(T===b-1){const K=D instanceof Error?D:new Error(String(D));throw we(K),console.error("Failed to sync state to Convex after retries:",D),K}await new Promise(K=>setTimeout(K,Math.pow(2,T)*100))}},[nt,v,L]),qe=m.useMemo(()=>function(){return et.current},[]),He=m.useMemo(()=>async function(b){const E={...et.current,...b};et.current=E,Q||ct(E),w&&w(E);try{await vr(b)}catch(T){throw T}},[vr,w,Q]);m.useEffect(()=>{Q&&x&&(et.current=x)},[Q,x]);const ue=m.useMemo(()=>k?.enabled?async function(b,E=20,T){if(P&&P.length>1){const K=P.map(_=>fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json",...L.current?{Authorization:`Bearer ${L.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(E,100),organizationId:_,...Object.keys(R).length>0?{filters:R}:{}})}).then(W=>W.ok?W.json():null)),B=await Promise.all(K),G=[];for(const _ of B)_?.candidates&&G.push(..._.candidates);G.sort((_,W)=>{const Tt=_.scores?.rerank||_.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-Tt});const H=G.slice(0,E).map((_,W)=>{const Tt=_.citation||_.url;return{rank:W+1,doc_id:_.doc_id,block_id:_.block_id,url:_.url,citation:Tt,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:b,total:G.length,results:H,summary:`Found ${G.length} relevant results across ${P.length} source(s) for "${b}". Top result: ${H[0]?.title||"N/A"}`}}const D=k.organizationId&&k.organizationId!=="default"?k.organizationId:void 0,R={...k.filters,...T};try{const K={q:b,k:Math.min(E,100)};D&&(K.organizationId=D),Object.keys(R).length>0&&(K.filters=R);const B={"Content-Type":"application/json"};L.current&&(B.Authorization=`Bearer ${L.current}`);const G=await fetch(`${v}/search`,{method:"POST",headers:B,body:JSON.stringify(K)});if(!G.ok){const W=await G.text();return{success:!1,error:`Search failed: ${G.status} ${W}`}}const H=await G.json(),_=H.candidates.map((W,Tt)=>{const wn=W.citation||W.url;return{rank:Tt+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:wn,title:W.title||"Untitled",snippet:W.snippet,score:W.scores?.rerank||W.scores?.dense||0,metadata:{site:W.metadata?.site,lang:W.metadata?.lang,contentType:W.metadata?.content_type}}});return{success:!0,query:H.query,total:H.total,results:_,summary:`Found ${H.total} relevant results for "${b}". Top result: ${_[0]?.title||"N/A"}`}}catch(K){return{success:!1,error:K instanceof Error?K.message:"Unknown error occurred"}}}:null,[V,v,L]),de=m.useMemo(()=>k?.enabled?async function(b,E){const T=k.organizationId&&k.organizationId!=="default"?k.organizationId:P&&P.length>0?P[0]:void 0;try{const D={"Content-Type":"application/json"};L.current&&(D.Authorization=`Bearer ${L.current}`);const R=await fetch(`${v}/fetch`,{method:"POST",headers:D,body:JSON.stringify({doc_id:b,block_ids:E,...T?{organizationId:T}:{}})});if(!R.ok){const B=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${B}`}}const K=await R.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||b}`}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Unknown error occurred"}}}:null,[V,v,L]),he=m.useMemo(()=>{const p=[...u,...d,qe];return(!Q||S)&&p.push(He),k?.enabled&&(ue&&p.push(ue),de&&p.push(de)),p},[u,d,qe,He,ue,de,Q,S,k]),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:[]}}];(!Q||S)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const b=[];return k?.enabled&&b.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Hn,...p,...b]},[Hn,Q,S,k]),br=m.useMemo(()=>new Set(_t.map(p=>p.name)),[_t]),yn=m.useMemo(()=>_t.filter(p=>p.name==="getState"?!0:p.name==="setState"?!Q||S:br.has(p.name)),[_t,br,Q,S]),xn=m.useMemo(()=>{const p=new Map,b=new Map(Hn.map(E=>[E.name,E]));return p.set("getState",qe),(!Q||S)&&p.set("setState",He),k?.enabled&&(ue&&p.set("searchDocs",ue),de&&p.set("fetchDocContent",de)),he.forEach(E=>{if(E===qe||E===He||E===ue||E===de)return;const T=E[zt];if(T){const R=b.get(T);if(R){p.set(R.name,E);return}}const D=_t.find(R=>R.name===E.name);D&&p.set(D.name,E)}),p},[he,_t,qe,He,ue,de,Q,S,k]),Xe=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),k?.enabled&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(_t.map(E=>[E.name,E]));return d.forEach(E=>{const T=E[zt];if(T&&b.has(T))p.add(T);else{const D=_t.find(R=>R.name===E.name);D&&p.add(D.name)}}),p},[d,_t,k]),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 b=localStorage.getItem("arcten-sidebar-width");b&&Ft(parseInt(b));const E=localStorage.getItem("arcten-sidebar-height");E&&$t(parseInt(E));const T=localStorage.getItem("arcten-sidebar-detached");T&&Te(JSON.parse(T));const D=localStorage.getItem("arcten-sidebar-position");if(D){const K=JSON.parse(D),B=50,G=Math.max(B-i,Math.min(K.x,window.innerWidth-B)),H=Math.max(0,Math.min(K.y,window.innerHeight-B));Be({x:G,y:H})}const R=localStorage.getItem("arcten-sidebar-minimized");R&&Ht(JSON.parse(R)),Wn(!0)}},[]);const Jt=m.useMemo(()=>C,[C?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!b.ok)throw new Error("Failed to fetch token");const E=await b.json();$(E.clientToken),L.current=E.clientToken,Vt(E.expiresAt),Y(null)}catch(b){Y(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{gt.current&&clearTimeout(gt.current)}),[y,Jt]),m.useEffect(()=>{if(!mt)return;gt.current&&clearTimeout(gt.current);const p=Math.floor(Date.now()/1e3),b=mt-p,T=Math.max(0,b-5);return gt.current=setTimeout(async()=>{try{const D=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!D.ok)throw new Error("Failed to refresh token");const R=await D.json();$(R.clientToken),L.current=R.clientToken,Vt(R.expiresAt),Y(null)}catch(D){console.error("Token refresh failed:",D),Y(D instanceof Error?D.message:"Failed to refresh token")}},T*1e3),()=>{gt.current&&clearTimeout(gt.current)}},[mt,y,Jt]),m.useEffect(()=>{(async()=>{if(he.length!==0)try{const b=he.map(T=>({name:T.name,code:T.toString()})),E=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(E.ok){const T=await E.json();F(T.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[he]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{pn(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{A(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Xn=m.useCallback(async()=>{if(!(!Jt?.id||!N)){le(!0);try{const b=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();yt(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{le(!1)}}},[Jt?.id,N,v]);m.useEffect(()=>{Jt?.id&&N&&Xn()},[Jt?.id,N,Xn]);function Ia(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Oa(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1);const b=Q?x||{}:{};et.current=b,Q||ct(b),w&&w(b),Nt.current=!1}async function La(p){if(N)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),yt(q.filter(b=>b._id!==p)),p===nt&&Oa()}catch(b){console.error("Failed to delete conversation:",b)}}async function Fa(p){At(p.chatId),tt(!1),le(!0);try{const b=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${L.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const T=(await b.json()).messages||[];bn(T),gn(T)}catch(b){console.error("Failed to load conversation messages:",b);const E=p.messages||[];bn(E),gn(E)}finally{le(!1)}}const $a=async(p,b={})=>{const E=b.headers?new Headers(b.headers):new Headers;return E.delete("user-agent"),E.delete("User-Agent"),fetch(p,{...b,headers:E})},{messages:Zt,sendMessage:Ba,status:Bt,error:Tr,stop:vn,addToolResult:fe,setMessages:bn}=Wi.useChat({id:nt||void 0,transport:new Vn.DefaultChatTransport({api:`${v}/chat`,fetch:$a,headers:()=>{const p={};return L.current&&(p.Authorization=`Bearer ${L.current}`),p},body:()=>({tools:yn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:j,state:et.current})}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Zt[Zt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(E=>E.type?.startsWith("tool-")&&E.state==="input-available"&&typeof E.toolCallId=="string"&&E.input!==void 0)||[];for(const E of b){const T=E,D=T.type?.replace("tool-","")||"",R=T.toolCallId;if(Xe.has(D)){if(Ke.has(R))continue;Yt(B=>B.has(R)?B:new Set(B).add(R)),(async()=>{try{const B=xn.get(D);if(!B){console.warn(`[ArctenAgent] Tool ${D} not found in toolsMap. Available tools:`,Array.from(xn.keys())),fe({toolCallId:R,tool:D,output:`Error: Tool ${D} not found`}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt});return}const G=ds(T.input),H=yn.find(W=>W.name===D);let _;if(H&&H.jsonSchema?.properties){const Tt=Object.keys(H.jsonSchema.properties).map(wn=>G[wn]);console.log(`[ArctenAgent] Executing safe tool ${D} with args:`,Tt),_=await B(...Tt)}else if(D==="getState")_=B();else if(D==="setState"){const W=G.updates||G;_=await B(W)}else _=await B(...Object.values(G));console.log(`[ArctenAgent] Tool ${D} completed, result:`,_),fe({toolCallId:R,tool:D,output:_}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt})}catch(B){console.error(`[ArctenAgent] Error executing safe tool ${D}:`,B),fe({toolCallId:R,tool:D,output:`Error: ${B instanceof Error?B.message:String(B)}`}),Yt(G=>{const H=new Set(G);return H.delete(R),H})}})()}}},[Zt,Xe,xn,yn,fe]),m.useEffect(()=>{if(!nt||!L.current)return;(async()=>{oe(!0),we(null);try{const E=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,T=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:nt},format:"json"})});if(!T.ok){if(T.status===404||T.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${T.status}), using empty state`);const H=Q?x||{}:{};et.current=H,Q||ct(H),w&&w(H),Nt.current=!0,oe(!1);return}const G=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${G}`)}const R=(await T.json())?.value||{},K=!Nt.current;let B;K?(B={...Q?x||{}:{},...R},Nt.current=!0):B=R,et.current=B,Q||ct(B),w&&w(B)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const T=b instanceof Error?b:new Error(String(b));if(we(T),!Nt.current){const D=Q?x||{}:{};et.current=D,Q||ct(D),w&&w(D),Nt.current=!0}}finally{oe(!1)}})()},[nt,v,Q,x,w]),m.useEffect(()=>{vt&&Gt.current&&Gt.current.focus()},[vt,Zt]);function za(){ae(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ua(){ae(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[vt]),m.useEffect(()=>{Xt.current&&Xt.current.scrollIntoView({behavior:"smooth"})},[Zt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Bt==="streaming"||Bt==="submitted")&&(b.preventDefault(),vn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Bt,vn]);function _a(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1)}function Sr(p){if(p.preventDefault(),!Ae.trim())return;(Bt==="streaming"||Bt==="submitted")&&vn();const b=wr[Math.floor(Math.random()*wr.length)]||"Thinking...";qn(b),Ba({text:Ae}),We("")}function Wa(p){const b=p.target.value;We(b)}m.useEffect(()=>{if(!ce)return;function p(E){if(J){const T=E.clientX-wt.x,D=E.clientY-wt.y;T>=a&&T<=c&&Ft(T),D>=400&&D<=1e3&&$t(D)}else{const T=window.innerWidth-E.clientX;T>=a&&T<=c&&Ft(T)}}function b(){Ct(!1),localStorage.setItem("arcten-sidebar-width",bt.toString()),localStorage.setItem("arcten-sidebar-height",Rt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ce,bt,Rt,J,wt,a,c]);function Ka(p){p.preventDefault(),Ct(!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(!Pt),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Pt))}function Xa(p){J&&(jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.y}))}return m.useEffect(()=>{if(!J)return;function p(){Be(b=>{const T=window.innerWidth-50,D=window.innerHeight-50,R=50-bt,K=0,B=Math.max(R,Math.min(b.x,T)),G=Math.max(K,Math.min(b.y,D));if(B!==b.x||G!==b.y){const H={x:B,y:G};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(H)),H}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[J,bt]),m.useEffect(()=>{if(!ze)return;function p(E){const T=E.clientX-Ue.x,D=E.clientY-Ue.y,R=50,K=window.innerWidth-R,B=window.innerHeight-R,G=R-bt,H=0,_=Math.max(G,Math.min(T,K)),W=Math.max(H,Math.min(D,B));Be({x:_,y:W})}function b(){jt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(wt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ze,Ue,wt,bt]),_e?Z?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: ",Z]})}):N?h.jsx(mu,{features:Wh,children:h.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
+ ${vt?"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
+ ${vt?"":"w-[30px]"}
24
+ `,style:vt?J?{width:`${bt}px`,height:Pt?"auto":`${Rt}px`,left:`${wt.x}px`,top:`${wt.y}px`}:{width:`${bt}px`}:void 0,onClick:vt?void 0:za,children:vt?h.jsxs(h.Fragment,{children:[!J&&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:Ka,children:h.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&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(),Ct(!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(),jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.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(),Ct(!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 ${J?"cursor-move":""}`,onMouseDown:J?Xa:void 0,children:[h.jsx("h2",{className:`text-base font-semibold ${J&&Pt?"cursor-pointer":""}`,onClick:J&&Pt?p=>{p.stopPropagation(),Ar()}:void 0,children:r}),h.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:_a,"aria-label":"New chat",children:h.jsx(dt.Plus,{className:"h-4 w-4"})})}),h.jsx(ee,{children:"Start a new conversation"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ha:qa,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?h.jsx(dt.Dock,{className:"h-4 w-4"}):h.jsx(dt.PictureInPicture2,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?"Dock to sidebar":"Undock to floating window"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ar:Ua,"aria-label":J?Pt?"Maximize":"Minimize":"Close sidebar",children:J?Pt?h.jsx(dt.Maximize2,{className:"h-4 w-4"}):h.jsx(dt.Minimize2,{className:"h-4 w-4"}):h.jsx(dt.X,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?Pt?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Pt&&h.jsxs(h.Fragment,{children:[C&&q.length>0&&h.jsxs("div",{className:`border-b border-border ${X?"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(Nn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{X||Xn(),tt(!X)},children:X?"Show less":"View all"})]}),h.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=>h.jsxs("div",{className:"group relative",children:[h.jsxs("button",{type:"button",className:ht(pe({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Fa(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:Ia(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:b=>{b.stopPropagation(),La(p._id)},"aria-label":"Delete conversation",children:h.jsx(dt.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:Zt.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?"}),M.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:[(z?M:M.slice(0,10)).map(p=>h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.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})}),h.jsx(ee,{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)),M.length>10&&!z&&h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.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:()=>U(!0),children:["+",M.length-10," more"]})}),h.jsx(ee,{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:M.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"})]})})]}),z&&M.length>10&&h.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:()=>U(!1),children:"Show less"})]})})]}):h.jsxs(h.Fragment,{children:[Zt.map(p=>{const E=p.parts.filter(T=>T.type==="text").map(T=>T.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(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:E}):h.jsx("div",{className:"space-y-2",children:p.parts.map((T,D)=>{if(T.type?.startsWith("tool-")){const R=T.type?.replace("tool-","")||"",K=yn.find(H=>H.name===R),B=T.state==="input-available",G=T.state==="output-available";if(B&&Xe.has(R),B){if(Xe.has(R))return null;const H=ds(T.input);return h.jsx(Pn,{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:K?.description||"",args:H,onApprove:async()=>{if(Ke.has(T.toolCallId))return;Yt(W=>new Set(W).add(T.toolCallId));const _=xn.get(R);if(_)try{const W=await _(...Object.values(H));fe({toolCallId:T.toolCallId,tool:R,output:W})}catch(W){fe({toolCallId:T.toolCallId,tool:R,output:`Error: ${W}`})}},onDeny:async()=>{Ke.has(T.toolCallId)||(Yt(_=>new Set(_).add(T.toolCallId)),fe({toolCallId:T.toolCallId,tool:R,output:"User denied tool execution"}))}})},`${T.toolCallId}-${D}`)}else if(G){const H=T.output==="User denied tool execution",_=ds(T.input);return h.jsx(Gh,{toolName:R,args:_,isDenied:H,isSafe:Xe.has(R)},`${T.toolCallId}-${D}`)}return null}if(T.type==="text"&&T.text&&mn){const{processedText:R,citations:K,citationMap:B,referencesText:G}=df(T.text);return h.jsx(lf,{text:R,citations:K,citationMap:B,referencesText:G,ResponseComponent:mn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:I},`${p.id}-${D}`)}return T.type==="reasoning"&&T.text?h.jsxs(Va,{className:"w-full",isStreaming:Bt==="streaming"&&D===p.parts.length-1&&p.id===Zt.at(-1)?.id,children:[h.jsx(Na,{}),h.jsx(Ra,{children:T.text})]},`${p.id}-${D}`):null})})})},p.id)}),h.jsx("div",{ref:Xt})]})}),Tr&&h.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Tr.message]}),h.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[h.jsx(fu,{mode:"wait",children:(Bt==="streaming"||Bt==="submitted")&&h.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:[h.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]}}),h.jsx("p",{className:"text-xs text-muted-foreground",children:Kn})]})}),h.jsxs("form",{onSubmit:Sr,className:"relative",children:[h.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"?h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:vn,children:h.jsx(dt.Square,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{children:"Escape"})," to stop"]})]}):h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"submit",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Ae.trim(),children:h.jsx(dt.ArrowRight,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{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(dt.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 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 ff(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 mf({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:l=[],conversationId:u,initialState:d={},onToolCall:f,onFinish:g,sources:y,ragConfig:v,ragFilters:C}={}){const x=m.useMemo(()=>v!==void 0?v:C?{enabled:!0,filters:C}:y&&y.length>0?{enabled:!0,organizationId:y[0],filters:void 0}:{enabled:!1},[y,v,C]),[w,S]=m.useState(n||null),P=m.useRef(n||null),[V,I]=m.useState(null),[k,N]=m.useState(null),$=m.useRef(null),[L,Z]=m.useState([]),[Y,mt]=m.useState(u||(typeof window<"u"?crypto.randomUUID():null)),[Vt,gt]=m.useState(!1),[Q,ot]=m.useState(new Set),[ct,et]=m.useState(d),ut=m.useRef(d),[oe,_n]=m.useState(!1),[we,Nt]=m.useState(null),vt=m.useRef(!1),ae=m.useCallback(async(j,A=3)=>{if(!Y||!P.current)return;const M=async()=>{const z=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Y,updates:j},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${q}`)}};for(let F=0;F<A;F++)try{await M(),Nt(null);return}catch(z){if(F===A-1){const q=z instanceof Error?z:new Error(String(z));throw Nt(q),console.error("Failed to sync state to Convex after retries:",z),q}await new Promise(q=>setTimeout(q,Math.pow(2,F)*100))}},[Y,t,P]),bt=m.useMemo(()=>function(){return ut.current},[]),Ft=m.useMemo(()=>async function(A){const M={...ut.current,...A};ut.current=M,et(M);try{await ae(A)}catch(F){throw F}},[ae]),Rt=m.useMemo(()=>x?.enabled?async function(A,M=20,F){const z={...x.filters,...F};if(y&&y.length>1){const q=y.map(X=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...P.current?{Authorization:`Bearer ${P.current}`}:{}},body:JSON.stringify({q:A,k:Math.min(M,100),organizationId:X,...Object.keys(z).length>0?{filters:z}:{}})}).then(tt=>tt.ok?tt.json():null)),yt=await Promise.all(q),nt=[];for(const X of yt)X?.candidates&&nt.push(...X.candidates);nt.sort((X,tt)=>{const Ce=X.scores?.rerank||X.scores?.dense||0;return(tt.scores?.rerank||tt.scores?.dense||0)-Ce});const At=nt.slice(0,M).map((X,tt)=>{const Ce=X.citation||X.url;return{rank:tt+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:A,total:nt.length,results:At,summary:`Found ${nt.length} relevant results across ${y.length} source(s) for "${A}". Top result: ${At[0]?.title||"N/A"}`}}const U=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const q={q:A,k:Math.min(M,100)};U&&(q.organizationId=U),Object.keys(z).length>0&&(q.filters=z);const yt={"Content-Type":"application/json"};P.current&&(yt.Authorization=`Bearer ${P.current}`);const nt=await fetch(`${t}/search`,{method:"POST",headers:yt,body:JSON.stringify(q)});if(!nt.ok){const tt=await nt.text();return{success:!1,error:`Search failed: ${nt.status} ${tt}`}}const At=await nt.json(),X=At.candidates.map((tt,Ce)=>{const le=tt.citation||tt.url;return{rank:Ce+1,doc_id:tt.doc_id,block_id:tt.block_id,url:tt.url,citation:le,title:tt.title||"Untitled",snippet:tt.snippet,score:tt.scores?.rerank||tt.scores?.dense||0,metadata:{site:tt.metadata?.site,lang:tt.metadata?.lang,contentType:tt.metadata?.content_type}}});return{success:!0,query:At.query,total:At.total,results:X,summary:`Found ${At.total} relevant results for "${A}". Top result: ${X[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[x,t,P]),$t=m.useMemo(()=>x?.enabled?async function(A,M){const F=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const z={"Content-Type":"application/json"};P.current&&(z.Authorization=`Bearer ${P.current}`);const U=await fetch(`${t}/fetch`,{method:"POST",headers:z,body:JSON.stringify({doc_id:A,block_ids:M,...F?{organizationId:F}:{}})});if(!U.ok){const yt=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${yt}`}}const q=await U.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||A}`}}catch(z){return{success:!1,error:z instanceof Error?z.message:"Unknown error occurred"}}}:null,[x,t,P]),ce=m.useMemo(()=>{const j=[...o,...i,bt,Ft];return x?.enabled&&(Rt&&j.push(Rt),$t&&j.push($t)),j},[o,i,bt,Ft,Rt,$t,x]),Ct=m.useMemo(()=>Ea(ce,a),[ce,a]),J=m.useMemo(()=>{const j=new Map,A=new Map(Ct.map(M=>[M.name,M]));return j.set("getState",bt),j.set("setState",Ft),x?.enabled&&(Rt&&j.set("searchDocs",Rt),$t&&j.set("fetchDocContent",$t)),ce.forEach(M=>{if(M===bt||M===Ft||M===Rt||M===$t)return;const F=M[zt];if(F){const U=A.get(F);if(U){j.set(U.name,M);return}}const z=Ct.find(U=>U.name===M.name);z&&j.set(z.name,M)}),j},[ce,Ct,bt,Ft,Rt,$t,x]),Te=m.useMemo(()=>new Set(Ct.map(j=>j.name)),[Ct]),Pt=m.useMemo(()=>{const j=[{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"]}}],A=[];return x?.enabled&&A.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"]}}),[...Ct,...j,...A]},[Ct,x]),Ht=m.useMemo(()=>Pt.filter(j=>j.name==="getState"||j.name==="setState"?!0:Te.has(j.name)),[Pt,Te]),wt=m.useMemo(()=>{const j=new Set;return j.add("getState"),j.add("setState"),x?.enabled&&(j.add("searchDocs"),j.add("fetchDocContent")),i.forEach(A=>{for(const[M,F]of J.entries())if(F===A){j.add(M);break}}),j},[i,J]);m.useEffect(()=>s||n?void 0:((async()=>{try{const A=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!A.ok)throw new Error("Failed to fetch token");const M=await A.json();S(M.clientToken),P.current=M.clientToken,N(M.expiresAt),I(null)}catch(A){console.error("[useAgent] Token fetch failed:",A),I(A instanceof Error?A.message:"Failed to fetch token")}})(),()=>{$.current&&clearTimeout($.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!k||s||n)return;$.current&&clearTimeout($.current);const j=Math.floor(Date.now()/1e3),A=k-j,F=Math.max(0,A-5);return $.current=setTimeout(async()=>{try{const z=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!z.ok)throw new Error("Failed to refresh token");const U=await z.json();S(U.clientToken),P.current=U.clientToken,N(U.expiresAt),I(null)}catch(z){console.error("[useAgent] Token refresh failed:",z),I(z instanceof Error?z.message:"Failed to refresh token")}},F*1e3),()=>{$.current&&clearTimeout($.current)}},[k,e,JSON.stringify(r),s,n]);const Be=async(j,A={})=>{const M=A.headers?new Headers(A.headers):new Headers;M.delete("user-agent"),M.delete("User-Agent"),console.log("[useAgent] Making request to:",j),console.log("[useAgent] Method:",A.method||"GET"),console.log("[useAgent] Has Authorization header:",M.has("Authorization")),console.log("[useAgent] Client token available:",!!P.current);try{const F=await fetch(j,{...A,headers:M});if(!F.ok){console.error("[useAgent] Request failed:",F.status,F.statusText);const z=await F.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",z)}return F}catch(F){throw console.error("[useAgent] Fetch error:",F),F}},ze=`${t}/chat`;console.log("[useAgent] Chat API URL:",ze);const{messages:jt,sendMessage:Ue,status:Se,error:_e,stop:Wn,addToolResult:Xt,setMessages:Gt}=Wi.useChat({id:Y||void 0,messages:l,transport:new Vn.DefaultChatTransport({api:ze,fetch:Be,headers:()=>{const j={};return P.current?(j.Authorization=`Bearer ${P.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),j},body:()=>{const j=Ht.map(M=>({name:M.name,description:M.description,inputSchema:M.jsonSchema})),A=j.filter(M=>M.name==="getState"||M.name==="setState").map(M=>M.name);return A.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",A),{tools:j,systemPrompt:c,state:ut.current,...C&&{ragFilters:C}}}}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{jt.forEach(j=>{j.role==="assistant"&&j.parts.forEach(A=>{if(!A.type?.startsWith("tool-")||A.state!=="input-available")return;const M=A.type.replace("tool-",""),F=A.toolCallId;if(Q.has(F))return;ot(U=>new Set(U).add(F));const z=ff(A.input);if(wt.has(M)){const U=J.get(M);U?(async()=>{try{const q=Ht.find(nt=>nt.name===M);let yt;if(q&&q.jsonSchema?.properties){const At=Object.keys(q.jsonSchema.properties).map(X=>z[X]);yt=await U(...At)}else if(M==="getState")yt=U();else if(M==="setState"){const nt=z.updates||z;yt=await U(nt)}else yt=await U(...Object.values(z));Xt({toolCallId:F,tool:M,output:yt})}catch(q){console.error(`[useAgent] Error executing tool ${M}:`,q),Xt({toolCallId:F,tool:M,output:`Error: ${q}`})}})():console.warn(`[useAgent] Tool ${M} not found in toolsMap`)}else f&&f({toolCall:{toolCallId:F,toolName:M,args:z}})})})},[jt,wt,J,f,Xt,Q,Ft,Ht]),m.useEffect(()=>{if(Se==="ready"&&jt.length>0&&g){const j=jt[jt.length-1];j&&j.role==="assistant"&&g({message:j,messages:jt,isAbort:!1,isDisconnect:!1,isError:!!_e})}},[Se,jt,_e,g]);async function Ae(){if(!(!r?.id||!w)){gt(!0);try{const A=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${w}`}})).json();Z(A.conversations||[])}catch(j){console.error("Failed to fetch conversations:",j)}finally{gt(!1)}}}m.useEffect(()=>{r?.id&&w&&Ae()},[JSON.stringify(r),w,t]),m.useEffect(()=>{if(!Y||!P.current)return;(async()=>{_n(!0),Nt(null);try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Y},format:"json"})});if(!A.ok){const q=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${q}`)}const F=(await A.json())?.value||{},z=!vt.current;let U;z?(U={...d,...F},vt.current=!0):U=F,ut.current=U,et(U)}catch(A){console.error("Failed to fetch state:",A);const M=A instanceof Error?A:new Error(String(A));Nt(M),vt.current||(ut.current=d,et(d),vt.current=!0)}finally{_n(!1)}})()},[Y,t]);async function We(j){mt(j),gt(!0);try{const A=await fetch(`${t}/conversations/${j}/messages`,{headers:{Authorization:`Bearer ${P.current}`}});if(!A.ok)throw new Error(`Failed to fetch messages: ${A.statusText}`);const F=(await A.json()).messages||[];Gt(F)}catch(A){console.error("Failed to load conversation messages:",A)}finally{gt(!1)}}async function mn(j){if(w)try{await fetch(`${t}/conversations/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${w}`}}),Z(L.filter(A=>A._id!==j)),j===Y&&pn()}catch(A){console.error("Failed to delete conversation:",A)}}function pn(){const j=crypto.randomUUID();mt(j),Gt([]),ot(new Set),ut.current=d,et(d),vt.current=!1}function Kn(j){Xt(j)}async function qn(j){const A={...ut.current,...j};ut.current=A,et(A);try{await ae(j)}catch(M){throw M}}async function Ke(){if(!r?.id||!P.current)throw new Error("User authentication required to share state");const j=`shared_${crypto.randomUUID()}`;try{return await fetch(`${t.replace("/chat","")}/convex/api/mutation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:create",args:{stateId:j,state:ut.current,projectId:"default",createdBy:r.id},format:"json"})}),j}catch(A){throw console.error("Failed to share state:",A),A}}async function Yt(j){if(!P.current)throw new Error("Authentication required to import state");try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:getByStateId",args:{stateId:j},format:"json"})});if(!A.ok)throw new Error("Failed to fetch shared state");const F=(await A.json())?.value||{};ut.current=F,et(F)}catch(A){throw console.error("Failed to import state:",A),A}}return{id:Y,messages:jt,status:Se,error:_e,sendMessage:Ue,stop:Wn,addToolOutput:Kn,setMessages:Gt,conversations:L,loadConversation:We,deleteConversation:mn,startNewConversation:pn,isLoadingConversations:Vt,clientToken:w,tokenError:V,state:ct,setState:qn,shareState:Ke,importState:Yt,isStateLoading:oe,stateError:we}}exports.verifyToken=ac.verifyToken;exports.ARCTEN_ORIGINAL_NAME=zt;exports.ArctenAgent=hf;exports.preserveToolName=qh;exports.useAgent=mf;