@arcteninc/core 0.0.88 → 0.0.89

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,4 +1,4 @@
1
- "use strict";var sc=Object.create;var Er=Object.defineProperty;var rc=Object.getOwnPropertyDescriptor;var ic=Object.getOwnPropertyNames;var oc=Object.getPrototypeOf,ac=Object.prototype.hasOwnProperty;var cc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ic(t))!ac.call(e,r)&&r!==n&&Er(e,r,{get:()=>t[r],enumerable:!(s=rc(t,r))||s.enumerable});return e};var lc=(e,t,n)=>(n=e!=null?sc(oc(e)):{},cc(t||!e||!e.__esModule?Er(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),me=require("lucide-react"),Yi=require("@ai-sdk/react"),On=require("ai"),Ji=require("@radix-ui/react-slot"),Zi=require("class-variance-authority"),uc=require("clsx"),dc=require("tailwind-merge"),hc=require("@radix-ui/react-tooltip"),Dr=require("@radix-ui/react-use-controllable-state"),fc=require("@radix-ui/react-collapsible"),mc=require("react-dom"),pc=require("./server.cjs");function $s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Fe=$s(m),$t=$s(hc),Bs=$s(fc);function pe(...e){return dc.twMerge(uc.clsx(e))}const wt=Zi.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"}}),Ln=Fe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?Ji.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:pe(wt({variant:t,size:n,className:e})),...r})});Ln.displayName="Button";const gc=Zi.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 Qn({className:e,variant:t,asChild:n=!1,...s}){const r=n?Ji.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:pe(gc({variant:t}),e),...s})}const yc=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Fe.useState(!0);Fe.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[e.current,t])},Qi=Fe.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Fe.useRef(null),[c,u]=Fe.useState("");return yc({textAreaRef:a,triggerAutoSize:c,maxHeight:e,minHeight:t}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Fe.useEffect(()=>{u(r)},[o?.defaultValue,r]),d.jsx("textarea",{...o,value:r,ref:a,className:pe("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)}})});Qi.displayName="AutosizeTextarea";function xc({delayDuration:e=0,...t}){return d.jsx($t.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ot({...e}){return d.jsx(xc,{children:d.jsx($t.Root,{"data-slot":"tooltip",...e})})}function at({...e}){return d.jsx($t.Trigger,{"data-slot":"tooltip-trigger",...e})}function ct({className:e,sideOffset:t=0,children:n,...s}){return d.jsx($t.Portal,{children:d.jsxs($t.Content,{"data-slot":"tooltip-content",sideOffset:t,className:pe("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,d.jsx($t.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Nr({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:pe("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const zs=m.createContext({});function Us(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const _s=typeof window<"u",eo=_s?m.useLayoutEffect:m.useEffect,_n=m.createContext(null);function Ws(e,t){e.indexOf(t)===-1&&e.push(t)}function Ks(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Xe=(e,t,n)=>n>t?t:n<e?e:n;function gs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let _t=()=>{},Ye=()=>{};process.env.NODE_ENV!=="production"&&(_t=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(gs(t,n))},Ye=(e,t,n)=>{if(!e)throw new Error(gs(t,n))});const Je={},to=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function no(e){return typeof e=="object"&&e!==null}const so=e=>/^0[^.\s]+$/u.test(e);function qs(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ne=e=>e,vc=(e,t)=>n=>t(e(n)),gn=(...e)=>e.reduce(vc),un=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Gs{constructor(){this.subscriptions=[]}add(t){return Ws(this.subscriptions,t),()=>Ks(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $e=e=>e*1e3,De=e=>e/1e3;function ro(e,t){return t?e*(1e3/t):0}const Rr=new Set;function Hs(e,t,n){e||Rr.has(t)||(console.warn(gs(t,n)),Rr.add(t))}const io=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,bc=1e-7,wc=12;function Tc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=io(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>bc&&++a<wc);return i}function yn(e,t,n,s){if(e===t&&n===s)return Ne;const r=o=>Tc(o,0,1,e,n);return o=>o===0||o===1?o:io(r(o),t,s)}const oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ao=e=>t=>1-e(1-t),co=yn(.33,1.53,.69,.99),Xs=ao(co),lo=oo(Xs),uo=e=>(e*=2)<1?.5*Xs(e):.5*(2-Math.pow(2,-10*(e-1))),Ys=e=>1-Math.sin(Math.acos(e)),ho=ao(Ys),fo=oo(Ys),Sc=yn(.42,0,1,1),Ac=yn(0,0,.58,1),mo=yn(.42,0,.58,1),Pc=e=>Array.isArray(e)&&typeof e[0]!="number",po=e=>Array.isArray(e)&&typeof e[0]=="number",Vr={linear:Ne,easeIn:Sc,easeInOut:mo,easeOut:Ac,circIn:Ys,circInOut:fo,circOut:ho,backIn:Xs,backInOut:lo,backOut:co,anticipate:uo},Cc=e=>typeof e=="string",Ir=e=>{if(po(e)){Ye(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return yn(t,n,s,r)}else if(Cc(e))return Ye(Vr[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Vr[e];return e},Cn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function jc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(l){i.has(l)&&(u.schedule(l),e()),l(a)}const u={schedule:(l,h=!1,f=!1)=>{const x=f&&r?n:s;return h&&i.add(l),x.has(l)||x.add(l),l},cancel:l=>{s.delete(l),i.delete(l)},process:l=>{if(a=l,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(l))}};return u}const kc=40;function go(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Cn.reduce((y,M)=>(y[M]=jc(o),y),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:x}=i,v=()=>{const y=Je.useManualTiming?r.timestamp:performance.now();n=!1,Je.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(y-r.timestamp,kc),1)),r.timestamp=y,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),x.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(v))},S=()=>{n=!0,s=!0,r.isProcessing||e(v)};return{schedule:Cn.reduce((y,M)=>{const k=i[M];return y[M]=(C,A=!1,E=!1)=>(n||S(),k.schedule(C,A,E)),y},{}),cancel:y=>{for(let M=0;M<Cn.length;M++)i[Cn[M]].cancel(y)},state:r,steps:i}}const{schedule:oe,cancel:ut,state:ve,steps:es}=go(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ne,!0);let Dn;function Mc(){Dn=void 0}const Ce={now:()=>(Dn===void 0&&Ce.set(ve.isProcessing||Je.useManualTiming?ve.timestamp:performance.now()),Dn),set:e=>{Dn=e,queueMicrotask(Mc)}},yo=e=>t=>typeof t=="string"&&t.startsWith(e),Js=yo("--"),Ec=yo("var(--"),Zs=e=>Ec(e)?Dc.test(e.split("/*")[0].trim()):!1,Dc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Wt={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},dn={...Wt,transform:e=>Xe(0,1,e)},jn={...Wt,default:1},sn=e=>Math.round(e*1e5)/1e5,Qs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Nc(e){return e==null}const Rc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,er=(e,t)=>n=>!!(typeof n=="string"&&Rc.test(n)&&n.startsWith(e)||t&&!Nc(n)&&Object.prototype.hasOwnProperty.call(n,t)),xo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Qs);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Vc=e=>Xe(0,255,e),ts={...Wt,transform:e=>Math.round(Vc(e))},St={test:er("rgb","red"),parse:xo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+ts.transform(e)+", "+ts.transform(t)+", "+ts.transform(n)+", "+sn(dn.transform(s))+")"};function Ic(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const ys={test:er("#"),parse:Ic,transform:St.transform},xn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),lt=xn("deg"),Ke=xn("%"),B=xn("px"),Oc=xn("vh"),Lc=xn("vw"),Or={...Ke,parse:e=>Ke.parse(e)/100,transform:e=>Ke.transform(e*100)},Rt={test:er("hsl","hue"),parse:xo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Ke.transform(sn(t))+", "+Ke.transform(sn(n))+", "+sn(dn.transform(s))+")"},fe={test:e=>St.test(e)||ys.test(e)||Rt.test(e),parse:e=>St.test(e)?St.parse(e):Rt.test(e)?Rt.parse(e):ys.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?St.transform(e):Rt.transform(e),getAnimatableNone:e=>{const t=fe.parse(e);return t.alpha=0,fe.transform(t)}},Fc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function $c(e){return isNaN(e)&&typeof e=="string"&&(e.match(Qs)?.length||0)+(e.match(Fc)?.length||0)>0}const vo="number",bo="color",Bc="var",zc="var(",Lr="${}",Uc=/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 hn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(Uc,c=>(fe.test(c)?(s.color.push(o),r.push(bo),n.push(fe.parse(c))):c.startsWith(zc)?(s.var.push(o),r.push(Bc),n.push(c)):(s.number.push(o),r.push(vo),n.push(parseFloat(c))),++o,Lr)).split(Lr);return{values:n,split:a,indexes:s,types:r}}function wo(e){return hn(e).values}function To(e){const{split:t,types:n}=hn(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===vo?o+=sn(r[i]):a===bo?o+=fe.transform(r[i]):o+=r[i]}return o}}const _c=e=>typeof e=="number"?0:fe.test(e)?fe.getAnimatableNone(e):e;function Wc(e){const t=wo(e);return To(e)(t.map(_c))}const dt={test:$c,parse:wo,createTransformer:To,getAnimatableNone:Wc};function ns(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Kc({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=ns(c,a,e+1/3),o=ns(c,a,e),i=ns(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function Fn(e,t){return n=>n>0?t:e}const ce=(e,t,n)=>e+(t-e)*n,ss=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},qc=[ys,St,Rt],Gc=e=>qc.find(t=>t.test(e));function Fr(e){const t=Gc(e);if(_t(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Rt&&(n=Kc(n)),n}const $r=(e,t)=>{const n=Fr(e),s=Fr(t);if(!n||!s)return Fn(e,t);const r={...n};return o=>(r.red=ss(n.red,s.red,o),r.green=ss(n.green,s.green,o),r.blue=ss(n.blue,s.blue,o),r.alpha=ce(n.alpha,s.alpha,o),St.transform(r))},xs=new Set(["none","hidden"]);function Hc(e,t){return xs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Xc(e,t){return n=>ce(e,t,n)}function tr(e){return typeof e=="number"?Xc:typeof e=="string"?Zs(e)?Fn:fe.test(e)?$r:Zc:Array.isArray(e)?So:typeof e=="object"?fe.test(e)?$r:Yc:Fn}function So(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>tr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Yc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=tr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Jc(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const Zc=(e,t)=>{const n=dt.createTransformer(t),s=hn(e),r=hn(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?xs.has(e)&&!r.values.length||xs.has(t)&&!s.values.length?Hc(e,t):gn(So(Jc(s,r),r.values),n):(_t(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),Fn(e,t))};function Ao(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?ce(e,t,n):tr(e)(e,t)}const Qc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>oe.update(t,n),stop:()=>ut(t),now:()=>ve.isProcessing?ve.timestamp:Ce.now()}},Po=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},$n=2e4;function nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<$n;)t+=n,s=e.next(t);return t>=$n?1/0:t}function el(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(nr(s),$n);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:De(r)}}const tl=5;function Co(e,t,n){const s=Math.max(t-tl,0);return ro(n-e(s),t-s)}const ae={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},rs=.001;function nl({duration:e=ae.duration,bounce:t=ae.bounce,velocity:n=ae.velocity,mass:s=ae.mass}){let r,o;_t(e<=$e(ae.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=Xe(ae.minDamping,ae.maxDamping,i),e=Xe(ae.minDuration,ae.maxDuration,De(e)),i<1?(r=u=>{const l=u*i,h=l*e,f=l-n,g=vs(u,i),x=Math.exp(-h);return rs-f/g*x},o=u=>{const h=u*i*e,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*e,x=Math.exp(-h),v=vs(Math.pow(u,2),i);return(-r(u)+rs>0?-1:1)*((f-g)*x)/v}):(r=u=>{const l=Math.exp(-u*e),h=(u-n)*e+1;return-rs+l*h},o=u=>{const l=Math.exp(-u*e),h=(n-u)*(e*e);return l*h});const a=5/e,c=rl(r,o,a);if(e=$e(e),isNaN(c))return{stiffness:ae.stiffness,damping:ae.damping,duration:e};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const sl=12;function rl(e,t,n){let s=n;for(let r=1;r<sl;r++)s=s-e(s)/t(s);return s}function vs(e,t){return e*Math.sqrt(1-t*t)}const il=["duration","bounce"],ol=["stiffness","damping","mass"];function Br(e,t){return t.some(n=>e[n]!==void 0)}function al(e){let t={velocity:ae.velocity,stiffness:ae.stiffness,damping:ae.damping,mass:ae.mass,isResolvedFromDuration:!1,...e};if(!Br(e,ol)&&Br(e,il))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Xe(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:ae.mass,stiffness:r,damping:o}}else{const n=nl(e);t={...t,...n,mass:ae.mass},t.isResolvedFromDuration=!0}return t}function Bn(e=ae.visualDuration,t=ae.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:l,duration:h,velocity:f,isResolvedFromDuration:g}=al({...n,velocity:-De(n.velocity||0)}),x=f||0,v=u/(2*Math.sqrt(c*l)),S=i-o,T=De(Math.sqrt(c/l)),b=Math.abs(S)<5;s||(s=b?ae.restSpeed.granular:ae.restSpeed.default),r||(r=b?ae.restDelta.granular:ae.restDelta.default);let y;if(v<1){const k=vs(T,v);y=C=>{const A=Math.exp(-v*T*C);return i-A*((x+v*T*S)/k*Math.sin(k*C)+S*Math.cos(k*C))}}else if(v===1)y=k=>i-Math.exp(-T*k)*(S+(x+T*S)*k);else{const k=T*Math.sqrt(v*v-1);y=C=>{const A=Math.exp(-v*T*C),E=Math.min(k*C,300);return i-A*((x+v*T*S)*Math.sinh(E)+k*S*Math.cosh(E))/k}}const M={calculatedDuration:g&&h||null,next:k=>{const C=y(k);if(g)a.done=k>=h;else{let A=k===0?x:0;v<1&&(A=k===0?$e(x):Co(y,k,C));const E=Math.abs(A)<=s,X=Math.abs(i-C)<=r;a.done=E&&X}return a.value=a.done?i:C,a},toString:()=>{const k=Math.min(nr(M),$n),C=Po(A=>M.next(k*A).value,k,30);return k+"ms "+C},toTransition:()=>{}};return M}Bn.applyToOptions=e=>{const t=el(e,100,Bn);return e.ease=t.ease,e.duration=$e(t.duration),e.type="keyframes",e};function bs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:l}){const h=e[0],f={done:!1,value:h},g=E=>a!==void 0&&E<a||c!==void 0&&E>c,x=E=>a===void 0?c:c===void 0||Math.abs(a-E)<Math.abs(c-E)?a:c;let v=n*t;const S=h+v,T=i===void 0?S:i(S);T!==S&&(v=T-h);const b=E=>-v*Math.exp(-E/s),y=E=>T+b(E),M=E=>{const X=b(E),O=y(E);f.done=Math.abs(X)<=u,f.value=f.done?T:O};let k,C;const A=E=>{g(f.value)&&(k=E,C=Bn({keyframes:[f.value,x(f.value)],velocity:Co(y,E,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return A(0),{calculatedDuration:null,next:E=>{let X=!1;return!C&&k===void 0&&(X=!0,M(E),A(E)),k!==void 0&&E>=k?C.next(E-k):(!X&&M(E),f)}}}function cl(e,t,n){const s=[],r=n||Je.mix||Ao,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const c=Array.isArray(t)?t[i]||Ne:t;a=gn(c,a)}s.push(a)}return s}function ll(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(Ye(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=cl(t,s,r),c=a.length,u=l=>{if(i&&l<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(l<e[h+1]);h++);const f=un(e[h],e[h+1],l);return a[h](f)};return n?l=>u(Xe(e[0],e[o-1],l)):u}function ul(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=un(0,t,s);e.push(ce(n,1,r))}}function dl(e){const t=[0];return ul(t,e.length-1),t}function hl(e,t){return e.map(n=>n*t)}function fl(e,t){return e.map(()=>t||mo).splice(0,e.length-1)}function Vt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Pc(s)?s.map(Ir):Ir(s),o={done:!1,value:t[0]},i=hl(n&&n.length===t.length?n:dl(t),e),a=ll(i,t,{ease:Array.isArray(r)?r:fl(t,r)});return{calculatedDuration:e,next:c=>(o.value=a(c),o.done=c>=e,o)}}const ml=e=>e!==null;function sr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(ml),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const pl={decay:bs,inertia:bs,tween:Vt,keyframes:Vt,spring:Bn};function jo(e){typeof e.type=="string"&&(e.type=pl[e.type])}class rr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const gl=e=>e/100;class ir extends rr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ce.now()&&this.tick(Ce.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;jo(t);const{type:n=Vt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const c=n||Vt;process.env.NODE_ENV!=="production"&&c!==Vt&&Ye(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Vt&&typeof a[0]!="number"&&(this.mixKeyframes=gn(gl,Ao(a[0],a[1])),a=[0,100]);const u=c({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=nr(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:h,repeatType:f,repeatDelay:g,type:x,onUpdate:v,finalKeyframe:S}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const T=this.currentTime-u*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?T<0:T>r;this.currentTime=Math.max(T,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let y=this.currentTime,M=s;if(h){const E=Math.min(this.currentTime,r)/a;let X=Math.floor(E),O=E%1;!O&&E>=1&&(O=1),O===1&&X--,X=Math.min(X,h+1),!!(X%2)&&(f==="reverse"?(O=1-O,g&&(O-=g/a)):f==="mirror"&&(M=i)),y=Xe(0,1,O)*a}const k=b?{done:!1,value:l[0]}:M.next(y);o&&(k.value=o(k.value));let{done:C}=k;!b&&c!==null&&(C=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const A=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&C);return A&&x!==bs&&(k.value=sr(l,this.options,S,this.speed)),v&&v(k.value),A&&this.finish(),k}then(t,n){return this.finished.then(t,n)}get duration(){return De(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+De(t)}get time(){return De(this.currentTime)}set time(t){t=$e(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Ce.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=De(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Qc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ce.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function yl(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const At=e=>e*180/Math.PI,ws=e=>{const t=At(Math.atan2(e[1],e[0]));return Ts(t)},xl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:ws,rotateZ:ws,skewX:e=>At(Math.atan(e[1])),skewY:e=>At(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ts=e=>(e=e%360,e<0&&(e+=360),e),zr=ws,Ur=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),_r=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),vl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ur,scaleY:_r,scale:e=>(Ur(e)+_r(e))/2,rotateX:e=>Ts(At(Math.atan2(e[6],e[5]))),rotateY:e=>Ts(At(Math.atan2(-e[2],e[0]))),rotateZ:zr,rotate:zr,skewX:e=>At(Math.atan(e[4])),skewY:e=>At(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Ss(e){return e.includes("scale")?1:0}function As(e,t){if(!e||e==="none")return Ss(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=vl,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=xl,r=a}if(!r)return Ss(t);const o=s[t],i=r[1].split(",").map(wl);return typeof o=="function"?o(i):i[o]}const bl=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return As(n,t)};function wl(e){return parseFloat(e.trim())}const Kt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],qt=new Set(Kt),Wr=e=>e===Wt||e===B,Tl=new Set(["x","y","z"]),Sl=Kt.filter(e=>!Tl.has(e));function Al(e){const t=[];return Sl.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Pt={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>As(t,"x"),y:(e,{transform:t})=>As(t,"y")};Pt.translateX=Pt.x;Pt.translateY=Pt.y;const Ct=new Set;let Ps=!1,Cs=!1,js=!1;function ko(){if(Cs){const e=Array.from(Ct).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Al(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Cs=!1,Ps=!1,Ct.forEach(e=>e.complete(js)),Ct.clear()}function Mo(){Ct.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Cs=!0)})}function Pl(){js=!0,Mo(),ko(),js=!1}class or{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ct.add(this),Ps||(Ps=!0,oe.read(Mo),oe.resolveKeyframes(ko))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}yl(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ct.delete(this)}cancel(){this.state==="scheduled"&&(Ct.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Cl=e=>e.startsWith("--");function jl(e,t,n){Cl(t)?e.style.setProperty(t,n):e.style[t]=n}const kl=qs(()=>window.ScrollTimeline!==void 0),Ml={};function El(e,t){const n=qs(e);return()=>Ml[t]??n()}const Eo=El(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),nn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,Kr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:nn([0,.65,.55,1]),circOut:nn([.55,0,1,.45]),backIn:nn([.31,.01,.66,-.59]),backOut:nn([.33,1.53,.69,.99])};function Do(e,t){if(e)return typeof e=="function"?Eo()?Po(e,t):"ease-out":po(e)?nn(e):Array.isArray(e)?e.map(n=>Do(n,t)||Kr.easeOut):Kr[e]}function Dl(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[t]:n};c&&(l.offset=c);const h=Do(a,r);Array.isArray(h)&&(l.easing=h);const f={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(f.pseudoElement=u),e.animate(l,f)}function No(e){return typeof e=="function"&&"applyToOptions"in e}function Nl({type:e,...t}){return No(e)&&Eo()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Rl extends rr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,Ye(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Nl(t);this.animation=Dl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=sr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):jl(n,s,l),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return De(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+De(t)}get time(){return De(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=$e(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&kl()?(this.animation.timeline=t,Ne):n(this)}}const Ro={anticipate:uo,backInOut:lo,circInOut:fo};function Vl(e){return e in Ro}function Il(e){typeof e.ease=="string"&&Vl(e.ease)&&(e.ease=Ro[e.ease])}const qr=10;class Ol extends Rl{constructor(t){Il(t),jo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new ir({...i,autoplay:!1}),c=$e(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-qr).value,a.sample(c).value,qr),a.stop()}}const Gr=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(dt.test(e)||e==="0")&&!e.startsWith("url("));function Ll(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function Fl(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=Gr(r,t),a=Gr(o,t);return _t(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Ll(e)||(n==="spring"||No(n))&&s}function ks(e){e.duration=0,e.type="keyframes"}const $l=new Set(["opacity","clipPath","filter","transform"]),Bl=qs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function zl(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=t.owner.getProps();return Bl()&&n&&$l.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Ul=40;class _l extends rr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ce.now();const f={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...h},g=l?.KeyframeResolver||or;this.keyframeResolver=new g(a,(x,v,S)=>this.onKeyframesResolved(x,v,f,!S),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=Ce.now(),Fl(t,o,i,a)||((Je.instantAnimations||!c)&&l?.(sr(t,s,n)),t[0]=t[t.length-1],ks(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Ul?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=!u&&zl(f)?new Ol({...f,element:f.motionValue.owner.current}):new ir(f);g.finished.then(()=>this.notifyFinished()).catch(Ne),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Pl()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Wl=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Kl(e){const t=Wl.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const ql=4;function Vo(e,t,n=1){Ye(n<=ql,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Kl(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return to(i)?parseFloat(i):i}return Zs(r)?Vo(r,t,n+1):r}function ar(e,t){return e?.[t]??e?.default??e}const Io=new Set(["width","height","top","left","right","bottom",...Kt]),Gl={test:e=>e==="auto",parse:e=>e},Oo=e=>t=>t.test(e),Lo=[Wt,B,Ke,lt,Lc,Oc,Gl],Hr=e=>Lo.find(Oo(e));function Hl(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||so(e):!0}const Xl=new Set(["brightness","contrast","saturate","opacity"]);function Yl(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Qs)||[];if(!s)return e;const r=n.replace(s,"");let o=Xl.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Jl=/\b([a-z-]*)\(.*?\)/gu,Ms={...dt,getAnimatableNone:e=>{const t=e.match(Jl);return t?t.map(Yl).join(" "):e}},Xr={...Wt,transform:Math.round},Zl={rotate:lt,rotateX:lt,rotateY:lt,rotateZ:lt,scale:jn,scaleX:jn,scaleY:jn,scaleZ:jn,skew:lt,skewX:lt,skewY:lt,distance:B,translateX:B,translateY:B,translateZ:B,x:B,y:B,z:B,perspective:B,transformPerspective:B,opacity:dn,originX:Or,originY:Or,originZ:B},cr={borderWidth:B,borderTopWidth:B,borderRightWidth:B,borderBottomWidth:B,borderLeftWidth:B,borderRadius:B,radius:B,borderTopLeftRadius:B,borderTopRightRadius:B,borderBottomRightRadius:B,borderBottomLeftRadius:B,width:B,maxWidth:B,height:B,maxHeight:B,top:B,right:B,bottom:B,left:B,padding:B,paddingTop:B,paddingRight:B,paddingBottom:B,paddingLeft:B,margin:B,marginTop:B,marginRight:B,marginBottom:B,marginLeft:B,backgroundPositionX:B,backgroundPositionY:B,...Zl,zIndex:Xr,fillOpacity:dn,strokeOpacity:dn,numOctaves:Xr},Ql={...cr,color:fe,backgroundColor:fe,outlineColor:fe,fill:fe,stroke:fe,borderColor:fe,borderTopColor:fe,borderRightColor:fe,borderBottomColor:fe,borderLeftColor:fe,filter:Ms,WebkitFilter:Ms},Fo=e=>Ql[e];function $o(e,t){let n=Fo(e);return n!==Ms&&(n=dt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const eu=new Set(["auto","none","0"]);function tu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!eu.has(o)&&hn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=$o(n,r)}class nu extends or{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),Zs(u))){const l=Vo(u,n.current);l!==void 0&&(t[c]=l),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Io.has(s)||t.length!==2)return;const[r,o]=t,i=Hr(r),a=Hr(o);if(i!==a)if(Wr(i)&&Wr(a))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else Pt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||Hl(t[r]))&&s.push(r);s.length&&tu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Pt[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Pt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{t.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function su(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const Bo=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function zo(e){return no(e)&&"offsetHeight"in e}const Yr=30,ru=e=>!isNaN(parseFloat(e));class iu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ce.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ce.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=ru(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Hs(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Gs);const s=this.events[t].add(n);return t==="change"?()=>{s(),oe.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Ce.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Yr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Yr);return ro(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function zt(e,t){return new iu(e,t)}const{schedule:lr}=go(queueMicrotask,!1),Le={x:!1,y:!1};function Uo(){return Le.x||Le.y}function ou(e){return e==="x"||e==="y"?Le[e]?null:(Le[e]=!0,()=>{Le[e]=!1}):Le.x||Le.y?null:(Le.x=Le.y=!0,()=>{Le.x=Le.y=!1})}function _o(e,t){const n=su(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Jr(e){return!(e.pointerType==="touch"||Uo())}function au(e,t,n={}){const[s,r,o]=_o(e,n),i=a=>{if(!Jr(a))return;const{target:c}=a,u=t(c,a);if(typeof u!="function"||!c)return;const l=h=>{Jr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Wo=(e,t)=>t?e===t?!0:Wo(e,t.parentElement):!1,ur=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,cu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function lu(e){return cu.has(e.tagName)||e.tabIndex!==-1}const Nn=new WeakSet;function Zr(e){return t=>{t.key==="Enter"&&e(t)}}function is(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const uu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Zr(()=>{if(Nn.has(n))return;is(n,"down");const r=Zr(()=>{is(n,"up")}),o=()=>is(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Qr(e){return ur(e)&&!Uo()}function du(e,t,n={}){const[s,r,o]=_o(e,n),i=a=>{const c=a.currentTarget;if(!Qr(a))return;Nn.add(c);const u=t(c,a),l=(g,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),Nn.has(c)&&Nn.delete(c),Qr(g)&&typeof u=="function"&&u(g,{success:x})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Wo(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),zo(a)&&(a.addEventListener("focus",u=>uu(u,r)),!lu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Ko(e){return no(e)&&"ownerSVGElement"in e}function hu(e){return Ko(e)&&e.tagName==="svg"}const Te=e=>!!(e&&e.getVelocity),fu=[...Lo,fe,dt],mu=e=>fu.find(Oo(e)),dr=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ei(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=ei(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():ei(e[r],null)}}}}function gu(...e){return Fe.useCallback(pu(...e),e)}class yu extends Fe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=zo(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 xu({children:e,isPresent:t,anchorX:n,root:s}){const r=m.useId(),o=m.useRef(null),i=m.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=m.useContext(dr),c=gu(o,e?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:h,left:f,right:g}=i.current;if(t||!o.current||!u||!l)return;const x=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const v=document.createElement("style");a&&(v.nonce=a);const S=s??document.head;return S.appendChild(v),v.sheet&&v.sheet.insertRule(`
1
+ "use strict";var sc=Object.create;var Er=Object.defineProperty;var rc=Object.getOwnPropertyDescriptor;var ic=Object.getOwnPropertyNames;var oc=Object.getPrototypeOf,ac=Object.prototype.hasOwnProperty;var cc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ic(t))!ac.call(e,r)&&r!==n&&Er(e,r,{get:()=>t[r],enumerable:!(s=rc(t,r))||s.enumerable});return e};var lc=(e,t,n)=>(n=e!=null?sc(oc(e)):{},cc(t||!e||!e.__esModule?Er(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),me=require("lucide-react"),Yi=require("@ai-sdk/react"),On=require("ai"),Ji=require("@radix-ui/react-slot"),Zi=require("class-variance-authority"),uc=require("clsx"),dc=require("tailwind-merge"),hc=require("@radix-ui/react-tooltip"),Dr=require("@radix-ui/react-use-controllable-state"),fc=require("@radix-ui/react-collapsible"),mc=require("react-dom"),pc=require("./server.cjs");function $s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Fe=$s(m),$t=$s(hc),Bs=$s(fc);function pe(...e){return dc.twMerge(uc.clsx(e))}const wt=Zi.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"}}),Ln=Fe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?Ji.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:pe(wt({variant:t,size:n,className:e})),...r})});Ln.displayName="Button";const gc=Zi.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 Qn({className:e,variant:t,asChild:n=!1,...s}){const r=n?Ji.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:pe(gc({variant:t}),e),...s})}const yc=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Fe.useState(!0);Fe.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[e.current,t])},Qi=Fe.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Fe.useRef(null),[c,u]=Fe.useState("");return yc({textAreaRef:a,triggerAutoSize:c,maxHeight:e,minHeight:t}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Fe.useEffect(()=>{u(r)},[o?.defaultValue,r]),d.jsx("textarea",{...o,value:r,ref:a,className:pe("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)}})});Qi.displayName="AutosizeTextarea";function xc({delayDuration:e=0,...t}){return d.jsx($t.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ot({...e}){return d.jsx(xc,{children:d.jsx($t.Root,{"data-slot":"tooltip",...e})})}function at({...e}){return d.jsx($t.Trigger,{"data-slot":"tooltip-trigger",...e})}function ct({className:e,sideOffset:t=0,children:n,...s}){return d.jsx($t.Portal,{children:d.jsxs($t.Content,{"data-slot":"tooltip-content",sideOffset:t,className:pe("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,d.jsx($t.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Nr({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:pe("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const zs=m.createContext({});function Us(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const _s=typeof window<"u",eo=_s?m.useLayoutEffect:m.useEffect,_n=m.createContext(null);function Ws(e,t){e.indexOf(t)===-1&&e.push(t)}function Ks(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Xe=(e,t,n)=>n>t?t:n<e?e:n;function gs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let _t=()=>{},Ye=()=>{};process.env.NODE_ENV!=="production"&&(_t=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(gs(t,n))},Ye=(e,t,n)=>{if(!e)throw new Error(gs(t,n))});const Je={},to=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function no(e){return typeof e=="object"&&e!==null}const so=e=>/^0[^.\s]+$/u.test(e);function qs(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ne=e=>e,vc=(e,t)=>n=>t(e(n)),gn=(...e)=>e.reduce(vc),un=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Gs{constructor(){this.subscriptions=[]}add(t){return Ws(this.subscriptions,t),()=>Ks(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $e=e=>e*1e3,De=e=>e/1e3;function ro(e,t){return t?e*(1e3/t):0}const Rr=new Set;function Hs(e,t,n){e||Rr.has(t)||(console.warn(gs(t,n)),Rr.add(t))}const io=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,bc=1e-7,wc=12;function Tc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=io(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>bc&&++a<wc);return i}function yn(e,t,n,s){if(e===t&&n===s)return Ne;const r=o=>Tc(o,0,1,e,n);return o=>o===0||o===1?o:io(r(o),t,s)}const oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ao=e=>t=>1-e(1-t),co=yn(.33,1.53,.69,.99),Xs=ao(co),lo=oo(Xs),uo=e=>(e*=2)<1?.5*Xs(e):.5*(2-Math.pow(2,-10*(e-1))),Ys=e=>1-Math.sin(Math.acos(e)),ho=ao(Ys),fo=oo(Ys),Sc=yn(.42,0,1,1),Ac=yn(0,0,.58,1),mo=yn(.42,0,.58,1),Pc=e=>Array.isArray(e)&&typeof e[0]!="number",po=e=>Array.isArray(e)&&typeof e[0]=="number",Vr={linear:Ne,easeIn:Sc,easeInOut:mo,easeOut:Ac,circIn:Ys,circInOut:fo,circOut:ho,backIn:Xs,backInOut:lo,backOut:co,anticipate:uo},Cc=e=>typeof e=="string",Ir=e=>{if(po(e)){Ye(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return yn(t,n,s,r)}else if(Cc(e))return Ye(Vr[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Vr[e];return e},Cn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function jc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(l){i.has(l)&&(u.schedule(l),e()),l(a)}const u={schedule:(l,h=!1,f=!1)=>{const x=f&&r?n:s;return h&&i.add(l),x.has(l)||x.add(l),l},cancel:l=>{s.delete(l),i.delete(l)},process:l=>{if(a=l,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(l))}};return u}const kc=40;function go(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Cn.reduce((y,M)=>(y[M]=jc(o),y),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:x}=i,v=()=>{const y=Je.useManualTiming?r.timestamp:performance.now();n=!1,Je.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(y-r.timestamp,kc),1)),r.timestamp=y,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),x.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(v))},S=()=>{n=!0,s=!0,r.isProcessing||e(v)};return{schedule:Cn.reduce((y,M)=>{const k=i[M];return y[M]=(C,A=!1,E=!1)=>(n||S(),k.schedule(C,A,E)),y},{}),cancel:y=>{for(let M=0;M<Cn.length;M++)i[Cn[M]].cancel(y)},state:r,steps:i}}const{schedule:oe,cancel:ut,state:ve,steps:es}=go(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ne,!0);let Dn;function Mc(){Dn=void 0}const Ce={now:()=>(Dn===void 0&&Ce.set(ve.isProcessing||Je.useManualTiming?ve.timestamp:performance.now()),Dn),set:e=>{Dn=e,queueMicrotask(Mc)}},yo=e=>t=>typeof t=="string"&&t.startsWith(e),Js=yo("--"),Ec=yo("var(--"),Zs=e=>Ec(e)?Dc.test(e.split("/*")[0].trim()):!1,Dc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Wt={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},dn={...Wt,transform:e=>Xe(0,1,e)},jn={...Wt,default:1},sn=e=>Math.round(e*1e5)/1e5,Qs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Nc(e){return e==null}const Rc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,er=(e,t)=>n=>!!(typeof n=="string"&&Rc.test(n)&&n.startsWith(e)||t&&!Nc(n)&&Object.prototype.hasOwnProperty.call(n,t)),xo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Qs);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Vc=e=>Xe(0,255,e),ts={...Wt,transform:e=>Math.round(Vc(e))},St={test:er("rgb","red"),parse:xo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+ts.transform(e)+", "+ts.transform(t)+", "+ts.transform(n)+", "+sn(dn.transform(s))+")"};function Ic(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const ys={test:er("#"),parse:Ic,transform:St.transform},xn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),lt=xn("deg"),Ke=xn("%"),B=xn("px"),Oc=xn("vh"),Lc=xn("vw"),Or={...Ke,parse:e=>Ke.parse(e)/100,transform:e=>Ke.transform(e*100)},Rt={test:er("hsl","hue"),parse:xo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Ke.transform(sn(t))+", "+Ke.transform(sn(n))+", "+sn(dn.transform(s))+")"},fe={test:e=>St.test(e)||ys.test(e)||Rt.test(e),parse:e=>St.test(e)?St.parse(e):Rt.test(e)?Rt.parse(e):ys.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?St.transform(e):Rt.transform(e),getAnimatableNone:e=>{const t=fe.parse(e);return t.alpha=0,fe.transform(t)}},Fc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function $c(e){return isNaN(e)&&typeof e=="string"&&(e.match(Qs)?.length||0)+(e.match(Fc)?.length||0)>0}const vo="number",bo="color",Bc="var",zc="var(",Lr="${}",Uc=/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 hn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(Uc,c=>(fe.test(c)?(s.color.push(o),r.push(bo),n.push(fe.parse(c))):c.startsWith(zc)?(s.var.push(o),r.push(Bc),n.push(c)):(s.number.push(o),r.push(vo),n.push(parseFloat(c))),++o,Lr)).split(Lr);return{values:n,split:a,indexes:s,types:r}}function wo(e){return hn(e).values}function To(e){const{split:t,types:n}=hn(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===vo?o+=sn(r[i]):a===bo?o+=fe.transform(r[i]):o+=r[i]}return o}}const _c=e=>typeof e=="number"?0:fe.test(e)?fe.getAnimatableNone(e):e;function Wc(e){const t=wo(e);return To(e)(t.map(_c))}const dt={test:$c,parse:wo,createTransformer:To,getAnimatableNone:Wc};function ns(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Kc({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=ns(c,a,e+1/3),o=ns(c,a,e),i=ns(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function Fn(e,t){return n=>n>0?t:e}const ce=(e,t,n)=>e+(t-e)*n,ss=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},qc=[ys,St,Rt],Gc=e=>qc.find(t=>t.test(e));function Fr(e){const t=Gc(e);if(_t(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Rt&&(n=Kc(n)),n}const $r=(e,t)=>{const n=Fr(e),s=Fr(t);if(!n||!s)return Fn(e,t);const r={...n};return o=>(r.red=ss(n.red,s.red,o),r.green=ss(n.green,s.green,o),r.blue=ss(n.blue,s.blue,o),r.alpha=ce(n.alpha,s.alpha,o),St.transform(r))},xs=new Set(["none","hidden"]);function Hc(e,t){return xs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Xc(e,t){return n=>ce(e,t,n)}function tr(e){return typeof e=="number"?Xc:typeof e=="string"?Zs(e)?Fn:fe.test(e)?$r:Zc:Array.isArray(e)?So:typeof e=="object"?fe.test(e)?$r:Yc:Fn}function So(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>tr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Yc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=tr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Jc(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const Zc=(e,t)=>{const n=dt.createTransformer(t),s=hn(e),r=hn(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?xs.has(e)&&!r.values.length||xs.has(t)&&!s.values.length?Hc(e,t):gn(So(Jc(s,r),r.values),n):(_t(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),Fn(e,t))};function Ao(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?ce(e,t,n):tr(e)(e,t)}const Qc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>oe.update(t,n),stop:()=>ut(t),now:()=>ve.isProcessing?ve.timestamp:Ce.now()}},Po=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},$n=2e4;function nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<$n;)t+=n,s=e.next(t);return t>=$n?1/0:t}function el(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(nr(s),$n);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:De(r)}}const tl=5;function Co(e,t,n){const s=Math.max(t-tl,0);return ro(n-e(s),t-s)}const ae={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},rs=.001;function nl({duration:e=ae.duration,bounce:t=ae.bounce,velocity:n=ae.velocity,mass:s=ae.mass}){let r,o;_t(e<=$e(ae.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=Xe(ae.minDamping,ae.maxDamping,i),e=Xe(ae.minDuration,ae.maxDuration,De(e)),i<1?(r=u=>{const l=u*i,h=l*e,f=l-n,g=vs(u,i),x=Math.exp(-h);return rs-f/g*x},o=u=>{const h=u*i*e,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*e,x=Math.exp(-h),v=vs(Math.pow(u,2),i);return(-r(u)+rs>0?-1:1)*((f-g)*x)/v}):(r=u=>{const l=Math.exp(-u*e),h=(u-n)*e+1;return-rs+l*h},o=u=>{const l=Math.exp(-u*e),h=(n-u)*(e*e);return l*h});const a=5/e,c=rl(r,o,a);if(e=$e(e),isNaN(c))return{stiffness:ae.stiffness,damping:ae.damping,duration:e};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:e}}}const sl=12;function rl(e,t,n){let s=n;for(let r=1;r<sl;r++)s=s-e(s)/t(s);return s}function vs(e,t){return e*Math.sqrt(1-t*t)}const il=["duration","bounce"],ol=["stiffness","damping","mass"];function Br(e,t){return t.some(n=>e[n]!==void 0)}function al(e){let t={velocity:ae.velocity,stiffness:ae.stiffness,damping:ae.damping,mass:ae.mass,isResolvedFromDuration:!1,...e};if(!Br(e,ol)&&Br(e,il))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Xe(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:ae.mass,stiffness:r,damping:o}}else{const n=nl(e);t={...t,...n,mass:ae.mass},t.isResolvedFromDuration=!0}return t}function Bn(e=ae.visualDuration,t=ae.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:l,duration:h,velocity:f,isResolvedFromDuration:g}=al({...n,velocity:-De(n.velocity||0)}),x=f||0,v=u/(2*Math.sqrt(c*l)),S=i-o,T=De(Math.sqrt(c/l)),b=Math.abs(S)<5;s||(s=b?ae.restSpeed.granular:ae.restSpeed.default),r||(r=b?ae.restDelta.granular:ae.restDelta.default);let y;if(v<1){const k=vs(T,v);y=C=>{const A=Math.exp(-v*T*C);return i-A*((x+v*T*S)/k*Math.sin(k*C)+S*Math.cos(k*C))}}else if(v===1)y=k=>i-Math.exp(-T*k)*(S+(x+T*S)*k);else{const k=T*Math.sqrt(v*v-1);y=C=>{const A=Math.exp(-v*T*C),E=Math.min(k*C,300);return i-A*((x+v*T*S)*Math.sinh(E)+k*S*Math.cosh(E))/k}}const M={calculatedDuration:g&&h||null,next:k=>{const C=y(k);if(g)a.done=k>=h;else{let A=k===0?x:0;v<1&&(A=k===0?$e(x):Co(y,k,C));const E=Math.abs(A)<=s,X=Math.abs(i-C)<=r;a.done=E&&X}return a.value=a.done?i:C,a},toString:()=>{const k=Math.min(nr(M),$n),C=Po(A=>M.next(k*A).value,k,30);return k+"ms "+C},toTransition:()=>{}};return M}Bn.applyToOptions=e=>{const t=el(e,100,Bn);return e.ease=t.ease,e.duration=$e(t.duration),e.type="keyframes",e};function bs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:l}){const h=e[0],f={done:!1,value:h},g=E=>a!==void 0&&E<a||c!==void 0&&E>c,x=E=>a===void 0?c:c===void 0||Math.abs(a-E)<Math.abs(c-E)?a:c;let v=n*t;const S=h+v,T=i===void 0?S:i(S);T!==S&&(v=T-h);const b=E=>-v*Math.exp(-E/s),y=E=>T+b(E),M=E=>{const X=b(E),L=y(E);f.done=Math.abs(X)<=u,f.value=f.done?T:L};let k,C;const A=E=>{g(f.value)&&(k=E,C=Bn({keyframes:[f.value,x(f.value)],velocity:Co(y,E,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return A(0),{calculatedDuration:null,next:E=>{let X=!1;return!C&&k===void 0&&(X=!0,M(E),A(E)),k!==void 0&&E>=k?C.next(E-k):(!X&&M(E),f)}}}function cl(e,t,n){const s=[],r=n||Je.mix||Ao,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const c=Array.isArray(t)?t[i]||Ne:t;a=gn(c,a)}s.push(a)}return s}function ll(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(Ye(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=cl(t,s,r),c=a.length,u=l=>{if(i&&l<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(l<e[h+1]);h++);const f=un(e[h],e[h+1],l);return a[h](f)};return n?l=>u(Xe(e[0],e[o-1],l)):u}function ul(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=un(0,t,s);e.push(ce(n,1,r))}}function dl(e){const t=[0];return ul(t,e.length-1),t}function hl(e,t){return e.map(n=>n*t)}function fl(e,t){return e.map(()=>t||mo).splice(0,e.length-1)}function Vt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=Pc(s)?s.map(Ir):Ir(s),o={done:!1,value:t[0]},i=hl(n&&n.length===t.length?n:dl(t),e),a=ll(i,t,{ease:Array.isArray(r)?r:fl(t,r)});return{calculatedDuration:e,next:c=>(o.value=a(c),o.done=c>=e,o)}}const ml=e=>e!==null;function sr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(ml),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const pl={decay:bs,inertia:bs,tween:Vt,keyframes:Vt,spring:Bn};function jo(e){typeof e.type=="string"&&(e.type=pl[e.type])}class rr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const gl=e=>e/100;class ir extends rr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ce.now()&&this.tick(Ce.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;jo(t);const{type:n=Vt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const c=n||Vt;process.env.NODE_ENV!=="production"&&c!==Vt&&Ye(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Vt&&typeof a[0]!="number"&&(this.mixKeyframes=gn(gl,Ao(a[0],a[1])),a=[0,100]);const u=c({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=nr(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:h,repeatType:f,repeatDelay:g,type:x,onUpdate:v,finalKeyframe:S}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const T=this.currentTime-u*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?T<0:T>r;this.currentTime=Math.max(T,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let y=this.currentTime,M=s;if(h){const E=Math.min(this.currentTime,r)/a;let X=Math.floor(E),L=E%1;!L&&E>=1&&(L=1),L===1&&X--,X=Math.min(X,h+1),!!(X%2)&&(f==="reverse"?(L=1-L,g&&(L-=g/a)):f==="mirror"&&(M=i)),y=Xe(0,1,L)*a}const k=b?{done:!1,value:l[0]}:M.next(y);o&&(k.value=o(k.value));let{done:C}=k;!b&&c!==null&&(C=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const A=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&C);return A&&x!==bs&&(k.value=sr(l,this.options,S,this.speed)),v&&v(k.value),A&&this.finish(),k}then(t,n){return this.finished.then(t,n)}get duration(){return De(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+De(t)}get time(){return De(this.currentTime)}set time(t){t=$e(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Ce.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=De(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Qc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ce.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function yl(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const At=e=>e*180/Math.PI,ws=e=>{const t=At(Math.atan2(e[1],e[0]));return Ts(t)},xl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:ws,rotateZ:ws,skewX:e=>At(Math.atan(e[1])),skewY:e=>At(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ts=e=>(e=e%360,e<0&&(e+=360),e),zr=ws,Ur=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),_r=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),vl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ur,scaleY:_r,scale:e=>(Ur(e)+_r(e))/2,rotateX:e=>Ts(At(Math.atan2(e[6],e[5]))),rotateY:e=>Ts(At(Math.atan2(-e[2],e[0]))),rotateZ:zr,rotate:zr,skewX:e=>At(Math.atan(e[4])),skewY:e=>At(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Ss(e){return e.includes("scale")?1:0}function As(e,t){if(!e||e==="none")return Ss(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=vl,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=xl,r=a}if(!r)return Ss(t);const o=s[t],i=r[1].split(",").map(wl);return typeof o=="function"?o(i):i[o]}const bl=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return As(n,t)};function wl(e){return parseFloat(e.trim())}const Kt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],qt=new Set(Kt),Wr=e=>e===Wt||e===B,Tl=new Set(["x","y","z"]),Sl=Kt.filter(e=>!Tl.has(e));function Al(e){const t=[];return Sl.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Pt={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>As(t,"x"),y:(e,{transform:t})=>As(t,"y")};Pt.translateX=Pt.x;Pt.translateY=Pt.y;const Ct=new Set;let Ps=!1,Cs=!1,js=!1;function ko(){if(Cs){const e=Array.from(Ct).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=Al(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Cs=!1,Ps=!1,Ct.forEach(e=>e.complete(js)),Ct.clear()}function Mo(){Ct.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Cs=!0)})}function Pl(){js=!0,Mo(),ko(),js=!1}class or{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Ct.add(this),Ps||(Ps=!0,oe.read(Mo),oe.resolveKeyframes(ko))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}yl(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Ct.delete(this)}cancel(){this.state==="scheduled"&&(Ct.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Cl=e=>e.startsWith("--");function jl(e,t,n){Cl(t)?e.style.setProperty(t,n):e.style[t]=n}const kl=qs(()=>window.ScrollTimeline!==void 0),Ml={};function El(e,t){const n=qs(e);return()=>Ml[t]??n()}const Eo=El(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),nn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,Kr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:nn([0,.65,.55,1]),circOut:nn([.55,0,1,.45]),backIn:nn([.31,.01,.66,-.59]),backOut:nn([.33,1.53,.69,.99])};function Do(e,t){if(e)return typeof e=="function"?Eo()?Po(e,t):"ease-out":po(e)?nn(e):Array.isArray(e)?e.map(n=>Do(n,t)||Kr.easeOut):Kr[e]}function Dl(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[t]:n};c&&(l.offset=c);const h=Do(a,r);Array.isArray(h)&&(l.easing=h);const f={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(f.pseudoElement=u),e.animate(l,f)}function No(e){return typeof e=="function"&&"applyToOptions"in e}function Nl({type:e,...t}){return No(e)&&Eo()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Rl extends rr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,Ye(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=Nl(t);this.animation=Dl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=sr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):jl(n,s,l),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return De(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+De(t)}get time(){return De(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=$e(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&kl()?(this.animation.timeline=t,Ne):n(this)}}const Ro={anticipate:uo,backInOut:lo,circInOut:fo};function Vl(e){return e in Ro}function Il(e){typeof e.ease=="string"&&Vl(e.ease)&&(e.ease=Ro[e.ease])}const qr=10;class Ol extends Rl{constructor(t){Il(t),jo(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new ir({...i,autoplay:!1}),c=$e(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-qr).value,a.sample(c).value,qr),a.stop()}}const Gr=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(dt.test(e)||e==="0")&&!e.startsWith("url("));function Ll(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function Fl(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=Gr(r,t),a=Gr(o,t);return _t(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Ll(e)||(n==="spring"||No(n))&&s}function ks(e){e.duration=0,e.type="keyframes"}const $l=new Set(["opacity","clipPath","filter","transform"]),Bl=qs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function zl(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=t.owner.getProps();return Bl()&&n&&$l.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Ul=40;class _l extends rr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ce.now();const f={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...h},g=l?.KeyframeResolver||or;this.keyframeResolver=new g(a,(x,v,S)=>this.onKeyframesResolved(x,v,f,!S),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=Ce.now(),Fl(t,o,i,a)||((Je.instantAnimations||!c)&&l?.(sr(t,s,n)),t[0]=t[t.length-1],ks(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Ul?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=!u&&zl(f)?new Ol({...f,element:f.motionValue.owner.current}):new ir(f);g.finished.then(()=>this.notifyFinished()).catch(Ne),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Pl()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Wl=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Kl(e){const t=Wl.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const ql=4;function Vo(e,t,n=1){Ye(n<=ql,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Kl(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return to(i)?parseFloat(i):i}return Zs(r)?Vo(r,t,n+1):r}function ar(e,t){return e?.[t]??e?.default??e}const Io=new Set(["width","height","top","left","right","bottom",...Kt]),Gl={test:e=>e==="auto",parse:e=>e},Oo=e=>t=>t.test(e),Lo=[Wt,B,Ke,lt,Lc,Oc,Gl],Hr=e=>Lo.find(Oo(e));function Hl(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||so(e):!0}const Xl=new Set(["brightness","contrast","saturate","opacity"]);function Yl(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Qs)||[];if(!s)return e;const r=n.replace(s,"");let o=Xl.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Jl=/\b([a-z-]*)\(.*?\)/gu,Ms={...dt,getAnimatableNone:e=>{const t=e.match(Jl);return t?t.map(Yl).join(" "):e}},Xr={...Wt,transform:Math.round},Zl={rotate:lt,rotateX:lt,rotateY:lt,rotateZ:lt,scale:jn,scaleX:jn,scaleY:jn,scaleZ:jn,skew:lt,skewX:lt,skewY:lt,distance:B,translateX:B,translateY:B,translateZ:B,x:B,y:B,z:B,perspective:B,transformPerspective:B,opacity:dn,originX:Or,originY:Or,originZ:B},cr={borderWidth:B,borderTopWidth:B,borderRightWidth:B,borderBottomWidth:B,borderLeftWidth:B,borderRadius:B,radius:B,borderTopLeftRadius:B,borderTopRightRadius:B,borderBottomRightRadius:B,borderBottomLeftRadius:B,width:B,maxWidth:B,height:B,maxHeight:B,top:B,right:B,bottom:B,left:B,padding:B,paddingTop:B,paddingRight:B,paddingBottom:B,paddingLeft:B,margin:B,marginTop:B,marginRight:B,marginBottom:B,marginLeft:B,backgroundPositionX:B,backgroundPositionY:B,...Zl,zIndex:Xr,fillOpacity:dn,strokeOpacity:dn,numOctaves:Xr},Ql={...cr,color:fe,backgroundColor:fe,outlineColor:fe,fill:fe,stroke:fe,borderColor:fe,borderTopColor:fe,borderRightColor:fe,borderBottomColor:fe,borderLeftColor:fe,filter:Ms,WebkitFilter:Ms},Fo=e=>Ql[e];function $o(e,t){let n=Fo(e);return n!==Ms&&(n=dt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const eu=new Set(["auto","none","0"]);function tu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!eu.has(o)&&hn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=$o(n,r)}class nu extends or{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),Zs(u))){const l=Vo(u,n.current);l!==void 0&&(t[c]=l),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Io.has(s)||t.length!==2)return;const[r,o]=t,i=Hr(r),a=Hr(o);if(i!==a)if(Wr(i)&&Wr(a))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else Pt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||Hl(t[r]))&&s.push(r);s.length&&tu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Pt[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Pt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{t.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function su(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const Bo=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function zo(e){return no(e)&&"offsetHeight"in e}const Yr=30,ru=e=>!isNaN(parseFloat(e));class iu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ce.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ce.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=ru(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Hs(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Gs);const s=this.events[t].add(n);return t==="change"?()=>{s(),oe.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Ce.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Yr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Yr);return ro(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function zt(e,t){return new iu(e,t)}const{schedule:lr}=go(queueMicrotask,!1),Le={x:!1,y:!1};function Uo(){return Le.x||Le.y}function ou(e){return e==="x"||e==="y"?Le[e]?null:(Le[e]=!0,()=>{Le[e]=!1}):Le.x||Le.y?null:(Le.x=Le.y=!0,()=>{Le.x=Le.y=!1})}function _o(e,t){const n=su(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Jr(e){return!(e.pointerType==="touch"||Uo())}function au(e,t,n={}){const[s,r,o]=_o(e,n),i=a=>{if(!Jr(a))return;const{target:c}=a,u=t(c,a);if(typeof u!="function"||!c)return;const l=h=>{Jr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Wo=(e,t)=>t?e===t?!0:Wo(e,t.parentElement):!1,ur=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,cu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function lu(e){return cu.has(e.tagName)||e.tabIndex!==-1}const Nn=new WeakSet;function Zr(e){return t=>{t.key==="Enter"&&e(t)}}function is(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const uu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Zr(()=>{if(Nn.has(n))return;is(n,"down");const r=Zr(()=>{is(n,"up")}),o=()=>is(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Qr(e){return ur(e)&&!Uo()}function du(e,t,n={}){const[s,r,o]=_o(e,n),i=a=>{const c=a.currentTarget;if(!Qr(a))return;Nn.add(c);const u=t(c,a),l=(g,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),Nn.has(c)&&Nn.delete(c),Qr(g)&&typeof u=="function"&&u(g,{success:x})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Wo(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),zo(a)&&(a.addEventListener("focus",u=>uu(u,r)),!lu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Ko(e){return no(e)&&"ownerSVGElement"in e}function hu(e){return Ko(e)&&e.tagName==="svg"}const Te=e=>!!(e&&e.getVelocity),fu=[...Lo,fe,dt],mu=e=>fu.find(Oo(e)),dr=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ei(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=ei(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():ei(e[r],null)}}}}function gu(...e){return Fe.useCallback(pu(...e),e)}class yu extends Fe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=zo(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 xu({children:e,isPresent:t,anchorX:n,root:s}){const r=m.useId(),o=m.useRef(null),i=m.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=m.useContext(dr),c=gu(o,e?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:h,left:f,right:g}=i.current;if(t||!o.current||!u||!l)return;const x=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const v=document.createElement("style");a&&(v.nonce=a);const S=s??document.head;return S.appendChild(v),v.sheet&&v.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
@@ -6,7 +6,7 @@
6
6
  ${x}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{S.contains(v)&&S.removeChild(v)}},[t]),d.jsx(yu,{isPresent:t,childRef:o,sizeRef:i,children:Fe.cloneElement(e,{ref:c})})}const vu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=Us(bu),l=m.useId();let h=!0,f=m.useMemo(()=>(h=!1,{id:l,initial:t,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const x of u.values())if(!x)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&h&&(f={...f}),m.useMemo(()=>{u.forEach((g,x)=>u.set(x,!1))},[n]),Fe.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=d.jsx(xu,{isPresent:n,anchorX:a,root:c,children:e})),d.jsx(_n.Provider,{value:f,children:e})};function bu(){return new Map}function qo(e=!0){const t=m.useContext(_n);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=m.useId();m.useEffect(()=>{if(e)return r(o)},[e]);const i=m.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const kn=e=>e.key||"";function ti(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const wu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=qo(i),h=m.useMemo(()=>ti(e),[e]),f=i&&!u?[]:h.map(kn),g=m.useRef(!0),x=m.useRef(h),v=Us(()=>new Map),[S,T]=m.useState(h),[b,y]=m.useState(h);eo(()=>{g.current=!1,x.current=h;for(let C=0;C<b.length;C++){const A=kn(b[C]);f.includes(A)?v.delete(A):v.get(A)!==!0&&v.set(A,!1)}},[b,f.length,f.join("-")]);const M=[];if(h!==S){let C=[...h];for(let A=0;A<b.length;A++){const E=b[A],X=kn(E);f.includes(X)||(C.splice(A,0,E),M.push(E))}return o==="wait"&&M.length&&(C=M),y(ti(C)),T(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&b.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:k}=m.useContext(zs);return d.jsx(d.Fragment,{children:b.map(C=>{const A=kn(C),E=i&&!u?!1:h===b||f.includes(A),X=()=>{if(v.has(A))v.set(A,!0);else return;let O=!0;v.forEach(se=>{se||(O=!1)}),O&&(k?.(),y(x.current),i&&l?.(),s&&s())};return d.jsx(vu,{isPresent:E,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:E?void 0:X,anchorX:a,children:C},A)})})},hr=m.createContext({strict:!1}),ni={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"]},Ut={};for(const e in ni)Ut[e]={isEnabled:t=>ni[e].some(n=>!!t[n])};function Es(e){for(const t in e)Ut[t]={...Ut[t],...e[t]}}function Tu({children:e,features:t,strict:n=!1}){const[,s]=m.useState(!os(t)),r=m.useRef(void 0);if(!os(t)){const{renderer:o,...i}=t;r.current=o,Es(i)}return m.useEffect(()=>{os(t)&&t().then(({renderer:o,...i})=>{Es(i),r.current=o,s(!0)})},[]),d.jsx(hr.Provider,{value:{renderer:r.current,strict:n},children:e})}function os(e){return typeof e=="function"}const Su=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 zn(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Su.has(e)}let Go=e=>!zn(e);function Au(e){typeof e=="function"&&(Go=t=>t.startsWith("on")?!zn(t):e(t))}try{Au(require("@emotion/is-prop-valid").default)}catch{}function Pu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Go(r)||n===!0&&zn(r)||!t&&!zn(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Wn=m.createContext({});function Kn(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function fn(e){return typeof e=="string"||Array.isArray(e)}const fr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],mr=["initial",...fr];function qn(e){return Kn(e.animate)||mr.some(t=>fn(e[t]))}function Ho(e){return!!(qn(e)||e.variants)}function Cu(e,t){if(qn(e)){const{initial:n,animate:s}=e;return{initial:n===!1||fn(n)?n:void 0,animate:fn(s)?s:void 0}}return e.inherit!==!1?t:{}}function ju(e){const{initial:t,animate:n}=Cu(e,m.useContext(Wn));return m.useMemo(()=>({initial:t,animate:n}),[si(t),si(n)])}function si(e){return Array.isArray(e)?e.join(" "):e}const mn={};function ku(e){for(const t in e)mn[t]=e[t],Js(t)&&(mn[t].isCSSVariable=!0)}function Xo(e,{layout:t,layoutId:n}){return qt.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!mn[e]||e==="opacity")}const Mu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Eu=Kt.length;function Du(e,t,n){let s="",r=!0;for(let o=0;o<Eu;o++){const i=Kt[o],a=e[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=Bo(a,cr[i]);if(!c){r=!1;const l=Mu[i]||i;s+=`${l}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function pr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const c in t){const u=t[c];if(qt.has(c)){i=!0;continue}else if(Js(c)){r[c]=u;continue}else{const l=Bo(u,cr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(t.transform||(i||n?s.transform=Du(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:l=0}=o;s.transformOrigin=`${c} ${u} ${l}`}}const gr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Yo(e,t,n){for(const s in t)!Te(t[s])&&!Xo(s,n)&&(e[s]=t[s])}function Nu({transformTemplate:e},t){return m.useMemo(()=>{const n=gr();return pr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ru(e,t){const n=e.style||{},s={};return Yo(s,n,e),Object.assign(s,Nu(e,t)),s}function Vu(e,t){const n={},s=Ru(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Iu={offset:"stroke-dashoffset",array:"stroke-dasharray"},Ou={offset:"strokeDashoffset",array:"strokeDasharray"};function Lu(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?Iu:Ou;e[o.offset]=B.transform(-s);const i=B.transform(t),a=B.transform(n);e[o.array]=`${i} ${a}`}function Jo(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(pr(e,a,u),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:f}=e;h.transform&&(f.transform=h.transform,delete h.transform),(f.transform||h.transformOrigin)&&(f.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Lu(h,r,o,i,!1)}const Zo=()=>({...gr(),attrs:{}}),Qo=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Fu(e,t,n,s){const r=m.useMemo(()=>{const o=Zo();return Jo(o,t,Qo(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Yo(o,e.style,e),r.style={...o,...r.style}}return r}const $u=["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 yr(e){return typeof e!="string"||e.includes("-")?!1:!!($u.indexOf(e)>-1||/[A-Z]/u.test(e))}function Bu(e,t,n,{latestValues:s},r,o=!1){const a=(yr(e)?Fu:Vu)(t,s,r,e),c=Pu(t,typeof e=="string",o),u=e!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=t,h=m.useMemo(()=>Te(l)?l.get():l,[l]);return m.createElement(e,{...u,children:h})}function ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function xr(e,t,n,s){if(typeof t=="function"){const[r,o]=ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function Rn(e){return Te(e)?e.get():e}function zu({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Uu(n,s,r,e),renderState:t()}}function Uu(e,t,n,s){const r={},o=s(e,{});for(const f in o)r[f]=Rn(o[f]);let{initial:i,animate:a}=e;const c=qn(e),u=Ho(e);t&&u&&!c&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const h=l?a:i;if(h&&typeof h!="boolean"&&!Kn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const x=xr(e,f[g]);if(x){const{transitionEnd:v,transition:S,...T}=x;for(const b in T){let y=T[b];if(Array.isArray(y)){const M=l?y.length-1:0;y=y[M]}y!==null&&(r[b]=y)}for(const b in v)r[b]=v[b]}}}return r}const ea=e=>(t,n)=>{const s=m.useContext(Wn),r=m.useContext(_n),o=()=>zu(e,t,s,r);return n?o():Us(o)};function vr(e,t,n){const{style:s}=e,r={};for(const o in s)(Te(s[o])||t.style&&Te(t.style[o])||Xo(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const _u=ea({scrapeMotionValuesFromProps:vr,createRenderState:gr});function ta(e,t,n){const s=vr(e,t,n);for(const r in e)if(Te(e[r])||Te(t[r])){const o=Kt.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Wu=ea({scrapeMotionValuesFromProps:ta,createRenderState:Zo}),Ku=Symbol.for("motionComponentSymbol");function It(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function qu(e,t,n){return m.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):It(n)&&(n.current=s))},[t])}const br=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Gu="framerAppearId",na="data-"+br(Gu),sa=m.createContext({});function Hu(e,t,n,s,r){const{visualElement:o}=m.useContext(Wn),i=m.useContext(hr),a=m.useContext(_n),c=m.useContext(dr).reducedMotion,u=m.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const l=u.current,h=m.useContext(sa);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Xu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[na],x=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return eo(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),x.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!x.current&&l.animationState&&l.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),x.current=!1),l.enteringChildren=void 0)}),l}function Xu(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ra(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&It(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function ra(e){if(e)return e.options.allowProjection!==!1?e.projection:ra(e.parent)}function Vn(e,{forwardMotionProps:t=!1}={},n,s){n&&Es(n);const r=yr(e)?Wu:_u;function o(a,c){let u;const l={...m.useContext(dr),...a,layoutId:Yu(a)},{isStatic:h}=l,f=ju(a),g=r(a,h);if(!h&&_s){Ju(l,n);const x=Zu(l);u=x.MeasureLayout,f.visualElement=Hu(e,g,l,s,x.ProjectionNode)}return d.jsxs(Wn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Bu(e,a,qu(g,f.visualElement,c),g,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=m.forwardRef(o);return i[Ku]=e,i}function Yu({layoutId:e}){const t=m.useContext(zs).id;return t&&e!==void 0?t+"-"+e:e}function Ju(e,t){const n=m.useContext(hr).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?_t(!1,s,"lazy-strict-mode"):Ye(!1,s,"lazy-strict-mode")}}function Zu(e){const{drag:t,layout:n}=Ut;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Qu(e,t){if(typeof Proxy>"u")return Vn;const n=new Map,s=(o,i)=>Vn(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Hs(!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,Vn(i,void 0,e,t)),n.get(i))})}function ia({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function ed({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function td(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function as(e){return e===void 0||e===1}function Ds({scale:e,scaleX:t,scaleY:n}){return!as(e)||!as(t)||!as(n)}function Tt(e){return Ds(e)||oa(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function oa(e){return ii(e.x)||ii(e.y)}function ii(e){return e&&e!=="0%"}function Un(e,t,n){const s=e-n,r=t*s;return n+r}function oi(e,t,n,s,r){return r!==void 0&&(e=Un(e,r,s)),Un(e,n,s)+t}function Ns(e,t=0,n=1,s,r){e.min=oi(e.min,t,n,s,r),e.max=oi(e.max,t,n,s,r)}function aa(e,{x:t,y:n}){Ns(e.x,t.translate,t.scale,t.originPoint),Ns(e.y,n.translate,n.scale,n.originPoint)}const ai=.999999999999,ci=1.0000000000001;function nd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Lt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,aa(e,i)),s&&Tt(o.latestValues)&&Lt(e,o.latestValues))}t.x<ci&&t.x>ai&&(t.x=1),t.y<ci&&t.y>ai&&(t.y=1)}function Ot(e,t){e.min=e.min+t,e.max=e.max+t}function li(e,t,n,s,r=.5){const o=ce(e.min,e.max,r);Ns(e,t,n,o,s)}function Lt(e,t){li(e.x,t.x,t.scaleX,t.scale,t.originX),li(e.y,t.y,t.scaleY,t.scale,t.originY)}function ca(e,t){return ia(td(e.getBoundingClientRect(),t))}function sd(e,t,n){const s=ca(e,n),{scroll:r}=t;return r&&(Ot(s.x,r.offset.x),Ot(s.y,r.offset.y)),s}const ui=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ft=()=>({x:ui(),y:ui()}),di=()=>({min:0,max:0}),he=()=>({x:di(),y:di()}),Rs={current:null},la={current:!1};function rd(){if(la.current=!0,!!_s)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Rs.current=e.matches;e.addEventListener("change",t),t()}else Rs.current=!1}const id=new WeakMap;function od(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Te(r))e.addValue(s,r);else if(Te(o))e.addValue(s,zt(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,zt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const hi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class ad{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=or,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=Ce.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,oe.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=qn(n),this.isVariantNode=Ho(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:l,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const g=h[f];c[f]!==void 0&&Te(g)&&g.set(c[f])}}mount(t){this.current=t,id.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),la.current||rd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Rs.current,process.env.NODE_ENV!=="production"&&Hs(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(),ut(this.notifyUpdate),ut(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=qt.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&oe.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Ut){const n=Ut[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):he()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<hi.length;s++){const r=hi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=od(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=zt(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(to(s)||so(s))?s=parseFloat(s):!mu(s)&&dt.test(n)&&(s=$o(t,n)),this.setBaseTarget(t,Te(s)?s.get():s)),Te(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=xr(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Te(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Gs),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){lr.render(this.render)}}class ua extends ad{constructor(){super(...arguments),this.KeyframeResolver=nu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Te(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function da(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function cd(e){return window.getComputedStyle(e)}class ld extends ua{constructor(){super(...arguments),this.type="html",this.renderInstance=da}readValueFromInstance(t,n){if(qt.has(n))return this.projection?.isProjecting?Ss(n):bl(t,n);{const s=cd(t),r=(Js(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return ca(t,n)}build(t,n,s){pr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return vr(t,n,s)}}const ha=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 ud(e,t,n,s){da(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(ha.has(r)?r:br(r),t.attrs[r])}class dd extends ua{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=he}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(qt.has(n)){const s=Fo(n);return s&&s.default||0}return n=ha.has(n)?n:br(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return ta(t,n,s)}build(t,n,s){Jo(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){ud(t,n,s,r)}mount(t){this.isSVGTag=Qo(t.tagName),super.mount(t)}}const fa=(e,t)=>yr(e)?new dd(t):new ld(t,{allowProjection:e!==m.Fragment});function Bt(e,t,n){const s=e.getProps();return xr(s,t,n!==void 0?n:s.custom,e)}const Vs=e=>Array.isArray(e);function hd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,zt(n))}function fd(e){return Vs(e)?e[e.length-1]||0:e}function md(e,t){const n=Bt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=fd(o[i]);hd(e,i,a)}}function pd(e){return!!(Te(e)&&e.add)}function Is(e,t){const n=e.getValue("willChange");if(pd(n))return n.add(t);if(!n&&Je.WillChange){const s=new Je.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function ma(e){return e.props[na]}const gd=e=>e!==null;function yd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(gd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const xd={type:"spring",stiffness:500,damping:25,restSpeed:10},vd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),bd={type:"keyframes",duration:.8},wd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Td=(e,{keyframes:t})=>t.length>2?bd:qt.has(e)?e.startsWith("scale")?vd(t[1]):xd:wd;function Sd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const wr=(e,t,n,s={},r,o)=>i=>{const a=ar(s,e)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-$e(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:f=>{t.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};Sd(a)||Object.assign(l,Td(e,l)),l.duration&&(l.duration=$e(l.duration)),l.repeatDelay&&(l.repeatDelay=$e(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(ks(l),l.delay===0&&(h=!0)),(Je.instantAnimations||Je.skipAnimations)&&(h=!0,ks(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const f=yd(l.keyframes,a);if(f!==void 0){oe.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new ir(l):new _l(l)};function Ad({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function pa(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const c=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const l in a){const h=e.getValue(l,e.latestValues[l]??null),f=a[l];if(f===void 0||u&&Ad(u,l))continue;const g={delay:n,...ar(o||{},l)},x=h.get();if(x!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===x&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const T=ma(e);if(T){const b=window.MotionHandoffAnimation(T,l,oe);b!==null&&(g.startTime=b,v=!0)}}Is(e,l),h.start(wr(l,h,f,e.shouldReduceMotion&&Io.has(l)?{type:!1}:g,e,v));const S=h.animation;S&&c.push(S)}return i&&Promise.all(c).then(()=>{oe.update(()=>{i&&md(e,i)})}),c}function ga(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,l)=>u.sortNodePosition(l)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Os(e,t,n={}){const s=Bt(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(pa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return Pd(e,t,c,u,l,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,u]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Pd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(Os(c,t,{...i,delay:n+(typeof s=="function"?0:s)+ga(e.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function Cd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>Os(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=Os(e,t,n);else{const r=typeof t=="function"?Bt(e,t,n.custom):t;s=Promise.all(pa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function ya(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const jd=mr.length;function xa(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?xa(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<jd;n++){const s=mr[n],r=e.props[s];(fn(r)||r===!1)&&(t[s]=r)}return t}const kd=[...fr].reverse(),Md=fr.length;function Ed(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Cd(e,n,s)))}function Dd(e){let t=Ed(e),n=fi(),s=!0;const r=c=>(u,l)=>{const h=Bt(e,l,c==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...x}=h;u={...u,...x,...g}}return u};function o(c){t=c(e)}function i(c){const{props:u}=e,l=xa(e.parent)||{},h=[],f=new Set;let g={},x=1/0;for(let S=0;S<Md;S++){const T=kd[S],b=n[T],y=u[T]!==void 0?u[T]:l[T],M=fn(y),k=T===c?b.isActive:null;k===!1&&(x=S);let C=y===l[T]&&y!==u[T]&&M;if(C&&s&&e.manuallyAnimateOnMount&&(C=!1),b.protectedKeys={...g},!b.isActive&&k===null||!y&&!b.prevProp||Kn(y)||typeof y=="boolean")continue;const A=Nd(b.prevProp,y);let E=A||T===c&&b.isActive&&!C&&M||S>x&&M,X=!1;const O=Array.isArray(y)?y:[y];let se=O.reduce(r(T),{});k===!1&&(se={});const{prevResolvedValues:ie={}}=b,ge={...ie,...se},Z=Q=>{E=!0,f.has(Q)&&(X=!0,f.delete(Q)),b.needsAnimating[Q]=!0;const de=e.getValue(Q);de&&(de.liveStyle=!1)};for(const Q in ge){const de=se[Q],le=ie[Q];if(g.hasOwnProperty(Q))continue;let ee=!1;Vs(de)&&Vs(le)?ee=!ya(de,le):ee=de!==le,ee?de!=null?Z(Q):f.add(Q):de!==void 0&&f.has(Q)?Z(Q):b.protectedKeys[Q]=!0}b.prevProp=y,b.prevResolvedValues=se,b.isActive&&(g={...g,...se}),s&&e.blockInitialAnimation&&(E=!1);const re=C&&A;E&&(!re||X)&&h.push(...O.map(Q=>{const de={type:T};if(typeof Q=="string"&&s&&!re&&e.manuallyAnimateOnMount&&e.parent){const{parent:le}=e,ee=Bt(le,Q);if(le.enteringChildren&&ee){const{delayChildren:Ze}=ee.transition||{};de.delay=ga(le.enteringChildren,e,Ze)}}return{animation:Q,options:de}}))}if(f.size){const S={};if(typeof u.initial!="boolean"){const T=Bt(e,Array.isArray(u.initial)?u.initial[0]:u.initial);T&&T.transition&&(S.transition=T.transition)}f.forEach(T=>{const b=e.getBaseTarget(T),y=e.getValue(T);y&&(y.liveStyle=!0),S[T]=b??null}),h.push({animation:S})}let v=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,v?t(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const h in n)n[h].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=fi()}}}function Nd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!ya(t,e):!1}function bt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fi(){return{animate:bt(!0),whileInView:bt(),whileHover:bt(),whileTap:bt(),whileDrag:bt(),whileFocus:bt(),exit:bt()}}class ht{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Rd extends ht{constructor(t){super(t),t.animationState||(t.animationState=Dd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Kn(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Vd=0;class Id extends ht{constructor(){super(...arguments),this.id=Vd++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const va={animation:{Feature:Rd},exit:{Feature:Id}};function pn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function vn(e){return{point:{x:e.pageX,y:e.pageY}}}const Od=e=>t=>ur(t)&&e(t,vn(t));function rn(e,t,n,s){return pn(e,t,Od(n),s)}const ba=1e-4,Ld=1-ba,Fd=1+ba,wa=.01,$d=0-wa,Bd=0+wa;function Se(e){return e.max-e.min}function zd(e,t,n){return Math.abs(e-t)<=n}function mi(e,t,n,s=.5){e.origin=s,e.originPoint=ce(t.min,t.max,e.origin),e.scale=Se(n)/Se(t),e.translate=ce(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Ld&&e.scale<=Fd||isNaN(e.scale))&&(e.scale=1),(e.translate>=$d&&e.translate<=Bd||isNaN(e.translate))&&(e.translate=0)}function on(e,t,n,s){mi(e.x,t.x,n.x,s?s.originX:void 0),mi(e.y,t.y,n.y,s?s.originY:void 0)}function pi(e,t,n){e.min=n.min+t.min,e.max=e.min+Se(t)}function Ud(e,t,n){pi(e.x,t.x,n.x),pi(e.y,t.y,n.y)}function gi(e,t,n){e.min=t.min-n.min,e.max=e.min+Se(t)}function an(e,t,n){gi(e.x,t.x,n.x),gi(e.y,t.y,n.y)}function Ee(e){return[e("x"),e("y")]}const Ta=({current:e})=>e?e.ownerDocument.defaultView:null,yi=(e,t)=>Math.abs(e-t);function _d(e,t){const n=yi(e.x,t.x),s=yi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Sa{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=ls(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,x=_d(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!x)return;const{point:v}=f,{timestamp:S}=ve;this.history.push({...v,timestamp:S});const{onStart:T,onMove:b}=this.handlers;g||(T&&T(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),b&&b(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=cs(g,this.transformPagePoint),oe.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:x,onSessionEnd:v,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const T=ls(f.type==="pointercancel"?this.lastMoveEventInfo:cs(g,this.transformPagePoint),this.history);this.startEvent&&x&&x(f,T),v&&v(f,T)},!ur(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=vn(t),c=cs(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=ve;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(t,ls(c,this.history)),this.removeListeners=gn(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),ut(this.updatePoint)}}function cs(e,t){return t?{point:t(e.point)}:e}function xi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ls({point:e},t){return{point:e,delta:xi(e,Aa(t)),offset:xi(e,Wd(t)),velocity:Kd(t,.1)}}function Wd(e){return e[0]}function Aa(e){return e[e.length-1]}function Kd(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Aa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>$e(t)));)n--;if(!s)return{x:0,y:0};const o=De(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 qd(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?ce(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?ce(n,e,s.max):Math.min(e,n)),e}function vi(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Gd(e,{top:t,left:n,bottom:s,right:r}){return{x:vi(e.x,n,r),y:vi(e.y,t,s)}}function bi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Hd(e,t){return{x:bi(e.x,t.x),y:bi(e.y,t.y)}}function Xd(e,t){let n=.5;const s=Se(e),r=Se(t);return r>s?n=un(t.min,t.max-s,e.min):s>r&&(n=un(e.min,e.max-r,t.min)),Xe(0,1,n)}function Yd(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Ls=.35;function Jd(e=Ls){return e===!1?e=0:e===!0&&(e=Ls),{x:wi(e,"left","right"),y:wi(e,"top","bottom")}}function wi(e,t,n){return{min:Ti(e,t),max:Ti(e,n)}}function Ti(e,t){return typeof e=="number"?e:e[t]||0}const Zd=new WeakMap;class Qd{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=he(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:x,onDragStart:v}=this.getProps();if(g&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ou(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ee(T=>{let b=this.getAxisMotionValue(T).get()||0;if(Ke.test(b)){const{projection:y}=this.visualElement;if(y&&y.layout){const M=y.layout.layoutBox[T];M&&(b=Se(M)*(parseFloat(b)/100))}}this.originPoint[T]=b}),v&&oe.postRender(()=>v(h,f)),Is(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:x,onDirectionLock:v,onDrag:S}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:T}=f;if(x&&this.currentDirection===null){this.currentDirection=eh(T),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,T),this.updateAxis("y",f.point,T),this.visualElement.render(),S&&S(h,f)},c=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f,this.stop(h,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Ee(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new Sa(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:Ta(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&oe.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!Mn(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=qd(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&It(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Gd(s.layoutBox,t):this.constraints=!1,this.elastic=Jd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ee(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Yd(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!It(t))return!1;const s=t.current;Ye(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=sd(s,r.root,this.visualElement.getTransformPagePoint());let i=Hd(r.layout.layoutBox,o);if(n){const a=n(ed(i));this.hasMutatedConstraints=!!a,a&&(i=ia(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Ee(l=>{if(!Mn(l,n,this.currentDirection))return;let h=c&&c[l]||{};i&&(h={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,x={type:"inertia",velocity:s?t[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,x)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Is(this.visualElement,t),s.start(wr(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ee(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ee(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Ee(n=>{const{drag:s}=this.getProps();if(!Mn(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-ce(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!It(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ee(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Xd({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(),Ee(i=>{if(!Mn(i,t,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(ce(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Zd.set(this.visualElement,this);const t=this.visualElement.current,n=rn(t,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();It(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()),oe.read(s);const i=pn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ee(l=>{const h=this.getAxisMotionValue(l);h&&(this.originPoint[l]+=c[l].translate,h.set(h.get()+c[l].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=Ls,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Mn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function eh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class th extends ht{constructor(t){super(t),this.removeGroupControls=Ne,this.removeListeners=Ne,this.controls=new Qd(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ne}unmount(){this.removeGroupControls(),this.removeListeners()}}const Si=e=>(t,n)=>{e&&oe.postRender(()=>e(t,n))};class nh extends ht{constructor(){super(...arguments),this.removePointerDownListener=Ne}onPointerDown(t){this.session=new Sa(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ta(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Si(t),onStart:Si(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&oe.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=rn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const In={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ai(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const tn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(B.test(e))e=parseFloat(e);else return e;const n=Ai(e,t.target.x),s=Ai(e,t.target.y);return`${n}% ${s}%`}},sh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=dt.parse(e);if(r.length>5)return s;const o=dt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=c;const u=ce(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 us=!1;class rh extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;ku(ih),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),us&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),In.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,us=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||oe.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),lr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;us=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Pa(e){const[t,n]=qo(),s=m.useContext(zs);return d.jsx(rh,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(sa),isPresent:t,safeToRemove:n})}const ih={borderRadius:{...tn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:tn,borderTopRightRadius:tn,borderBottomLeftRadius:tn,borderBottomRightRadius:tn,boxShadow:sh};function oh(e,t,n){const s=Te(e)?e:zt(e);return s.start(wr("",s,t,n)),s.animation}const ah=(e,t)=>e.depth-t.depth;class ch{constructor(){this.children=[],this.isDirty=!1}add(t){Ws(this.children,t),this.isDirty=!0}remove(t){Ks(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(ah),this.isDirty=!1,this.children.forEach(t)}}function lh(e,t){const n=Ce.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(ut(s),e(o-t))};return oe.setup(s,!0),()=>ut(s)}const Ca=["TopLeft","TopRight","BottomLeft","BottomRight"],uh=Ca.length,Pi=e=>typeof e=="string"?parseFloat(e):e,Ci=e=>typeof e=="number"||B.test(e);function dh(e,t,n,s,r,o){r?(e.opacity=ce(0,n.opacity??1,hh(s)),e.opacityExit=ce(t.opacity??1,0,fh(s))):o&&(e.opacity=ce(t.opacity??1,n.opacity??1,s));for(let i=0;i<uh;i++){const a=`border${Ca[i]}Radius`;let c=ji(t,a),u=ji(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||Ci(c)===Ci(u)?(e[a]=Math.max(ce(Pi(c),Pi(u),s),0),(Ke.test(u)||Ke.test(c))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=ce(t.rotate||0,n.rotate||0,s))}function ji(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const hh=ja(0,.5,ho),fh=ja(.5,.95,Ne);function ja(e,t,n){return s=>s<e?0:s>t?1:n(un(e,t,s))}function ki(e,t){e.min=t.min,e.max=t.max}function Me(e,t){ki(e.x,t.x),ki(e.y,t.y)}function Mi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Ei(e,t,n,s,r){return e-=t,e=Un(e,1/n,s),r!==void 0&&(e=Un(e,1/r,s)),e}function mh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Ke.test(t)&&(t=parseFloat(t),t=ce(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=ce(o.min,o.max,s);e===o&&(a-=t),e.min=Ei(e.min,t,n,a,r),e.max=Ei(e.max,t,n,a,r)}function Di(e,t,[n,s,r],o,i){mh(e,t[n],t[s],t[r],t.scale,o,i)}const ph=["x","scaleX","originX"],gh=["y","scaleY","originY"];function Ni(e,t,n,s){Di(e.x,t,ph,n?n.x:void 0,s?s.x:void 0),Di(e.y,t,gh,n?n.y:void 0,s?s.y:void 0)}function Ri(e){return e.translate===0&&e.scale===1}function ka(e){return Ri(e.x)&&Ri(e.y)}function Vi(e,t){return e.min===t.min&&e.max===t.max}function yh(e,t){return Vi(e.x,t.x)&&Vi(e.y,t.y)}function Ii(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Ma(e,t){return Ii(e.x,t.x)&&Ii(e.y,t.y)}function Oi(e){return Se(e.x)/Se(e.y)}function Li(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class xh{constructor(){this.members=[]}add(t){Ws(this.members,t),t.scheduleRender()}remove(t){if(Ks(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function vh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:l,rotateX:h,rotateY:f,skewX:g,skewY:x}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),h&&(s+=`rotateX(${h}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),x&&(s+=`skewY(${x}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const ds=["","X","Y","Z"],bh=1e3;let wh=0;function hs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Ea(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=ma(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",oe,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Ea(s)}function Da({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=wh++,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(Ah),this.nodes.forEach(kh),this.nodes.forEach(Mh),this.nodes.forEach(Ph)},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 ch)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Gs),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=Ko(i)&&!hu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let l,h=0;const f=()=>this.root.updateBlockedByResize=!1;oe.read(()=>{h=window.innerWidth}),e(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=lh(f,250),In.hasAnimatedSinceResize&&(In.hasAnimatedSinceResize=!1,this.nodes.forEach(Bi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:h,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const x=this.options.transition||u.getDefaultTransition()||Vh,{onLayoutAnimationStart:v,onLayoutAnimationComplete:S}=u.getProps(),T=!this.targetLayout||!Ma(this.targetLayout,g),b=!h&&f;if(this.options.layoutRoot||this.resumeFrom||b||h&&(T||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const y={...ar(x,"layout"),onPlay:v,onComplete:S};(u.shouldReduceMotion||this.options.layoutRoot)&&(y.delay=0,y.type=!1),this.startAnimation(y),this.setAnimationOrigin(l,b)}else h||Bi(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(),ut(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(Eh),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&&Ea(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const h=this.path[l];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Fi);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach($i);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(jh),this.nodes.forEach(Th),this.nodes.forEach(Sh)):this.nodes.forEach($i),this.clearAllSnapshots();const a=Ce.now();ve.delta=Xe(0,1e3/60,a-ve.timestamp),ve.timestamp=a,ve.isProcessing=!0,es.update.process(ve),es.preRender.process(ve),es.render.process(ve),ve.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,lr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ch),this.sharedNodes.forEach(Dh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,oe.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){oe.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Se(this.snapshot.measuredBox.x)&&!Se(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=he(),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&&!ka(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Tt(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)),Ih(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return he();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Oh))){const{scroll:u}=this.root;u&&(Ot(a.x,u.offset.x),Ot(a.y,u.offset.y))}return a}removeElementScroll(i){const a=he();if(Me(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:h}=u;u!==this.root&&l&&h.layoutScroll&&(l.wasRoot&&Me(a,i),Ot(a.x,l.offset.x),Ot(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=he();Me(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&&Lt(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),Tt(l.latestValues)&&Lt(c,l.latestValues)}return Tt(this.latestValues)&&Lt(c,this.latestValues),c}removeTransform(i){const a=he();Me(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Tt(u.latestValues))continue;Ds(u.latestValues)&&u.updateSnapshot();const l=he(),h=u.measurePageBox();Me(l,h),Ni(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return Tt(this.latestValues)&&Ni(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!==ve.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:l,layoutId:h}=this.options;if(!(!this.layout||!(l||h))){if(this.resolvedRelativeTargetAt=ve.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=he(),this.relativeTargetOrigin=he(),an(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Me(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=he(),this.targetWithTransforms=he()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Ud(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Me(this.target,this.layout.layoutBox),aa(this.target,this.targetDelta)):Me(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=he(),this.relativeTargetOrigin=he(),an(this.relativeTargetOrigin,this.target,f.target),Me(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ds(this.parent.latestValues)||oa(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===ve.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;Me(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;nd(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=he());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Mi(this.prevProjectionDelta.x,this.projectionDelta.x),Mi(this.prevProjectionDelta.y,this.projectionDelta.y)),on(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Li(this.projectionDelta.x,this.prevProjectionDelta.x)||!Li(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=Ft(),this.projectionDelta=Ft(),this.projectionDeltaWithTransform=Ft()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=Ft();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=he(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,v=g!==x,S=this.getStack(),T=!S||S.members.length<=1,b=!!(v&&!T&&this.options.crossfade===!0&&!this.path.some(Rh));this.animationProgress=0;let y;this.mixTargetDelta=M=>{const k=M/1e3;zi(h.x,i.x,k),zi(h.y,i.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(an(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Nh(this.relativeTarget,this.relativeTargetOrigin,f,k),y&&yh(this.relativeTarget,y)&&(this.isProjectionDirty=!1),y||(y=he()),Me(y,this.relativeTarget)),v&&(this.animationValues=l,dh(l,u,this.latestValues,k,b,T)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ut(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=oe.update(()=>{In.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=zt(0)),this.currentAnimation=oh(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(bh),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&&Na(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||he();const h=Se(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=Se(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Me(a,c),Lt(a,l),on(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new xh),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&&hs("z",i,u,this.animationValues);for(let l=0;l<ds.length;l++)hs(`rotate${ds[l]}`,i,u,this.animationValues),hs(`skew${ds[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=Rn(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=Rn(a?.pointerEvents)||""),this.hasProjected&&!Tt(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=vh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(h=c(l,h)),i.transform=h;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?l.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:l.opacityExit:i.opacity=u===this?l.opacity!==void 0?l.opacity:"":l.opacityExit!==void 0?l.opacityExit:0;for(const x in mn){if(l[x]===void 0)continue;const{correct:v,applyTo:S,isCSSVariable:T}=mn[x],b=h==="none"?l[x]:v(l[x],u);if(S){const y=S.length;for(let M=0;M<y;M++)i[S[M]]=b}else T?this.options.visualElement.renderState.vars[x]=b:i[x]=b}this.options.layoutId&&(i.pointerEvents=u===this?Rn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Fi),this.root.sharedNodes.clear()}}}function Th(e){e.updateLayout()}function Sh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Ee(l=>{const h=o?t.measuredBox[l]:t.layoutBox[l],f=Se(h);h.min=n[l].min,h.max=h.min+f}):Na(r,t.layoutBox,n)&&Ee(l=>{const h=o?t.measuredBox[l]:t.layoutBox[l],f=Se(n[l]);h.max=h.min+f,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[l].max=e.relativeTarget[l].min+f)});const i=Ft();on(i,n,t.layoutBox);const a=Ft();o?on(a,e.applyTransform(s,!0),t.measuredBox):on(a,n,t.layoutBox);const c=!ka(i);let u=!1;if(!e.resumeFrom){const l=e.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:h,layout:f}=l;if(h&&f){const g=he();an(g,t.layoutBox,h.layoutBox);const x=he();an(x,n,f.layoutBox),Ma(g,x)||(u=!0),l.options.layoutRoot&&(e.relativeTarget=x,e.relativeTargetOrigin=g,e.relativeParent=l)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Ah(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Ph(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Ch(e){e.clearSnapshot()}function Fi(e){e.clearMeasurements()}function $i(e){e.isLayoutDirty=!1}function jh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Bi(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function kh(e){e.resolveTargetDelta()}function Mh(e){e.calcProjection()}function Eh(e){e.resetSkewAndRotation()}function Dh(e){e.removeLeadSnapshot()}function zi(e,t,n){e.translate=ce(t.translate,0,n),e.scale=ce(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Ui(e,t,n,s){e.min=ce(t.min,n.min,s),e.max=ce(t.max,n.max,s)}function Nh(e,t,n,s){Ui(e.x,t.x,n.x,s),Ui(e.y,t.y,n.y,s)}function Rh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const Vh={duration:.45,ease:[.4,0,.1,1]},_i=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Wi=_i("applewebkit/")&&!_i("chrome/")?Math.round:Ne;function Ki(e){e.min=Wi(e.min),e.max=Wi(e.max)}function Ih(e){Ki(e.x),Ki(e.y)}function Na(e,t,n){return e==="position"||e==="preserve-aspect"&&!zd(Oi(t),Oi(n),.2)}function Oh(e){return e!==e.root&&e.scroll?.wasRoot}const Lh=Da({attachResizeListener:(e,t)=>pn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),fs={current:void 0},Ra=Da({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!fs.current){const e=new Lh({});e.mount(window),e.setOptions({layoutScroll:!0}),fs.current=e}return fs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Fh={pan:{Feature:nh},drag:{Feature:th,ProjectionNode:Ra,MeasureLayout:Pa}};function qi(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&oe.postRender(()=>o(t,vn(t)))}class $h extends ht{mount(){const{current:t}=this.node;t&&(this.unmount=au(t,(n,s)=>(qi(this.node,s,"Start"),r=>qi(this.node,r,"End"))))}unmount(){}}class Bh extends ht{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=gn(pn(this.node.current,"focus",()=>this.onFocus()),pn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Gi(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&oe.postRender(()=>o(t,vn(t)))}class zh extends ht{mount(){const{current:t}=this.node;t&&(this.unmount=du(t,(n,s)=>(Gi(this.node,s,"Start"),(r,{success:o})=>Gi(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Fs=new WeakMap,ms=new WeakMap,Uh=e=>{const t=Fs.get(e.target);t&&t(e)},_h=e=>{e.forEach(Uh)};function Wh({root:e,...t}){const n=e||document;ms.has(n)||ms.set(n,{});const s=ms.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(_h,{root:e,...t})),s[r]}function Kh(e,t,n){const s=Wh(t);return Fs.set(e,n),s.observe(e),()=>{Fs.delete(e),s.unobserve(e)}}const qh={some:0,all:1};class Gh extends ht{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:qh[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:l,onViewportLeave:h}=this.node.getProps(),f=u?l:h;f&&f(c)};return Kh(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Hh(t,n))&&this.startObserver()}unmount(){}}function Hh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Va={inView:{Feature:Gh},tap:{Feature:zh},focus:{Feature:Bh},hover:{Feature:$h}},Xh={layout:{ProjectionNode:Ra,MeasureLayout:Pa}},Yh={...va,...Va,...Fh,...Xh},Jh=Qu(Yh,fa),Zh={renderer:fa,...va,...Va};function Ia(e,t){return Vn(e,t)}const En=Ia("div"),Qh=Ia("p"),We=Symbol.for("@arcteninc/core:originalName");function ef(e,t){return e[We]=t,e}function tf(e,t,n,s){if(typeof e!="function")return null;const r=e[We];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[We]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[We]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(c=>!n.has(c.name)),i)return e[We]=i.name,{fn:e,meta:i};return null}function Oa(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{S.contains(v)&&S.removeChild(v)}},[t]),d.jsx(yu,{isPresent:t,childRef:o,sizeRef:i,children:Fe.cloneElement(e,{ref:c})})}const vu=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=Us(bu),l=m.useId();let h=!0,f=m.useMemo(()=>(h=!1,{id:l,initial:t,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const x of u.values())if(!x)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&h&&(f={...f}),m.useMemo(()=>{u.forEach((g,x)=>u.set(x,!1))},[n]),Fe.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(e=d.jsx(xu,{isPresent:n,anchorX:a,root:c,children:e})),d.jsx(_n.Provider,{value:f,children:e})};function bu(){return new Map}function qo(e=!0){const t=m.useContext(_n);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=m.useId();m.useEffect(()=>{if(e)return r(o)},[e]);const i=m.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const kn=e=>e.key||"";function ti(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const wu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=qo(i),h=m.useMemo(()=>ti(e),[e]),f=i&&!u?[]:h.map(kn),g=m.useRef(!0),x=m.useRef(h),v=Us(()=>new Map),[S,T]=m.useState(h),[b,y]=m.useState(h);eo(()=>{g.current=!1,x.current=h;for(let C=0;C<b.length;C++){const A=kn(b[C]);f.includes(A)?v.delete(A):v.get(A)!==!0&&v.set(A,!1)}},[b,f.length,f.join("-")]);const M=[];if(h!==S){let C=[...h];for(let A=0;A<b.length;A++){const E=b[A],X=kn(E);f.includes(X)||(C.splice(A,0,E),M.push(E))}return o==="wait"&&M.length&&(C=M),y(ti(C)),T(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&b.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:k}=m.useContext(zs);return d.jsx(d.Fragment,{children:b.map(C=>{const A=kn(C),E=i&&!u?!1:h===b||f.includes(A),X=()=>{if(v.has(A))v.set(A,!0);else return;let L=!0;v.forEach(se=>{se||(L=!1)}),L&&(k?.(),y(x.current),i&&l?.(),s&&s())};return d.jsx(vu,{isPresent:E,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:E?void 0:X,anchorX:a,children:C},A)})})},hr=m.createContext({strict:!1}),ni={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"]},Ut={};for(const e in ni)Ut[e]={isEnabled:t=>ni[e].some(n=>!!t[n])};function Es(e){for(const t in e)Ut[t]={...Ut[t],...e[t]}}function Tu({children:e,features:t,strict:n=!1}){const[,s]=m.useState(!os(t)),r=m.useRef(void 0);if(!os(t)){const{renderer:o,...i}=t;r.current=o,Es(i)}return m.useEffect(()=>{os(t)&&t().then(({renderer:o,...i})=>{Es(i),r.current=o,s(!0)})},[]),d.jsx(hr.Provider,{value:{renderer:r.current,strict:n},children:e})}function os(e){return typeof e=="function"}const Su=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 zn(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Su.has(e)}let Go=e=>!zn(e);function Au(e){typeof e=="function"&&(Go=t=>t.startsWith("on")?!zn(t):e(t))}try{Au(require("@emotion/is-prop-valid").default)}catch{}function Pu(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Go(r)||n===!0&&zn(r)||!t&&!zn(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Wn=m.createContext({});function Kn(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function fn(e){return typeof e=="string"||Array.isArray(e)}const fr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],mr=["initial",...fr];function qn(e){return Kn(e.animate)||mr.some(t=>fn(e[t]))}function Ho(e){return!!(qn(e)||e.variants)}function Cu(e,t){if(qn(e)){const{initial:n,animate:s}=e;return{initial:n===!1||fn(n)?n:void 0,animate:fn(s)?s:void 0}}return e.inherit!==!1?t:{}}function ju(e){const{initial:t,animate:n}=Cu(e,m.useContext(Wn));return m.useMemo(()=>({initial:t,animate:n}),[si(t),si(n)])}function si(e){return Array.isArray(e)?e.join(" "):e}const mn={};function ku(e){for(const t in e)mn[t]=e[t],Js(t)&&(mn[t].isCSSVariable=!0)}function Xo(e,{layout:t,layoutId:n}){return qt.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!mn[e]||e==="opacity")}const Mu={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Eu=Kt.length;function Du(e,t,n){let s="",r=!0;for(let o=0;o<Eu;o++){const i=Kt[o],a=e[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=Bo(a,cr[i]);if(!c){r=!1;const l=Mu[i]||i;s+=`${l}(${u}) `}n&&(t[i]=u)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function pr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const c in t){const u=t[c];if(qt.has(c)){i=!0;continue}else if(Js(c)){r[c]=u;continue}else{const l=Bo(u,cr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(t.transform||(i||n?s.transform=Du(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:l=0}=o;s.transformOrigin=`${c} ${u} ${l}`}}const gr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Yo(e,t,n){for(const s in t)!Te(t[s])&&!Xo(s,n)&&(e[s]=t[s])}function Nu({transformTemplate:e},t){return m.useMemo(()=>{const n=gr();return pr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ru(e,t){const n=e.style||{},s={};return Yo(s,n,e),Object.assign(s,Nu(e,t)),s}function Vu(e,t){const n={},s=Ru(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Iu={offset:"stroke-dashoffset",array:"stroke-dasharray"},Ou={offset:"strokeDashoffset",array:"strokeDasharray"};function Lu(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?Iu:Ou;e[o.offset]=B.transform(-s);const i=B.transform(t),a=B.transform(n);e[o.array]=`${i} ${a}`}function Jo(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(pr(e,a,u),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:f}=e;h.transform&&(f.transform=h.transform,delete h.transform),(f.transform||h.transformOrigin)&&(f.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Lu(h,r,o,i,!1)}const Zo=()=>({...gr(),attrs:{}}),Qo=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Fu(e,t,n,s){const r=m.useMemo(()=>{const o=Zo();return Jo(o,t,Qo(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Yo(o,e.style,e),r.style={...o,...r.style}}return r}const $u=["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 yr(e){return typeof e!="string"||e.includes("-")?!1:!!($u.indexOf(e)>-1||/[A-Z]/u.test(e))}function Bu(e,t,n,{latestValues:s},r,o=!1){const a=(yr(e)?Fu:Vu)(t,s,r,e),c=Pu(t,typeof e=="string",o),u=e!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=t,h=m.useMemo(()=>Te(l)?l.get():l,[l]);return m.createElement(e,{...u,children:h})}function ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function xr(e,t,n,s){if(typeof t=="function"){const[r,o]=ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function Rn(e){return Te(e)?e.get():e}function zu({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Uu(n,s,r,e),renderState:t()}}function Uu(e,t,n,s){const r={},o=s(e,{});for(const f in o)r[f]=Rn(o[f]);let{initial:i,animate:a}=e;const c=qn(e),u=Ho(e);t&&u&&!c&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const h=l?a:i;if(h&&typeof h!="boolean"&&!Kn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const x=xr(e,f[g]);if(x){const{transitionEnd:v,transition:S,...T}=x;for(const b in T){let y=T[b];if(Array.isArray(y)){const M=l?y.length-1:0;y=y[M]}y!==null&&(r[b]=y)}for(const b in v)r[b]=v[b]}}}return r}const ea=e=>(t,n)=>{const s=m.useContext(Wn),r=m.useContext(_n),o=()=>zu(e,t,s,r);return n?o():Us(o)};function vr(e,t,n){const{style:s}=e,r={};for(const o in s)(Te(s[o])||t.style&&Te(t.style[o])||Xo(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const _u=ea({scrapeMotionValuesFromProps:vr,createRenderState:gr});function ta(e,t,n){const s=vr(e,t,n);for(const r in e)if(Te(e[r])||Te(t[r])){const o=Kt.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Wu=ea({scrapeMotionValuesFromProps:ta,createRenderState:Zo}),Ku=Symbol.for("motionComponentSymbol");function It(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function qu(e,t,n){return m.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):It(n)&&(n.current=s))},[t])}const br=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Gu="framerAppearId",na="data-"+br(Gu),sa=m.createContext({});function Hu(e,t,n,s,r){const{visualElement:o}=m.useContext(Wn),i=m.useContext(hr),a=m.useContext(_n),c=m.useContext(dr).reducedMotion,u=m.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const l=u.current,h=m.useContext(sa);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Xu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[na],x=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return eo(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),x.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!x.current&&l.animationState&&l.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),x.current=!1),l.enteringChildren=void 0)}),l}function Xu(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ra(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&It(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function ra(e){if(e)return e.options.allowProjection!==!1?e.projection:ra(e.parent)}function Vn(e,{forwardMotionProps:t=!1}={},n,s){n&&Es(n);const r=yr(e)?Wu:_u;function o(a,c){let u;const l={...m.useContext(dr),...a,layoutId:Yu(a)},{isStatic:h}=l,f=ju(a),g=r(a,h);if(!h&&_s){Ju(l,n);const x=Zu(l);u=x.MeasureLayout,f.visualElement=Hu(e,g,l,s,x.ProjectionNode)}return d.jsxs(Wn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Bu(e,a,qu(g,f.visualElement,c),g,h,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=m.forwardRef(o);return i[Ku]=e,i}function Yu({layoutId:e}){const t=m.useContext(zs).id;return t&&e!==void 0?t+"-"+e:e}function Ju(e,t){const n=m.useContext(hr).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?_t(!1,s,"lazy-strict-mode"):Ye(!1,s,"lazy-strict-mode")}}function Zu(e){const{drag:t,layout:n}=Ut;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Qu(e,t){if(typeof Proxy>"u")return Vn;const n=new Map,s=(o,i)=>Vn(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Hs(!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,Vn(i,void 0,e,t)),n.get(i))})}function ia({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function ed({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function td(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function as(e){return e===void 0||e===1}function Ds({scale:e,scaleX:t,scaleY:n}){return!as(e)||!as(t)||!as(n)}function Tt(e){return Ds(e)||oa(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function oa(e){return ii(e.x)||ii(e.y)}function ii(e){return e&&e!=="0%"}function Un(e,t,n){const s=e-n,r=t*s;return n+r}function oi(e,t,n,s,r){return r!==void 0&&(e=Un(e,r,s)),Un(e,n,s)+t}function Ns(e,t=0,n=1,s,r){e.min=oi(e.min,t,n,s,r),e.max=oi(e.max,t,n,s,r)}function aa(e,{x:t,y:n}){Ns(e.x,t.translate,t.scale,t.originPoint),Ns(e.y,n.translate,n.scale,n.originPoint)}const ai=.999999999999,ci=1.0000000000001;function nd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Lt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,aa(e,i)),s&&Tt(o.latestValues)&&Lt(e,o.latestValues))}t.x<ci&&t.x>ai&&(t.x=1),t.y<ci&&t.y>ai&&(t.y=1)}function Ot(e,t){e.min=e.min+t,e.max=e.max+t}function li(e,t,n,s,r=.5){const o=ce(e.min,e.max,r);Ns(e,t,n,o,s)}function Lt(e,t){li(e.x,t.x,t.scaleX,t.scale,t.originX),li(e.y,t.y,t.scaleY,t.scale,t.originY)}function ca(e,t){return ia(td(e.getBoundingClientRect(),t))}function sd(e,t,n){const s=ca(e,n),{scroll:r}=t;return r&&(Ot(s.x,r.offset.x),Ot(s.y,r.offset.y)),s}const ui=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ft=()=>({x:ui(),y:ui()}),di=()=>({min:0,max:0}),he=()=>({x:di(),y:di()}),Rs={current:null},la={current:!1};function rd(){if(la.current=!0,!!_s)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Rs.current=e.matches;e.addEventListener("change",t),t()}else Rs.current=!1}const id=new WeakMap;function od(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Te(r))e.addValue(s,r);else if(Te(o))e.addValue(s,zt(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,zt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const hi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class ad{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=or,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=Ce.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,oe.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=qn(n),this.isVariantNode=Ho(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:l,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const g=h[f];c[f]!==void 0&&Te(g)&&g.set(c[f])}}mount(t){this.current=t,id.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),la.current||rd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Rs.current,process.env.NODE_ENV!=="production"&&Hs(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(),ut(this.notifyUpdate),ut(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=qt.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&oe.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Ut){const n=Ut[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):he()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<hi.length;s++){const r=hi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=od(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=zt(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(to(s)||so(s))?s=parseFloat(s):!mu(s)&&dt.test(n)&&(s=$o(t,n)),this.setBaseTarget(t,Te(s)?s.get():s)),Te(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=xr(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Te(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Gs),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){lr.render(this.render)}}class ua extends ad{constructor(){super(...arguments),this.KeyframeResolver=nu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Te(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function da(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function cd(e){return window.getComputedStyle(e)}class ld extends ua{constructor(){super(...arguments),this.type="html",this.renderInstance=da}readValueFromInstance(t,n){if(qt.has(n))return this.projection?.isProjecting?Ss(n):bl(t,n);{const s=cd(t),r=(Js(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return ca(t,n)}build(t,n,s){pr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return vr(t,n,s)}}const ha=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 ud(e,t,n,s){da(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(ha.has(r)?r:br(r),t.attrs[r])}class dd extends ua{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=he}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(qt.has(n)){const s=Fo(n);return s&&s.default||0}return n=ha.has(n)?n:br(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return ta(t,n,s)}build(t,n,s){Jo(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){ud(t,n,s,r)}mount(t){this.isSVGTag=Qo(t.tagName),super.mount(t)}}const fa=(e,t)=>yr(e)?new dd(t):new ld(t,{allowProjection:e!==m.Fragment});function Bt(e,t,n){const s=e.getProps();return xr(s,t,n!==void 0?n:s.custom,e)}const Vs=e=>Array.isArray(e);function hd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,zt(n))}function fd(e){return Vs(e)?e[e.length-1]||0:e}function md(e,t){const n=Bt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=fd(o[i]);hd(e,i,a)}}function pd(e){return!!(Te(e)&&e.add)}function Is(e,t){const n=e.getValue("willChange");if(pd(n))return n.add(t);if(!n&&Je.WillChange){const s=new Je.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function ma(e){return e.props[na]}const gd=e=>e!==null;function yd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(gd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const xd={type:"spring",stiffness:500,damping:25,restSpeed:10},vd=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),bd={type:"keyframes",duration:.8},wd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Td=(e,{keyframes:t})=>t.length>2?bd:qt.has(e)?e.startsWith("scale")?vd(t[1]):xd:wd;function Sd({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const wr=(e,t,n,s={},r,o)=>i=>{const a=ar(s,e)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-$e(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-u,onUpdate:f=>{t.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};Sd(a)||Object.assign(l,Td(e,l)),l.duration&&(l.duration=$e(l.duration)),l.repeatDelay&&(l.repeatDelay=$e(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(ks(l),l.delay===0&&(h=!0)),(Je.instantAnimations||Je.skipAnimations)&&(h=!0,ks(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&t.get()!==void 0){const f=yd(l.keyframes,a);if(f!==void 0){oe.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new ir(l):new _l(l)};function Ad({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function pa(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const c=[],u=r&&e.animationState&&e.animationState.getState()[r];for(const l in a){const h=e.getValue(l,e.latestValues[l]??null),f=a[l];if(f===void 0||u&&Ad(u,l))continue;const g={delay:n,...ar(o||{},l)},x=h.get();if(x!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===x&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const T=ma(e);if(T){const b=window.MotionHandoffAnimation(T,l,oe);b!==null&&(g.startTime=b,v=!0)}}Is(e,l),h.start(wr(l,h,f,e.shouldReduceMotion&&Io.has(l)?{type:!1}:g,e,v));const S=h.animation;S&&c.push(S)}return i&&Promise.all(c).then(()=>{oe.update(()=>{i&&md(e,i)})}),c}function ga(e,t,n,s=0,r=1){const o=Array.from(e).sort((u,l)=>u.sortNodePosition(l)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Os(e,t,n={}){const s=Bt(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(pa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return Pd(e,t,c,u,l,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,u]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Pd(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(Os(c,t,{...i,delay:n+(typeof s=="function"?0:s)+ga(e.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function Cd(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>Os(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=Os(e,t,n);else{const r=typeof t=="function"?Bt(e,t,n.custom):t;s=Promise.all(pa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function ya(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const jd=mr.length;function xa(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?xa(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<jd;n++){const s=mr[n],r=e.props[s];(fn(r)||r===!1)&&(t[s]=r)}return t}const kd=[...fr].reverse(),Md=fr.length;function Ed(e){return t=>Promise.all(t.map(({animation:n,options:s})=>Cd(e,n,s)))}function Dd(e){let t=Ed(e),n=fi(),s=!0;const r=c=>(u,l)=>{const h=Bt(e,l,c==="exit"?e.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...x}=h;u={...u,...x,...g}}return u};function o(c){t=c(e)}function i(c){const{props:u}=e,l=xa(e.parent)||{},h=[],f=new Set;let g={},x=1/0;for(let S=0;S<Md;S++){const T=kd[S],b=n[T],y=u[T]!==void 0?u[T]:l[T],M=fn(y),k=T===c?b.isActive:null;k===!1&&(x=S);let C=y===l[T]&&y!==u[T]&&M;if(C&&s&&e.manuallyAnimateOnMount&&(C=!1),b.protectedKeys={...g},!b.isActive&&k===null||!y&&!b.prevProp||Kn(y)||typeof y=="boolean")continue;const A=Nd(b.prevProp,y);let E=A||T===c&&b.isActive&&!C&&M||S>x&&M,X=!1;const L=Array.isArray(y)?y:[y];let se=L.reduce(r(T),{});k===!1&&(se={});const{prevResolvedValues:ie={}}=b,ge={...ie,...se},Z=Q=>{E=!0,f.has(Q)&&(X=!0,f.delete(Q)),b.needsAnimating[Q]=!0;const de=e.getValue(Q);de&&(de.liveStyle=!1)};for(const Q in ge){const de=se[Q],le=ie[Q];if(g.hasOwnProperty(Q))continue;let ee=!1;Vs(de)&&Vs(le)?ee=!ya(de,le):ee=de!==le,ee?de!=null?Z(Q):f.add(Q):de!==void 0&&f.has(Q)?Z(Q):b.protectedKeys[Q]=!0}b.prevProp=y,b.prevResolvedValues=se,b.isActive&&(g={...g,...se}),s&&e.blockInitialAnimation&&(E=!1);const re=C&&A;E&&(!re||X)&&h.push(...L.map(Q=>{const de={type:T};if(typeof Q=="string"&&s&&!re&&e.manuallyAnimateOnMount&&e.parent){const{parent:le}=e,ee=Bt(le,Q);if(le.enteringChildren&&ee){const{delayChildren:Ze}=ee.transition||{};de.delay=ga(le.enteringChildren,e,Ze)}}return{animation:Q,options:de}}))}if(f.size){const S={};if(typeof u.initial!="boolean"){const T=Bt(e,Array.isArray(u.initial)?u.initial[0]:u.initial);T&&T.transition&&(S.transition=T.transition)}f.forEach(T=>{const b=e.getBaseTarget(T),y=e.getValue(T);y&&(y.liveStyle=!0),S[T]=b??null}),h.push({animation:S})}let v=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,v?t(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const h in n)n[h].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=fi()}}}function Nd(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!ya(t,e):!1}function bt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fi(){return{animate:bt(!0),whileInView:bt(),whileHover:bt(),whileTap:bt(),whileDrag:bt(),whileFocus:bt(),exit:bt()}}class ht{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Rd extends ht{constructor(t){super(t),t.animationState||(t.animationState=Dd(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Kn(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Vd=0;class Id extends ht{constructor(){super(...arguments),this.id=Vd++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const va={animation:{Feature:Rd},exit:{Feature:Id}};function pn(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function vn(e){return{point:{x:e.pageX,y:e.pageY}}}const Od=e=>t=>ur(t)&&e(t,vn(t));function rn(e,t,n,s){return pn(e,t,Od(n),s)}const ba=1e-4,Ld=1-ba,Fd=1+ba,wa=.01,$d=0-wa,Bd=0+wa;function Se(e){return e.max-e.min}function zd(e,t,n){return Math.abs(e-t)<=n}function mi(e,t,n,s=.5){e.origin=s,e.originPoint=ce(t.min,t.max,e.origin),e.scale=Se(n)/Se(t),e.translate=ce(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Ld&&e.scale<=Fd||isNaN(e.scale))&&(e.scale=1),(e.translate>=$d&&e.translate<=Bd||isNaN(e.translate))&&(e.translate=0)}function on(e,t,n,s){mi(e.x,t.x,n.x,s?s.originX:void 0),mi(e.y,t.y,n.y,s?s.originY:void 0)}function pi(e,t,n){e.min=n.min+t.min,e.max=e.min+Se(t)}function Ud(e,t,n){pi(e.x,t.x,n.x),pi(e.y,t.y,n.y)}function gi(e,t,n){e.min=t.min-n.min,e.max=e.min+Se(t)}function an(e,t,n){gi(e.x,t.x,n.x),gi(e.y,t.y,n.y)}function Ee(e){return[e("x"),e("y")]}const Ta=({current:e})=>e?e.ownerDocument.defaultView:null,yi=(e,t)=>Math.abs(e-t);function _d(e,t){const n=yi(e.x,t.x),s=yi(e.y,t.y);return Math.sqrt(n**2+s**2)}class Sa{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=ls(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,x=_d(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!x)return;const{point:v}=f,{timestamp:S}=ve;this.history.push({...v,timestamp:S});const{onStart:T,onMove:b}=this.handlers;g||(T&&T(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),b&&b(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=cs(g,this.transformPagePoint),oe.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:x,onSessionEnd:v,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const T=ls(f.type==="pointercancel"?this.lastMoveEventInfo:cs(g,this.transformPagePoint),this.history);this.startEvent&&x&&x(f,T),v&&v(f,T)},!ur(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=vn(t),c=cs(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=ve;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(t,ls(c,this.history)),this.removeListeners=gn(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),ut(this.updatePoint)}}function cs(e,t){return t?{point:t(e.point)}:e}function xi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ls({point:e},t){return{point:e,delta:xi(e,Aa(t)),offset:xi(e,Wd(t)),velocity:Kd(t,.1)}}function Wd(e){return e[0]}function Aa(e){return e[e.length-1]}function Kd(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Aa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>$e(t)));)n--;if(!s)return{x:0,y:0};const o=De(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 qd(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?ce(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?ce(n,e,s.max):Math.min(e,n)),e}function vi(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Gd(e,{top:t,left:n,bottom:s,right:r}){return{x:vi(e.x,n,r),y:vi(e.y,t,s)}}function bi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Hd(e,t){return{x:bi(e.x,t.x),y:bi(e.y,t.y)}}function Xd(e,t){let n=.5;const s=Se(e),r=Se(t);return r>s?n=un(t.min,t.max-s,e.min):s>r&&(n=un(e.min,e.max-r,t.min)),Xe(0,1,n)}function Yd(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Ls=.35;function Jd(e=Ls){return e===!1?e=0:e===!0&&(e=Ls),{x:wi(e,"left","right"),y:wi(e,"top","bottom")}}function wi(e,t,n){return{min:Ti(e,t),max:Ti(e,n)}}function Ti(e,t){return typeof e=="number"?e:e[t]||0}const Zd=new WeakMap;class Qd{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=he(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:x,onDragStart:v}=this.getProps();if(g&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ou(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ee(T=>{let b=this.getAxisMotionValue(T).get()||0;if(Ke.test(b)){const{projection:y}=this.visualElement;if(y&&y.layout){const M=y.layout.layoutBox[T];M&&(b=Se(M)*(parseFloat(b)/100))}}this.originPoint[T]=b}),v&&oe.postRender(()=>v(h,f)),Is(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:x,onDirectionLock:v,onDrag:S}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:T}=f;if(x&&this.currentDirection===null){this.currentDirection=eh(T),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,T),this.updateAxis("y",f.point,T),this.visualElement.render(),S&&S(h,f)},c=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f,this.stop(h,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Ee(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new Sa(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:Ta(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&oe.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!Mn(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=qd(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&It(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Gd(s.layoutBox,t):this.constraints=!1,this.elastic=Jd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ee(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Yd(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!It(t))return!1;const s=t.current;Ye(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=sd(s,r.root,this.visualElement.getTransformPagePoint());let i=Hd(r.layout.layoutBox,o);if(n){const a=n(ed(i));this.hasMutatedConstraints=!!a,a&&(i=ia(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Ee(l=>{if(!Mn(l,n,this.currentDirection))return;let h=c&&c[l]||{};i&&(h={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,x={type:"inertia",velocity:s?t[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,x)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Is(this.visualElement,t),s.start(wr(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ee(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ee(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Ee(n=>{const{drag:s}=this.getProps();if(!Mn(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-ce(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!It(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ee(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Xd({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(),Ee(i=>{if(!Mn(i,t,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(ce(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Zd.set(this.visualElement,this);const t=this.visualElement.current,n=rn(t,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();It(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()),oe.read(s);const i=pn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ee(l=>{const h=this.getAxisMotionValue(l);h&&(this.originPoint[l]+=c[l].translate,h.set(h.get()+c[l].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=Ls,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Mn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function eh(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class th extends ht{constructor(t){super(t),this.removeGroupControls=Ne,this.removeListeners=Ne,this.controls=new Qd(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ne}unmount(){this.removeGroupControls(),this.removeListeners()}}const Si=e=>(t,n)=>{e&&oe.postRender(()=>e(t,n))};class nh extends ht{constructor(){super(...arguments),this.removePointerDownListener=Ne}onPointerDown(t){this.session=new Sa(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ta(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Si(t),onStart:Si(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&oe.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=rn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const In={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ai(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const tn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(B.test(e))e=parseFloat(e);else return e;const n=Ai(e,t.target.x),s=Ai(e,t.target.y);return`${n}% ${s}%`}},sh={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=dt.parse(e);if(r.length>5)return s;const o=dt.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=c;const u=ce(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 us=!1;class rh extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;ku(ih),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),us&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),In.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,us=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||oe.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),lr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;us=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Pa(e){const[t,n]=qo(),s=m.useContext(zs);return d.jsx(rh,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(sa),isPresent:t,safeToRemove:n})}const ih={borderRadius:{...tn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:tn,borderTopRightRadius:tn,borderBottomLeftRadius:tn,borderBottomRightRadius:tn,boxShadow:sh};function oh(e,t,n){const s=Te(e)?e:zt(e);return s.start(wr("",s,t,n)),s.animation}const ah=(e,t)=>e.depth-t.depth;class ch{constructor(){this.children=[],this.isDirty=!1}add(t){Ws(this.children,t),this.isDirty=!0}remove(t){Ks(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(ah),this.isDirty=!1,this.children.forEach(t)}}function lh(e,t){const n=Ce.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(ut(s),e(o-t))};return oe.setup(s,!0),()=>ut(s)}const Ca=["TopLeft","TopRight","BottomLeft","BottomRight"],uh=Ca.length,Pi=e=>typeof e=="string"?parseFloat(e):e,Ci=e=>typeof e=="number"||B.test(e);function dh(e,t,n,s,r,o){r?(e.opacity=ce(0,n.opacity??1,hh(s)),e.opacityExit=ce(t.opacity??1,0,fh(s))):o&&(e.opacity=ce(t.opacity??1,n.opacity??1,s));for(let i=0;i<uh;i++){const a=`border${Ca[i]}Radius`;let c=ji(t,a),u=ji(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||Ci(c)===Ci(u)?(e[a]=Math.max(ce(Pi(c),Pi(u),s),0),(Ke.test(u)||Ke.test(c))&&(e[a]+="%")):e[a]=u}(t.rotate||n.rotate)&&(e.rotate=ce(t.rotate||0,n.rotate||0,s))}function ji(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const hh=ja(0,.5,ho),fh=ja(.5,.95,Ne);function ja(e,t,n){return s=>s<e?0:s>t?1:n(un(e,t,s))}function ki(e,t){e.min=t.min,e.max=t.max}function Me(e,t){ki(e.x,t.x),ki(e.y,t.y)}function Mi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Ei(e,t,n,s,r){return e-=t,e=Un(e,1/n,s),r!==void 0&&(e=Un(e,1/r,s)),e}function mh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Ke.test(t)&&(t=parseFloat(t),t=ce(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=ce(o.min,o.max,s);e===o&&(a-=t),e.min=Ei(e.min,t,n,a,r),e.max=Ei(e.max,t,n,a,r)}function Di(e,t,[n,s,r],o,i){mh(e,t[n],t[s],t[r],t.scale,o,i)}const ph=["x","scaleX","originX"],gh=["y","scaleY","originY"];function Ni(e,t,n,s){Di(e.x,t,ph,n?n.x:void 0,s?s.x:void 0),Di(e.y,t,gh,n?n.y:void 0,s?s.y:void 0)}function Ri(e){return e.translate===0&&e.scale===1}function ka(e){return Ri(e.x)&&Ri(e.y)}function Vi(e,t){return e.min===t.min&&e.max===t.max}function yh(e,t){return Vi(e.x,t.x)&&Vi(e.y,t.y)}function Ii(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Ma(e,t){return Ii(e.x,t.x)&&Ii(e.y,t.y)}function Oi(e){return Se(e.x)/Se(e.y)}function Li(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class xh{constructor(){this.members=[]}add(t){Ws(this.members,t),t.scheduleRender()}remove(t){if(Ks(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function vh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:u,rotate:l,rotateX:h,rotateY:f,skewX:g,skewY:x}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),h&&(s+=`rotateX(${h}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),x&&(s+=`skewY(${x}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const ds=["","X","Y","Z"],bh=1e3;let wh=0;function hs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Ea(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=ma(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",oe,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Ea(s)}function Da({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=wh++,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(Ah),this.nodes.forEach(kh),this.nodes.forEach(Mh),this.nodes.forEach(Ph)},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 ch)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Gs),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=Ko(i)&&!hu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let l,h=0;const f=()=>this.root.updateBlockedByResize=!1;oe.read(()=>{h=window.innerWidth}),e(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=lh(f,250),In.hasAnimatedSinceResize&&(In.hasAnimatedSinceResize=!1,this.nodes.forEach(Bi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:h,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const x=this.options.transition||u.getDefaultTransition()||Vh,{onLayoutAnimationStart:v,onLayoutAnimationComplete:S}=u.getProps(),T=!this.targetLayout||!Ma(this.targetLayout,g),b=!h&&f;if(this.options.layoutRoot||this.resumeFrom||b||h&&(T||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const y={...ar(x,"layout"),onPlay:v,onComplete:S};(u.shouldReduceMotion||this.options.layoutRoot)&&(y.delay=0,y.type=!1),this.startAnimation(y),this.setAnimationOrigin(l,b)}else h||Bi(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(),ut(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(Eh),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&&Ea(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const h=this.path[l];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Fi);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach($i);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(jh),this.nodes.forEach(Th),this.nodes.forEach(Sh)):this.nodes.forEach($i),this.clearAllSnapshots();const a=Ce.now();ve.delta=Xe(0,1e3/60,a-ve.timestamp),ve.timestamp=a,ve.isProcessing=!0,es.update.process(ve),es.preRender.process(ve),es.render.process(ve),ve.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,lr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ch),this.sharedNodes.forEach(Dh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,oe.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){oe.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Se(this.snapshot.measuredBox.x)&&!Se(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=he(),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&&!ka(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Tt(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)),Ih(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return he();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Oh))){const{scroll:u}=this.root;u&&(Ot(a.x,u.offset.x),Ot(a.y,u.offset.y))}return a}removeElementScroll(i){const a=he();if(Me(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:h}=u;u!==this.root&&l&&h.layoutScroll&&(l.wasRoot&&Me(a,i),Ot(a.x,l.offset.x),Ot(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=he();Me(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&&Lt(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),Tt(l.latestValues)&&Lt(c,l.latestValues)}return Tt(this.latestValues)&&Lt(c,this.latestValues),c}removeTransform(i){const a=he();Me(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Tt(u.latestValues))continue;Ds(u.latestValues)&&u.updateSnapshot();const l=he(),h=u.measurePageBox();Me(l,h),Ni(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return Tt(this.latestValues)&&Ni(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!==ve.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:l,layoutId:h}=this.options;if(!(!this.layout||!(l||h))){if(this.resolvedRelativeTargetAt=ve.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=he(),this.relativeTargetOrigin=he(),an(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Me(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=he(),this.targetWithTransforms=he()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Ud(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Me(this.target,this.layout.layoutBox),aa(this.target,this.targetDelta)):Me(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=he(),this.relativeTargetOrigin=he(),an(this.relativeTargetOrigin,this.target,f.target),Me(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ds(this.parent.latestValues)||oa(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===ve.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;Me(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;nd(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=he());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Mi(this.prevProjectionDelta.x,this.projectionDelta.x),Mi(this.prevProjectionDelta.y,this.projectionDelta.y)),on(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Li(this.projectionDelta.x,this.prevProjectionDelta.x)||!Li(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=Ft(),this.projectionDelta=Ft(),this.projectionDeltaWithTransform=Ft()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=Ft();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=he(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,v=g!==x,S=this.getStack(),T=!S||S.members.length<=1,b=!!(v&&!T&&this.options.crossfade===!0&&!this.path.some(Rh));this.animationProgress=0;let y;this.mixTargetDelta=M=>{const k=M/1e3;zi(h.x,i.x,k),zi(h.y,i.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(an(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Nh(this.relativeTarget,this.relativeTargetOrigin,f,k),y&&yh(this.relativeTarget,y)&&(this.isProjectionDirty=!1),y||(y=he()),Me(y,this.relativeTarget)),v&&(this.animationValues=l,dh(l,u,this.latestValues,k,b,T)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ut(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=oe.update(()=>{In.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=zt(0)),this.currentAnimation=oh(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(bh),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&&Na(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||he();const h=Se(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=Se(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Me(a,c),Lt(a,l),on(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new xh),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&&hs("z",i,u,this.animationValues);for(let l=0;l<ds.length;l++)hs(`rotate${ds[l]}`,i,u,this.animationValues),hs(`skew${ds[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=Rn(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=Rn(a?.pointerEvents)||""),this.hasProjected&&!Tt(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=vh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(h=c(l,h)),i.transform=h;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?l.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:l.opacityExit:i.opacity=u===this?l.opacity!==void 0?l.opacity:"":l.opacityExit!==void 0?l.opacityExit:0;for(const x in mn){if(l[x]===void 0)continue;const{correct:v,applyTo:S,isCSSVariable:T}=mn[x],b=h==="none"?l[x]:v(l[x],u);if(S){const y=S.length;for(let M=0;M<y;M++)i[S[M]]=b}else T?this.options.visualElement.renderState.vars[x]=b:i[x]=b}this.options.layoutId&&(i.pointerEvents=u===this?Rn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(Fi),this.root.sharedNodes.clear()}}}function Th(e){e.updateLayout()}function Sh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?Ee(l=>{const h=o?t.measuredBox[l]:t.layoutBox[l],f=Se(h);h.min=n[l].min,h.max=h.min+f}):Na(r,t.layoutBox,n)&&Ee(l=>{const h=o?t.measuredBox[l]:t.layoutBox[l],f=Se(n[l]);h.max=h.min+f,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[l].max=e.relativeTarget[l].min+f)});const i=Ft();on(i,n,t.layoutBox);const a=Ft();o?on(a,e.applyTransform(s,!0),t.measuredBox):on(a,n,t.layoutBox);const c=!ka(i);let u=!1;if(!e.resumeFrom){const l=e.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:h,layout:f}=l;if(h&&f){const g=he();an(g,t.layoutBox,h.layoutBox);const x=he();an(x,n,f.layoutBox),Ma(g,x)||(u=!0),l.options.layoutRoot&&(e.relativeTarget=x,e.relativeTargetOrigin=g,e.relativeParent=l)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function Ah(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Ph(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Ch(e){e.clearSnapshot()}function Fi(e){e.clearMeasurements()}function $i(e){e.isLayoutDirty=!1}function jh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Bi(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function kh(e){e.resolveTargetDelta()}function Mh(e){e.calcProjection()}function Eh(e){e.resetSkewAndRotation()}function Dh(e){e.removeLeadSnapshot()}function zi(e,t,n){e.translate=ce(t.translate,0,n),e.scale=ce(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Ui(e,t,n,s){e.min=ce(t.min,n.min,s),e.max=ce(t.max,n.max,s)}function Nh(e,t,n,s){Ui(e.x,t.x,n.x,s),Ui(e.y,t.y,n.y,s)}function Rh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const Vh={duration:.45,ease:[.4,0,.1,1]},_i=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Wi=_i("applewebkit/")&&!_i("chrome/")?Math.round:Ne;function Ki(e){e.min=Wi(e.min),e.max=Wi(e.max)}function Ih(e){Ki(e.x),Ki(e.y)}function Na(e,t,n){return e==="position"||e==="preserve-aspect"&&!zd(Oi(t),Oi(n),.2)}function Oh(e){return e!==e.root&&e.scroll?.wasRoot}const Lh=Da({attachResizeListener:(e,t)=>pn(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),fs={current:void 0},Ra=Da({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!fs.current){const e=new Lh({});e.mount(window),e.setOptions({layoutScroll:!0}),fs.current=e}return fs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Fh={pan:{Feature:nh},drag:{Feature:th,ProjectionNode:Ra,MeasureLayout:Pa}};function qi(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&oe.postRender(()=>o(t,vn(t)))}class $h extends ht{mount(){const{current:t}=this.node;t&&(this.unmount=au(t,(n,s)=>(qi(this.node,s,"Start"),r=>qi(this.node,r,"End"))))}unmount(){}}class Bh extends ht{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=gn(pn(this.node.current,"focus",()=>this.onFocus()),pn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Gi(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&oe.postRender(()=>o(t,vn(t)))}class zh extends ht{mount(){const{current:t}=this.node;t&&(this.unmount=du(t,(n,s)=>(Gi(this.node,s,"Start"),(r,{success:o})=>Gi(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Fs=new WeakMap,ms=new WeakMap,Uh=e=>{const t=Fs.get(e.target);t&&t(e)},_h=e=>{e.forEach(Uh)};function Wh({root:e,...t}){const n=e||document;ms.has(n)||ms.set(n,{});const s=ms.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(_h,{root:e,...t})),s[r]}function Kh(e,t,n){const s=Wh(t);return Fs.set(e,n),s.observe(e),()=>{Fs.delete(e),s.unobserve(e)}}const qh={some:0,all:1};class Gh extends ht{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:qh[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:l,onViewportLeave:h}=this.node.getProps(),f=u?l:h;f&&f(c)};return Kh(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Hh(t,n))&&this.startObserver()}unmount(){}}function Hh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Va={inView:{Feature:Gh},tap:{Feature:zh},focus:{Feature:Bh},hover:{Feature:$h}},Xh={layout:{ProjectionNode:Ra,MeasureLayout:Pa}},Yh={...va,...Va,...Fh,...Xh},Jh=Qu(Yh,fa),Zh={renderer:fa,...va,...Va};function Ia(e,t){return Vn(e,t)}const En=Ia("div"),Qh=Ia("p"),We=Symbol.for("@arcteninc/core:originalName");function ef(e,t){return e[We]=t,e}function tf(e,t,n,s){if(typeof e!="function")return null;const r=e[We];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[We]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[We]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(c=>!n.has(c.name)),i)return e[We]=i.name,{fn:e,meta:i};return null}function Oa(e,t){let n,s;if(!t)throw new Error(`❌ toolMetadata is required!
10
10
 
11
11
  Please:
12
12
  1. Run "arcten-extract-types ." before build (add to package.json scripts)
@@ -16,9 +16,9 @@ Please:
16
16
  useAgent({ tools: [...], toolMetadata: toolMetadata })
17
17
  (Pass the full object for better minification support, or toolMetadata.functions for backward compatibility)
18
18
  `);if("functions"in t&&typeof t.functions=="object"){const o=t;n=o.functions,s=o.toolOrder}else n=t,s=void 0;const r=new Set;return e.map(o=>{const i=tf(o,n,r,s);if(!i){const a=o.name,u=o[We]||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 nf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return d.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:d.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&d.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),d.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d.jsxs(Ln,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(me.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Ln,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(me.X,{className:"h-3 w-3"})})]})]})})}function sf({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return d.jsxs("div",{className:"my-1",children:[d.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(me.ChevronDown,{className:"h-3 w-3"}):d.jsx(me.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(me.X,{className:"h-3 w-3"}):s?d.jsx(me.Zap,{className:"h-3 w-3"}):d.jsx(me.Check,{className:"h-3 w-3"}),d.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&c&&d.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:d.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function rf({...e}){return d.jsx(Bs.Root,{"data-slot":"collapsible",...e})}function of({...e}){return d.jsx(Bs.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function af({...e}){return d.jsx(Bs.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const cf=m.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Tr=m.memo(({className:e,...t})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(cf,{className:pe("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Tr.displayName="Response";const lf=Object.freeze(Object.defineProperty({__proto__:null,Response:Tr},Symbol.toStringTag,{value:"Module"})),uf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Jh.create(t),i=m.useMemo(()=>(e?.length??0)*r,[e,r]);return d.jsx(o,{animate:{backgroundPosition:"0% center"},className:pe("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},df=m.memo(uf),La=m.createContext(null),hf=()=>{const e=m.useContext(La);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},ff=1e3,mf=1e3,Fa=m.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Dr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Dr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[x,v]=m.useState(null);m.useEffect(()=>{t?x===null&&v(Date.now()):x!==null&&(h(Math.ceil((Date.now()-x)/mf)),v(null))},[t,x,h]),m.useEffect(()=>{if(s&&!t&&c&&!f){const T=setTimeout(()=>{u(!1),g(!0)},ff);return()=>clearTimeout(T)}},[t,c,s,u,f]);const S=T=>{u(T)};return d.jsx(La.Provider,{value:{isStreaming:t,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(rf,{className:pe("not-prose mb-4",e),onOpenChange:S,open:c,...a,children:i})})}),pf=(e,t)=>e||t===0?d.jsx(df,{duration:1,children:"Thinking..."}):t===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",t," seconds"]}),$a=m.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=hf();return d.jsx(of,{className:pe("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??d.jsxs(d.Fragment,{children:[d.jsx(me.BrainIcon,{className:"size-4"}),pf(s,o),d.jsx(me.ChevronDownIcon,{className:pe("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ba=m.memo(({className:e,children:t,...n})=>d.jsx(af,{className:pe("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:d.jsx(Tr,{className:"grid gap-2",children:t})}));Fa.displayName="Reasoning";$a.displayName="ReasoningTrigger";Ba.displayName="ReasoningContent";function Hi(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function gf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=Hi(s.domain);return d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsxs("button",{className:pe("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[d.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),d.jsx("span",{className:"leading-none",children:s.domain})]})}),d.jsx(ct,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>d.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:pe("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:i=>i.stopPropagation(),children:[d.jsx("img",{src:Hi(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),d.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function yf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=m.useRef(null),[l,h]=m.useState([]);m.useEffect(()=>{if(!a||!u.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const x=u.current;let v,S=!1;const T=new WeakSet,b=()=>{if(!u.current||S)return;S=!0;const M=u.current,k=/\[(\d+)\]/g,C=document.createTreeWalker(M,NodeFilter.SHOW_TEXT,null),A=[];let E;for(;E=C.nextNode();)if(E.nodeType===Node.TEXT_NODE&&!T.has(E)){const O=E,se=O.textContent||"";let ie=O.parentElement,ge=!1;for(;ie&&ie!==M;){if(ie.tagName==="A"||ie.tagName==="CODE"||ie.tagName==="PRE"){ge=!0;break}ie=ie.parentElement}if(!ge){const re=Array.from(se.matchAll(k)).filter(G=>{if(!G[1])return!1;const Q=parseInt(G[1],10);return n.has(Q)});re.length>0&&A.push({node:O,matches:re})}}if(A.length===0){S=!1;return}const X=[];A.forEach(({node:O,matches:se})=>{T.add(O);const ie=O.textContent||"",ge=document.createDocumentFragment();let Z=0;se.forEach(re=>{if(!re[1])return;re.index!==void 0&&re.index>Z&&ge.appendChild(document.createTextNode(ie.slice(Z,re.index)));const G=document.createElement("span");G.className="inline-flex items-center citation-button-container";const Q=parseInt(re[1],10);G.setAttribute("data-citation",re[1]),ge.appendChild(G),X.push({element:G,citationNum:Q}),Z=(re.index||0)+re[0].length}),Z<ie.length&&ge.appendChild(document.createTextNode(ie.slice(Z))),O.parentNode&&O.parentNode.replaceChild(ge,O)}),X.length>0&&h(O=>{const se=new Set(O.map(Z=>Z.element)),ie=O.filter(Z=>Z.element.isConnected),ge=X.filter(Z=>!se.has(Z.element));return[...ie,...ge]}),S=!1},y=new MutationObserver(()=>{clearTimeout(v),v=setTimeout(b,100)});return y.observe(x,{childList:!0,subtree:!0,characterData:!0}),v=setTimeout(b,200),()=>{y.disconnect(),clearTimeout(v)}},[e,t,n,a]);const f=s&&s.length>0||n&&n.size>0||r,g=a&&c&&f?d.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[d.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-2",children:"References"}),d.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:s&&s.length>0?s.map((x,v)=>{const S=x.numbers[0],T=x.anchor?`${x.baseUrl}#${x.anchor}`:x.url,b=x.anchor&&x.url!==T;return d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium whitespace-nowrap",children:["[",S,"]"]}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("a",{href:x.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:x.baseUrl}),b&&d.jsxs("span",{className:"text-stone-500 dark:text-stone-500 ml-1",children:["#",x.anchor]})]})]},`group-${v}`)}):Array.from(n.entries()).sort(([x],[v])=>x-v).map(([x,v])=>d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium",children:["[",x,"]"]}),d.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:v})]},x))})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:u,children:d.jsx(o,{children:e})}),a&&l.filter(({element:x})=>x.isConnected).map(({element:x,citationNum:v},S)=>{if(!t.find(y=>y.number===v))return null;const b=Array.from(new Map(t.map(y=>[y.url.replace(/\/+$/,""),{number:y.number,url:y.url,domain:xf(y.url)}])).values());return mc.createPortal(d.jsx(gf,{sources:b,citationNumber:v},`citation-${v}-${x}`),x,`citation-${v}-${S}`)}),g]})}function xf(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}function vf(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function Xi(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const b=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let M;for(;(M=y.exec(b))!==null;)if(M[1]&&M[2]){const k=parseInt(M[1],10),C=M[2].replace(/[.,;:!?]+$/,""),A=C.replace(/\/+$/,"");if(a.has(A)||a.set(A,C),i.has(A)||i.set(A,[]),i.get(A).push(k),!c.has(A))c.set(A,k);else{const E=c.get(A);k<E&&c.set(A,k)}}for(const[k,C]of i.entries()){const A=c.get(k);for(const E of C)E!==A&&u.set(E,A)}for(const[k,C]of c.entries()){const A=a.get(k)||k;r.set(C,A),o.push({number:C,url:A})}}let l,h=t;s&&s[0]&&(l=s[0],h=t.replace(n,""));const f=[];let g=0;const x=/```[\s\S]*?```|`[^`]+`/g;let v;for(;(v=x.exec(h))!==null;)v.index>g&&f.push({type:"text",content:h.slice(g,v.index),start:g,end:v.index}),f.push({type:"code",content:v[0],start:v.index,end:v.index+v[0].length}),g=v.index+v[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const S=f.map(b=>{if(b.type==="code")return b.content;let y=b.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(k,C,A)=>{const E=parseInt(C,10),X=A.replace(/\/+$/,""),O=u.get(E)||E;return c.has(X)||(c.set(X,O),r.has(O)||(r.set(O,A),o.push({number:O,url:A}))),`[${O}]`}),y=y.replace(/\[(\d+)\]/g,(k,C)=>{const A=parseInt(C,10);return`[${u.get(A)||A}]`}),y}),T=[];for(const[b,y]of c.entries()){const M=a.get(b)||b,{baseUrl:k,anchor:C}=vf(M);T.push({url:M,baseUrl:k,numbers:[y],anchor:C})}return T.sort((b,y)=>(b.numbers[0]||0)-(y.numbers[0]||0)),{processedText:S.join(""),citations:o.sort((b,y)=>b.number-y.number),citationMap:r,groupedCitations:T,referencesText:l}}function cn(e){if(typeof e=="string")try{const t=JSON.parse(e);return cn(t)}catch{return e}if(Array.isArray(e))return e.map(cn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=cn(s);return t}return e}function ps(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return cn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?cn(e):{}}function bf({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:h=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:x="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:S,state:T,onStateChange:b,allowStateEdits:y=!0,sources:M,ragConfig:k,showCitations:C=!0}){const A=m.useMemo(()=>k!==void 0?k:M&&M.length>0?{enabled:!0,organizationId:M[0],autoExecute:!0,filters:void 0}:{enabled:!1},[M,k]),[E,X]=m.useState(null),O=m.useRef(null),[se,ie]=m.useState(null),[ge,Z]=m.useState(null),re=m.useRef(null),G=T!==void 0,[Q,de]=m.useState({}),le=m.useRef({});G&&T?le.current=T:G||(le.current=Q);const[ee,Ze]=m.useState(!1),[jt,ye]=m.useState(null),Qe=m.useRef(!1),[Be,kt]=m.useState(u),[ze,et]=m.useState(i),[tt,Mt]=m.useState(600),[nt,Re]=m.useState(!1),[Y,Ve]=m.useState(!1),[Ae,ke]=m.useState(!1),[be,Et]=m.useState({x:100,y:100}),[Gt,ft]=m.useState(!1),[Dt,bn]=m.useState({x:0,y:0}),[wn,Ue]=m.useState(!1),Ht=m.useRef(null),st=m.useRef(null),[rt,Xt]=m.useState(""),[mt,Yt]=m.useState(null),[Gn,Hn]=m.useState("Thinking..."),[Jt,qe]=m.useState(new Set),[Xn,Yn]=m.useState(""),[P,j]=m.useState([]),[V,I]=m.useState(!1),[z,H]=m.useState([]),[_,we]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ue,Pe]=m.useState(!1),[ne,te]=m.useState(!1),[Nt,pt]=m.useState([]),Sr=m.useCallback(async(p,w=3)=>{if(!_||!O.current)return;const D=async()=>{const N=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,F=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:_,updates:p},format:"json"})});if(!F.ok){if(F.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await F.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${F.status} ${q}`)}};for(let R=0;R<w;R++)try{await D(),ye(null);return}catch(N){if(R===w-1){const q=N instanceof Error?N:new Error(String(N));throw ye(q),console.error("Failed to sync state to Convex after retries:",N),q}await new Promise(q=>setTimeout(q,Math.pow(2,R)*100))}},[_,v,O]),Zt=m.useMemo(()=>function(){return le.current},[]),Qt=m.useMemo(()=>async function(w){const D={...le.current,...w};le.current=D,G||de(D),b&&b(D);try{await Sr(w)}catch(R){throw R}},[Sr,b,G]);m.useEffect(()=>{G&&T&&(le.current=T)},[G,T]);const gt=m.useMemo(()=>A?.enabled?async function(w,D=20,R){if(M&&M.length>1){const q=M.map($=>fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json",...O.current?{Authorization:`Bearer ${O.current}`}:{}},body:JSON.stringify({q:w,k:Math.min(D,100),organizationId:$,...Object.keys(F).length>0?{filters:F}:{}})}).then(W=>W.ok?W.json():null)),U=await Promise.all(q),L=[];for(const $ of U)$?.candidates&&L.push(...$.candidates);L.sort(($,W)=>{const J=$.scores?.rerank||$.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-J});const K=L.slice(0,D).map(($,W)=>{const J=$.citation||$.url;return{rank:W+1,doc_id:$.doc_id,block_id:$.block_id,url:$.url,citation:J,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:w,total:L.length,results:K,summary:`Found ${L.length} relevant results across ${M.length} source(s) for "${w}". Top result: ${K[0]?.title||"N/A"}`}}const N=A.organizationId&&A.organizationId!=="default"?A.organizationId:void 0,F={...A.filters,...R};try{const q={q:w,k:Math.min(D,100)};N&&(q.organizationId=N),Object.keys(F).length>0&&(q.filters=F);const U={"Content-Type":"application/json"};O.current&&(U.Authorization=`Bearer ${O.current}`);const L=await fetch(`${v}/search`,{method:"POST",headers:U,body:JSON.stringify(q)});if(!L.ok){const W=await L.text();return{success:!1,error:`Search failed: ${L.status} ${W}`}}const K=await L.json(),$=K.candidates.map((W,J)=>{const je=W.citation||W.url;return{rank:J+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:je,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:K.query,total:K.total,results:$,summary:`Found ${K.total} relevant results for "${w}". Top result: ${$[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[k,v,O]),yt=m.useMemo(()=>A?.enabled?async function(w,D){const R=A.organizationId&&A.organizationId!=="default"?A.organizationId:M&&M.length>0?M[0]:void 0;try{const N={"Content-Type":"application/json"};O.current&&(N.Authorization=`Bearer ${O.current}`);const F=await fetch(`${v}/fetch`,{method:"POST",headers:N,body:JSON.stringify({doc_id:w,block_ids:D,...R?{organizationId:R}:{}})});if(!F.ok){const U=await F.text();return{success:!1,error:`Fetch failed: ${F.status} ${U}`}}const q=await F.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||w}`}}catch(N){return{success:!1,error:N instanceof Error?N.message:"Unknown error occurred"}}}:null,[k,v,O]),xt=m.useMemo(()=>{const p=[...l,...h,Zt];return(!G||y)&&p.push(Qt),A?.enabled&&(gt&&p.push(gt),yt&&p.push(yt)),p},[l,h,Zt,Qt,gt,yt,G,y,A]),Jn=m.useMemo(()=>Oa(xt,f),[xt,f]),Ge=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||y)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const w=[];return A?.enabled&&w.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Jn,...p,...w]},[Jn,G,y,A]),Ar=m.useMemo(()=>new Set(Ge.map(p=>p.name)),[Ge]),Tn=m.useMemo(()=>Ge.filter(p=>p.name==="getState"?!0:p.name==="setState"?!G||y:Ar.has(p.name)),[Ge,Ar,G,y]),Sn=m.useMemo(()=>{const p=new Map,w=new Map(Jn.map(D=>[D.name,D]));return p.set("getState",Zt),(!G||y)&&p.set("setState",Qt),A?.enabled&&(gt&&p.set("searchDocs",gt),yt&&p.set("fetchDocContent",yt)),xt.forEach(D=>{if(D===Zt||D===Qt||D===gt||D===yt)return;const R=D[We];if(R){const F=w.get(R);if(F){p.set(F.name,D);return}}const N=Ge.find(F=>F.name===D.name);N&&p.set(N.name,D)}),p},[xt,Ge,Zt,Qt,gt,yt,G,y,A]),en=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),A?.enabled&&A.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const w=new Map(Ge.map(D=>[D.name,D]));return h.forEach(D=>{const R=D[We];if(R&&w.has(R))p.add(R);else{const N=Ge.find(F=>F.name===D.name);N&&p.add(N.name)}}),p},[h,Ge,A]),Pr=["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&&kt(JSON.parse(p));const w=localStorage.getItem("arcten-sidebar-width");w&&et(parseInt(w));const D=localStorage.getItem("arcten-sidebar-height");D&&Mt(parseInt(D));const R=localStorage.getItem("arcten-sidebar-detached");R&&Ve(JSON.parse(R));const N=localStorage.getItem("arcten-sidebar-position");if(N){const q=JSON.parse(N),U=50,L=Math.max(U-i,Math.min(q.x,window.innerWidth-U)),K=Math.max(0,Math.min(q.y,window.innerHeight-U));Et({x:L,y:K})}const F=localStorage.getItem("arcten-sidebar-minimized");F&&ke(JSON.parse(F)),Ue(!0)}},[]);const it=m.useMemo(()=>S,[S?.id]);m.useEffect(()=>((async()=>{try{const w=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:it})});if(!w.ok)throw new Error("Failed to fetch token");const D=await w.json();X(D.clientToken),O.current=D.clientToken,Z(D.expiresAt),ie(null)}catch(w){ie(w instanceof Error?w.message:"Failed to fetch token")}})(),()=>{re.current&&clearTimeout(re.current)}),[x,it]),m.useEffect(()=>{if(!ge)return;re.current&&clearTimeout(re.current);const p=Math.floor(Date.now()/1e3),w=ge-p,R=Math.max(0,w-5);return re.current=setTimeout(async()=>{try{const N=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:it})});if(!N.ok)throw new Error("Failed to refresh token");const F=await N.json();X(F.clientToken),O.current=F.clientToken,Z(F.expiresAt),ie(null)}catch(N){console.error("Token refresh failed:",N),ie(N instanceof Error?N.message:"Failed to refresh token")}},R*1e3),()=>{re.current&&clearTimeout(re.current)}},[ge,x,it]),m.useEffect(()=>{(async()=>{if(xt.length!==0)try{const w=xt.map(R=>({name:R.name,code:R.toString()})),D=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:w})});if(D.ok){const R=await D.json();j(R.tools)}}catch(w){console.error("Failed to fetch tool descriptions:",w)}})()},[xt]),m.useEffect(()=>{Promise.resolve().then(()=>lf).then(p=>{Yt(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Yn(window.location.pathname)};p(),window.addEventListener("popstate",p);const w=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(w)}},[]);const Zn=m.useCallback(async()=>{if(!(!it?.id||!E)){te(!0);try{const w=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${E}`}})).json();H(w.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{te(!1)}}},[it?.id,E,v]);m.useEffect(()=>{it?.id&&E&&Zn()},[it?.id,E,Zn]);function za(p){const w=Math.floor((Date.now()-p)/1e3);return w<60?"now":w<3600?`${Math.floor(w/60)}m`:w<86400?`${Math.floor(w/3600)}h`:`${Math.floor(w/86400)}d`}function Ua(){const p=crypto.randomUUID();we(p),Pn([]),pt([]),Pe(!1);const w=G?T||{}:{};le.current=w,G||de(w),b&&b(w),Qe.current=!1}async function _a(p){if(E)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${E}`}}),H(z.filter(w=>w._id!==p)),p===_&&Ua()}catch(w){console.error("Failed to delete conversation:",w)}}async function Wa(p){we(p.chatId),Pe(!1),te(!0);try{const w=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${O.current}`}});if(!w.ok)throw new Error(`Failed to fetch messages: ${w.statusText}`);const R=(await w.json()).messages||[];Pn(R),pt(R)}catch(w){console.error("Failed to load conversation messages:",w);const D=p.messages||[];Pn(D),pt(D)}finally{te(!1)}}const Ka=async(p,w={})=>{const D=w.headers?new Headers(w.headers):new Headers;return D.delete("user-agent"),D.delete("User-Agent"),fetch(p,{...w,headers:D})},{messages:He,sendMessage:qa,status:Ie,error:Cr,stop:An,addToolResult:vt,setMessages:Pn}=Yi.useChat({id:_||void 0,transport:new On.DefaultChatTransport({api:`${v}/chat`,fetch:Ka,headers:()=>{const p={};return O.current&&(p.Authorization=`Bearer ${O.current}`),p},body:()=>({tools:Tn.map(w=>({name:w.name,description:w.description,inputSchema:w.jsonSchema})),systemPrompt:g,currentRoute:Xn,state:le.current})}),sendAutomaticallyWhen:On.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=He[He.length-1];if(!p||p.role!=="assistant")return;const w=p.parts?.filter(D=>D.type?.startsWith("tool-")&&D.state==="input-available"&&typeof D.toolCallId=="string"&&D.input!==void 0)||[];for(const D of w){const R=D,N=R.type?.replace("tool-","")||"",F=R.toolCallId;if(en.has(N)){if(Jt.has(F))continue;qe(U=>U.has(F)?U:new Set(U).add(F)),(async()=>{try{const U=Sn.get(N);if(!U){console.warn(`[ArctenAgent] Tool ${N} not found in toolsMap. Available tools:`,Array.from(Sn.keys())),vt({toolCallId:F,tool:N,output:`Error: Tool ${N} not found`}),qe(W=>{const J=new Set(W);return J.delete(F),J});return}const L=ps(R.input),K=Tn.find(W=>W.name===N);let $;if(K&&K.jsonSchema?.properties){const J=Object.keys(K.jsonSchema.properties).map(je=>L[je]);console.log(`[ArctenAgent] Executing safe tool ${N} with args:`,J),$=await U(...J)}else if(N==="getState")$=U();else if(N==="setState"){const W=L.updates||L;$=await U(W)}else $=await U(...Object.values(L));console.log(`[ArctenAgent] Tool ${N} completed, result:`,$),vt({toolCallId:F,tool:N,output:$}),qe(W=>{const J=new Set(W);return J.delete(F),J})}catch(U){console.error(`[ArctenAgent] Error executing safe tool ${N}:`,U),vt({toolCallId:F,tool:N,output:`Error: ${U instanceof Error?U.message:String(U)}`}),qe(L=>{const K=new Set(L);return K.delete(F),K})}})()}}},[He,en,Sn,Tn,vt]),m.useEffect(()=>{if(!_||!O.current)return;(async()=>{Ze(!0),ye(null);try{const D=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,R=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:_},format:"json"})});if(!R.ok){if(R.status===404||R.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${R.status}), using empty state`);const K=G?T||{}:{};le.current=K,G||de(K),b&&b(K),Qe.current=!0,Ze(!1);return}const L=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${R.status} ${L}`)}const F=(await R.json())?.value||{},q=!Qe.current;let U;q?(U={...G?T||{}:{},...F},Qe.current=!0):U=F,le.current=U,G||de(U),b&&b(U)}catch(w){w instanceof TypeError&&w.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",w):console.error("[ArctenAgent] Failed to fetch state:",w);const R=w instanceof Error?w:new Error(String(w));if(ye(R),!Qe.current){const N=G?T||{}:{};le.current=N,G||de(N),b&&b(N),Qe.current=!0}}finally{Ze(!1)}})()},[_,v,G,T,b]),m.useEffect(()=>{Be&&st.current&&st.current.focus()},[Be,He]);function Ga(){kt(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ha(){kt(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Be]),m.useEffect(()=>{Ht.current&&Ht.current.scrollIntoView({behavior:"smooth"})},[He]),m.useEffect(()=>{function p(w){w.key==="Escape"&&(Ie==="streaming"||Ie==="submitted")&&(w.preventDefault(),An())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ie,An]);function Xa(){const p=crypto.randomUUID();we(p),Pn([]),pt([]),Pe(!1)}function jr(p){if(p.preventDefault(),!rt.trim())return;(Ie==="streaming"||Ie==="submitted")&&An();const w=Pr[Math.floor(Math.random()*Pr.length)]||"Thinking...";Hn(w),qa({text:rt}),Xt("")}function Ya(p){const w=p.target.value;Xt(w)}m.useEffect(()=>{if(!nt)return;function p(D){if(Y){const R=D.clientX-be.x,N=D.clientY-be.y;R>=a&&R<=c&&et(R),N>=400&&N<=1e3&&Mt(N)}else{const R=window.innerWidth-D.clientX;R>=a&&R<=c&&et(R)}}function w(){Re(!1),localStorage.setItem("arcten-sidebar-width",ze.toString()),localStorage.setItem("arcten-sidebar-height",tt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[nt,ze,tt,Y,be,a,c]);function Ja(p){p.preventDefault(),Re(!0)}function Za(){Ve(!0),ke(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qa(){Ve(!1),ke(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function kr(){ke(!Ae),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ae))}function ec(p){Y&&(ft(!0),bn({x:p.clientX-be.x,y:p.clientY-be.y}))}return m.useEffect(()=>{if(!Y)return;function p(){Et(w=>{const R=window.innerWidth-50,N=window.innerHeight-50,F=50-ze,q=0,U=Math.max(F,Math.min(w.x,R)),L=Math.max(q,Math.min(w.y,N));if(U!==w.x||L!==w.y){const K={x:U,y:L};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(K)),K}return w})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[Y,ze]),m.useEffect(()=>{if(!Gt)return;function p(D){const R=D.clientX-Dt.x,N=D.clientY-Dt.y,F=50,q=window.innerWidth-F,U=window.innerHeight-F,L=F-ze,K=0,$=Math.max(L,Math.min(R,q)),W=Math.max(K,Math.min(N,U));Et({x:$,y:W})}function w(){ft(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(be))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[Gt,Dt,be,ze]),wn?se?d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",se]})}):E?d.jsx(Tu,{features:Zh,children:d.jsx(En,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:Y?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:Y?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
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 nf({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return d.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:d.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&d.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),d.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d.jsxs(Ln,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(me.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Ln,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(me.X,{className:"h-3 w-3"})})]})]})})}function sf({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return d.jsxs("div",{className:"my-1",children:[d.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(me.ChevronDown,{className:"h-3 w-3"}):d.jsx(me.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(me.X,{className:"h-3 w-3"}):s?d.jsx(me.Zap,{className:"h-3 w-3"}):d.jsx(me.Check,{className:"h-3 w-3"}),d.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&c&&d.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:d.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function rf({...e}){return d.jsx(Bs.Root,{"data-slot":"collapsible",...e})}function of({...e}){return d.jsx(Bs.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function af({...e}){return d.jsx(Bs.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const cf=m.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Tr=m.memo(({className:e,...t})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(cf,{className:pe("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Tr.displayName="Response";const lf=Object.freeze(Object.defineProperty({__proto__:null,Response:Tr},Symbol.toStringTag,{value:"Module"})),uf=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Jh.create(t),i=m.useMemo(()=>(e?.length??0)*r,[e,r]);return d.jsx(o,{animate:{backgroundPosition:"0% center"},className:pe("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},df=m.memo(uf),La=m.createContext(null),hf=()=>{const e=m.useContext(La);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},ff=1e3,mf=1e3,Fa=m.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Dr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Dr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[x,v]=m.useState(null);m.useEffect(()=>{t?x===null&&v(Date.now()):x!==null&&(h(Math.ceil((Date.now()-x)/mf)),v(null))},[t,x,h]),m.useEffect(()=>{if(s&&!t&&c&&!f){const T=setTimeout(()=>{u(!1),g(!0)},ff);return()=>clearTimeout(T)}},[t,c,s,u,f]);const S=T=>{u(T)};return d.jsx(La.Provider,{value:{isStreaming:t,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(rf,{className:pe("not-prose mb-4",e),onOpenChange:S,open:c,...a,children:i})})}),pf=(e,t)=>e||t===0?d.jsx(df,{duration:1,children:"Thinking..."}):t===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",t," seconds"]}),$a=m.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=hf();return d.jsx(of,{className:pe("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??d.jsxs(d.Fragment,{children:[d.jsx(me.BrainIcon,{className:"size-4"}),pf(s,o),d.jsx(me.ChevronDownIcon,{className:pe("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ba=m.memo(({className:e,children:t,...n})=>d.jsx(af,{className:pe("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:d.jsx(Tr,{className:"grid gap-2",children:t})}));Fa.displayName="Reasoning";$a.displayName="ReasoningTrigger";Ba.displayName="ReasoningContent";function Hi(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function gf({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=Hi(s.domain);return d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsxs("button",{className:pe("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[d.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),d.jsx("span",{className:"leading-none",children:s.domain})]})}),d.jsx(ct,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>d.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:pe("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:i=>i.stopPropagation(),children:[d.jsx("img",{src:Hi(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),d.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function yf({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=m.useRef(null),[l,h]=m.useState([]);m.useEffect(()=>{if(!a||!u.current||t.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const x=u.current;let v,S=!1;const T=new WeakSet,b=()=>{if(!u.current||S)return;S=!0;const M=u.current,k=/\[(\d+)\]/g,C=document.createTreeWalker(M,NodeFilter.SHOW_TEXT,null),A=[];let E;for(;E=C.nextNode();)if(E.nodeType===Node.TEXT_NODE&&!T.has(E)){const L=E,se=L.textContent||"";let ie=L.parentElement,ge=!1;for(;ie&&ie!==M;){if(ie.tagName==="A"||ie.tagName==="CODE"||ie.tagName==="PRE"){ge=!0;break}ie=ie.parentElement}if(!ge){const re=Array.from(se.matchAll(k)).filter(G=>{if(!G[1])return!1;const Q=parseInt(G[1],10);return n.has(Q)});re.length>0&&A.push({node:L,matches:re})}}if(A.length===0){S=!1;return}const X=[];A.forEach(({node:L,matches:se})=>{T.add(L);const ie=L.textContent||"",ge=document.createDocumentFragment();let Z=0;se.forEach(re=>{if(!re[1])return;re.index!==void 0&&re.index>Z&&ge.appendChild(document.createTextNode(ie.slice(Z,re.index)));const G=document.createElement("span");G.className="inline-flex items-center citation-button-container";const Q=parseInt(re[1],10);G.setAttribute("data-citation",re[1]),ge.appendChild(G),X.push({element:G,citationNum:Q}),Z=(re.index||0)+re[0].length}),Z<ie.length&&ge.appendChild(document.createTextNode(ie.slice(Z))),L.parentNode&&L.parentNode.replaceChild(ge,L)}),X.length>0&&h(L=>{const se=new Set(L.map(Z=>Z.element)),ie=L.filter(Z=>Z.element.isConnected),ge=X.filter(Z=>!se.has(Z.element));return[...ie,...ge]}),S=!1},y=new MutationObserver(()=>{clearTimeout(v),v=setTimeout(b,100)});return y.observe(x,{childList:!0,subtree:!0,characterData:!0}),v=setTimeout(b,200),()=>{y.disconnect(),clearTimeout(v)}},[e,t,n,a]);const f=s&&s.length>0||n&&n.size>0||r,g=a&&c&&f?d.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[d.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-2",children:"References"}),d.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:s&&s.length>0?s.map((x,v)=>{const S=x.numbers[0],T=x.anchor?`${x.baseUrl}#${x.anchor}`:x.url,b=x.anchor&&x.url!==T;return d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium whitespace-nowrap",children:["[",S,"]"]}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("a",{href:x.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:x.baseUrl}),b&&d.jsxs("span",{className:"text-stone-500 dark:text-stone-500 ml-1",children:["#",x.anchor]})]})]},`group-${v}`)}):Array.from(n.entries()).sort(([x],[v])=>x-v).map(([x,v])=>d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium",children:["[",x,"]"]}),d.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:v})]},x))})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:u,children:d.jsx(o,{children:e})}),a&&l.filter(({element:x})=>x.isConnected).map(({element:x,citationNum:v},S)=>{if(!t.find(y=>y.number===v))return null;const b=Array.from(new Map(t.map(y=>[y.url.replace(/\/+$/,""),{number:y.number,url:y.url,domain:xf(y.url)}])).values());return mc.createPortal(d.jsx(gf,{sources:b,citationNumber:v},`citation-${v}-${x}`),x,`citation-${v}-${S}`)}),g]})}function xf(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}function vf(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function Xi(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const b=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let M;for(;(M=y.exec(b))!==null;)if(M[1]&&M[2]){const k=parseInt(M[1],10),C=M[2].replace(/[.,;:!?]+$/,""),A=C.replace(/\/+$/,"");if(a.has(A)||a.set(A,C),i.has(A)||i.set(A,[]),i.get(A).push(k),!c.has(A))c.set(A,k);else{const E=c.get(A);k<E&&c.set(A,k)}}for(const[k,C]of i.entries()){const A=c.get(k);for(const E of C)E!==A&&u.set(E,A)}for(const[k,C]of c.entries()){const A=a.get(k)||k;r.set(C,A),o.push({number:C,url:A})}}let l,h=t;s&&s[0]&&(l=s[0],h=t.replace(n,""));const f=[];let g=0;const x=/```[\s\S]*?```|`[^`]+`/g;let v;for(;(v=x.exec(h))!==null;)v.index>g&&f.push({type:"text",content:h.slice(g,v.index),start:g,end:v.index}),f.push({type:"code",content:v[0],start:v.index,end:v.index+v[0].length}),g=v.index+v[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const S=f.map(b=>{if(b.type==="code")return b.content;let y=b.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(k,C,A)=>{const E=parseInt(C,10),X=A.replace(/\/+$/,""),L=u.get(E)||E;return c.has(X)||(c.set(X,L),r.has(L)||(r.set(L,A),o.push({number:L,url:A}))),`[${L}]`}),y=y.replace(/\[(\d+)\]/g,(k,C)=>{const A=parseInt(C,10);return`[${u.get(A)||A}]`}),y}),T=[];for(const[b,y]of c.entries()){const M=a.get(b)||b,{baseUrl:k,anchor:C}=vf(M);T.push({url:M,baseUrl:k,numbers:[y],anchor:C})}return T.sort((b,y)=>(b.numbers[0]||0)-(y.numbers[0]||0)),{processedText:S.join(""),citations:o.sort((b,y)=>b.number-y.number),citationMap:r,groupedCitations:T,referencesText:l}}function cn(e){if(typeof e=="string")try{const t=JSON.parse(e);return cn(t)}catch{return e}if(Array.isArray(e))return e.map(cn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=cn(s);return t}return e}function ps(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return cn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?cn(e):{}}function bf({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:h=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:x="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:S,state:T,onStateChange:b,allowStateEdits:y=!0,sources:M,ragConfig:k,showCitations:C=!0}){const A=m.useMemo(()=>k!==void 0?k:M&&M.length>0?{enabled:!0,organizationId:M[0],autoExecute:!0,filters:void 0}:{enabled:!1},[M,k]),[E,X]=m.useState(null),L=m.useRef(null),[se,ie]=m.useState(null),[ge,Z]=m.useState(null),re=m.useRef(null),G=T!==void 0,[Q,de]=m.useState({}),le=m.useRef({});G&&T?le.current=T:G||(le.current=Q);const[ee,Ze]=m.useState(!1),[jt,ye]=m.useState(null),Qe=m.useRef(!1),[Be,kt]=m.useState(u),[ze,et]=m.useState(i),[tt,Mt]=m.useState(600),[nt,Re]=m.useState(!1),[Y,Ve]=m.useState(!1),[Ae,ke]=m.useState(!1),[be,Et]=m.useState({x:100,y:100}),[Gt,ft]=m.useState(!1),[Dt,bn]=m.useState({x:0,y:0}),[wn,Ue]=m.useState(!1),Ht=m.useRef(null),st=m.useRef(null),[rt,Xt]=m.useState(""),[mt,Yt]=m.useState(null),[Gn,Hn]=m.useState("Thinking..."),[Jt,qe]=m.useState(new Set),[Xn,Yn]=m.useState(""),[P,j]=m.useState([]),[V,I]=m.useState(!1),[U,H]=m.useState([]),[W,we]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ue,Pe]=m.useState(!1),[ne,te]=m.useState(!1),[Nt,pt]=m.useState([]),Sr=m.useCallback(async(p,w=3)=>{if(!W||!L.current)return;const D=async()=>{const N=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,$=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:W,updates:p},format:"json"})});if(!$.ok){if($.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${$.status} ${q}`)}};for(let R=0;R<w;R++)try{await D(),ye(null);return}catch(N){if(R===w-1){const q=N instanceof Error?N:new Error(String(N));throw ye(q),console.error("Failed to sync state to Convex after retries:",N),q}await new Promise(q=>setTimeout(q,Math.pow(2,R)*100))}},[W,v,L]),Zt=m.useMemo(()=>function(){return le.current},[]),Qt=m.useMemo(()=>async function(w){const D={...le.current,...w};le.current=D,G||de(D),b&&b(D);try{await Sr(w)}catch(R){throw R}},[Sr,b,G]);m.useEffect(()=>{G&&T&&(le.current=T)},[G,T]);const gt=m.useMemo(()=>A?.enabled?async function(w,D=20,R){if(M&&M.length>1){const q=M.map(F=>fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json",...L.current?{Authorization:`Bearer ${L.current}`}:{}},body:JSON.stringify({q:w,k:Math.min(D,100),organizationId:F,...Object.keys($).length>0?{filters:$}:{}})}).then(z=>z.ok?z.json():null)),_=await Promise.all(q),O=[];for(const F of _)F?.candidates&&O.push(...F.candidates);O.sort((F,z)=>{const J=F.scores?.rerank||F.scores?.dense||0;return(z.scores?.rerank||z.scores?.dense||0)-J});const K=O.slice(0,D).map((F,z)=>{const J=F.citation||F.url;return{rank:z+1,doc_id:F.doc_id,block_id:F.block_id,url:F.url,citation:J,title:F.title||"Untitled",snippet:F.snippet,score:F.scores?.rerank||F.scores?.dense||0,metadata:{site:F.metadata?.site,lang:F.metadata?.lang,contentType:F.metadata?.content_type}}});return{success:!0,query:w,total:O.length,results:K,summary:`Found ${O.length} relevant results across ${M.length} source(s) for "${w}". Top result: ${K[0]?.title||"N/A"}`}}const N=A.organizationId&&A.organizationId!=="default"?A.organizationId:void 0,$={...A.filters,...R};try{const q={q:w,k:Math.min(D,100)};N&&(q.organizationId=N),Object.keys($).length>0&&(q.filters=$);const _={"Content-Type":"application/json"};L.current&&(_.Authorization=`Bearer ${L.current}`);const O=await fetch(`${v}/search`,{method:"POST",headers:_,body:JSON.stringify(q)});if(!O.ok){const z=await O.text();return{success:!1,error:`Search failed: ${O.status} ${z}`}}const K=await O.json(),F=K.candidates.map((z,J)=>{const je=z.citation||z.url;return{rank:J+1,doc_id:z.doc_id,block_id:z.block_id,url:z.url,citation:je,title:z.title||"Untitled",snippet:z.snippet,score:z.scores?.rerank||z.scores?.dense||0,metadata:{site:z.metadata?.site,lang:z.metadata?.lang,contentType:z.metadata?.content_type}}});return{success:!0,query:K.query,total:K.total,results:F,summary:`Found ${K.total} relevant results for "${w}". Top result: ${F[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[k,v,L]),yt=m.useMemo(()=>A?.enabled?async function(w,D){const R=A.organizationId&&A.organizationId!=="default"?A.organizationId:M&&M.length>0?M[0]:void 0;try{const N={"Content-Type":"application/json"};L.current&&(N.Authorization=`Bearer ${L.current}`);const $=await fetch(`${v}/fetch`,{method:"POST",headers:N,body:JSON.stringify({doc_id:w,block_ids:D,...R?{organizationId:R}:{}})});if(!$.ok){const _=await $.text();return{success:!1,error:`Fetch failed: ${$.status} ${_}`}}const q=await $.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||w}`}}catch(N){return{success:!1,error:N instanceof Error?N.message:"Unknown error occurred"}}}:null,[k,v,L]),xt=m.useMemo(()=>{const p=[...l,...h,Zt];return(!G||y)&&p.push(Qt),A?.enabled&&(gt&&p.push(gt),yt&&p.push(yt)),p},[l,h,Zt,Qt,gt,yt,G,y,A]),Jn=m.useMemo(()=>Oa(xt,f),[xt,f]),Ge=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||y)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const w=[];return A?.enabled&&w.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Jn,...p,...w]},[Jn,G,y,A]),Ar=m.useMemo(()=>new Set(Ge.map(p=>p.name)),[Ge]),Tn=m.useMemo(()=>Ge.filter(p=>p.name==="getState"?!0:p.name==="setState"?!G||y:Ar.has(p.name)),[Ge,Ar,G,y]),Sn=m.useMemo(()=>{const p=new Map,w=new Map(Jn.map(D=>[D.name,D]));return p.set("getState",Zt),(!G||y)&&p.set("setState",Qt),A?.enabled&&(gt&&p.set("searchDocs",gt),yt&&p.set("fetchDocContent",yt)),xt.forEach(D=>{if(D===Zt||D===Qt||D===gt||D===yt)return;const R=D[We];if(R){const $=w.get(R);if($){p.set($.name,D);return}}const N=Ge.find($=>$.name===D.name);N&&p.set(N.name,D)}),p},[xt,Ge,Zt,Qt,gt,yt,G,y,A]),en=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),A?.enabled&&A.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const w=new Map(Ge.map(D=>[D.name,D]));return h.forEach(D=>{const R=D[We];if(R&&w.has(R))p.add(R);else{const N=Ge.find($=>$.name===D.name);N&&p.add(N.name)}}),p},[h,Ge,A]),Pr=["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&&kt(JSON.parse(p));const w=localStorage.getItem("arcten-sidebar-width");w&&et(parseInt(w));const D=localStorage.getItem("arcten-sidebar-height");D&&Mt(parseInt(D));const R=localStorage.getItem("arcten-sidebar-detached");R&&Ve(JSON.parse(R));const N=localStorage.getItem("arcten-sidebar-position");if(N){const q=JSON.parse(N),_=50,O=Math.max(_-i,Math.min(q.x,window.innerWidth-_)),K=Math.max(0,Math.min(q.y,window.innerHeight-_));Et({x:O,y:K})}const $=localStorage.getItem("arcten-sidebar-minimized");$&&ke(JSON.parse($)),Ue(!0)}},[]);const it=m.useMemo(()=>S,[S?.id]);m.useEffect(()=>((async()=>{try{const w=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:it})});if(!w.ok)throw new Error("Failed to fetch token");const D=await w.json();X(D.clientToken),L.current=D.clientToken,Z(D.expiresAt),ie(null)}catch(w){ie(w instanceof Error?w.message:"Failed to fetch token")}})(),()=>{re.current&&clearTimeout(re.current)}),[x,it]),m.useEffect(()=>{if(!ge)return;re.current&&clearTimeout(re.current);const p=Math.floor(Date.now()/1e3),w=ge-p,R=Math.max(0,w-5);return re.current=setTimeout(async()=>{try{const N=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:it})});if(!N.ok)throw new Error("Failed to refresh token");const $=await N.json();X($.clientToken),L.current=$.clientToken,Z($.expiresAt),ie(null)}catch(N){console.error("Token refresh failed:",N),ie(N instanceof Error?N.message:"Failed to refresh token")}},R*1e3),()=>{re.current&&clearTimeout(re.current)}},[ge,x,it]),m.useEffect(()=>{(async()=>{if(xt.length!==0)try{const w=xt.map(R=>({name:R.name,code:R.toString()})),D=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:w})});if(D.ok){const R=await D.json();j(R.tools)}}catch(w){console.error("Failed to fetch tool descriptions:",w)}})()},[xt]),m.useEffect(()=>{Promise.resolve().then(()=>lf).then(p=>{Yt(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Yn(window.location.pathname)};p(),window.addEventListener("popstate",p);const w=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(w)}},[]);const Zn=m.useCallback(async()=>{if(!(!it?.id||!E)){te(!0);try{const w=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${E}`}})).json();H(w.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{te(!1)}}},[it?.id,E,v]);m.useEffect(()=>{it?.id&&E&&Zn()},[it?.id,E,Zn]);function za(p){const w=Math.floor((Date.now()-p)/1e3);return w<60?"now":w<3600?`${Math.floor(w/60)}m`:w<86400?`${Math.floor(w/3600)}h`:`${Math.floor(w/86400)}d`}function Ua(){const p=crypto.randomUUID();we(p),Pn([]),pt([]),Pe(!1);const w=G?T||{}:{};le.current=w,G||de(w),b&&b(w),Qe.current=!1}async function _a(p){if(E)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${E}`}}),H(U.filter(w=>w._id!==p)),p===W&&Ua()}catch(w){console.error("Failed to delete conversation:",w)}}async function Wa(p){we(p.chatId),Pe(!1),te(!0);try{const w=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${L.current}`}});if(!w.ok)throw new Error(`Failed to fetch messages: ${w.statusText}`);const R=(await w.json()).messages||[];Pn(R),pt(R)}catch(w){console.error("Failed to load conversation messages:",w);const D=p.messages||[];Pn(D),pt(D)}finally{te(!1)}}const Ka=async(p,w={})=>{const D=w.headers?new Headers(w.headers):new Headers;return D.delete("user-agent"),D.delete("User-Agent"),fetch(p,{...w,headers:D})},{messages:He,sendMessage:qa,status:Ie,error:Cr,stop:An,addToolResult:vt,setMessages:Pn}=Yi.useChat({id:W||void 0,transport:new On.DefaultChatTransport({api:`${v}/chat`,fetch:Ka,headers:()=>{const p={};return L.current&&(p.Authorization=`Bearer ${L.current}`),p},body:()=>({tools:Tn.map(w=>({name:w.name,description:w.description,inputSchema:w.jsonSchema})),systemPrompt:g,currentRoute:Xn,state:le.current})}),sendAutomaticallyWhen:On.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=He[He.length-1];if(!p||p.role!=="assistant")return;const w=p.parts?.filter(D=>D.type?.startsWith("tool-")&&D.state==="input-available"&&typeof D.toolCallId=="string"&&D.input!==void 0)||[];for(const D of w){const R=D,N=R.type?.replace("tool-","")||"",$=R.toolCallId;if(en.has(N)){if(Jt.has($))continue;qe(_=>_.has($)?_:new Set(_).add($)),(async()=>{try{const _=Sn.get(N);if(!_){console.warn(`[ArctenAgent] Tool ${N} not found in toolsMap. Available tools:`,Array.from(Sn.keys())),vt({toolCallId:$,tool:N,output:`Error: Tool ${N} not found`}),qe(z=>{const J=new Set(z);return J.delete($),J});return}const O=ps(R.input),K=Tn.find(z=>z.name===N);let F;if(K&&K.jsonSchema?.properties){const J=Object.keys(K.jsonSchema.properties).map(je=>O[je]);console.log(`[ArctenAgent] Executing safe tool ${N} with args:`,J),F=await _(...J)}else if(N==="getState")F=_();else if(N==="setState"){const z=O.updates||O;F=await _(z)}else F=await _(...Object.values(O));console.log(`[ArctenAgent] Tool ${N} completed, result:`,F),vt({toolCallId:$,tool:N,output:F}),qe(z=>{const J=new Set(z);return J.delete($),J})}catch(_){console.error(`[ArctenAgent] Error executing safe tool ${N}:`,_),vt({toolCallId:$,tool:N,output:`Error: ${_ instanceof Error?_.message:String(_)}`}),qe(O=>{const K=new Set(O);return K.delete($),K})}})()}}},[He,en,Sn,Tn,vt]),m.useEffect(()=>{if(!W||!L.current)return;(async()=>{Ze(!0),ye(null);try{const D=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,R=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:W},format:"json"})});if(!R.ok){if(R.status===404||R.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${R.status}), using empty state`);const K=G?T||{}:{};le.current=K,G||de(K),b&&b(K),Qe.current=!0,Ze(!1);return}const O=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${R.status} ${O}`)}const $=(await R.json())?.value||{},q=!Qe.current;let _;q?(_={...G?T||{}:{},...$},Qe.current=!0):_=$,le.current=_,G||de(_),b&&b(_)}catch(w){w instanceof TypeError&&w.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",w):console.error("[ArctenAgent] Failed to fetch state:",w);const R=w instanceof Error?w:new Error(String(w));if(ye(R),!Qe.current){const N=G?T||{}:{};le.current=N,G||de(N),b&&b(N),Qe.current=!0}}finally{Ze(!1)}})()},[W,v,G,T,b]),m.useEffect(()=>{Be&&st.current&&st.current.focus()},[Be,He]);function Ga(){kt(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ha(){kt(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Be]),m.useEffect(()=>{Ht.current&&Ht.current.scrollIntoView({behavior:"smooth"})},[He]),m.useEffect(()=>{function p(w){w.key==="Escape"&&(Ie==="streaming"||Ie==="submitted")&&(w.preventDefault(),An())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ie,An]);function Xa(){const p=crypto.randomUUID();we(p),Pn([]),pt([]),Pe(!1)}function jr(p){if(p.preventDefault(),!rt.trim())return;(Ie==="streaming"||Ie==="submitted")&&An();const w=Pr[Math.floor(Math.random()*Pr.length)]||"Thinking...";Hn(w),qa({text:rt}),Xt("")}function Ya(p){const w=p.target.value;Xt(w)}m.useEffect(()=>{if(!nt)return;function p(D){if(Y){const R=D.clientX-be.x,N=D.clientY-be.y;R>=a&&R<=c&&et(R),N>=400&&N<=1e3&&Mt(N)}else{const R=window.innerWidth-D.clientX;R>=a&&R<=c&&et(R)}}function w(){Re(!1),localStorage.setItem("arcten-sidebar-width",ze.toString()),localStorage.setItem("arcten-sidebar-height",tt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[nt,ze,tt,Y,be,a,c]);function Ja(p){p.preventDefault(),Re(!0)}function Za(){Ve(!0),ke(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qa(){Ve(!1),ke(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function kr(){ke(!Ae),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ae))}function ec(p){Y&&(ft(!0),bn({x:p.clientX-be.x,y:p.clientY-be.y}))}return m.useEffect(()=>{if(!Y)return;function p(){Et(w=>{const R=window.innerWidth-50,N=window.innerHeight-50,$=50-ze,q=0,_=Math.max($,Math.min(w.x,R)),O=Math.max(q,Math.min(w.y,N));if(_!==w.x||O!==w.y){const K={x:_,y:O};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(K)),K}return w})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[Y,ze]),m.useEffect(()=>{if(!Gt)return;function p(D){const R=D.clientX-Dt.x,N=D.clientY-Dt.y,$=50,q=window.innerWidth-$,_=window.innerHeight-$,O=$-ze,K=0,F=Math.max(O,Math.min(R,q)),z=Math.max(K,Math.min(N,_));Et({x:F,y:z})}function w(){ft(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(be))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",w)}},[Gt,Dt,be,ze]),wn?se?d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",se]})}):E?d.jsx(Tu,{features:Zh,children:d.jsx(En,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:Y?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:Y?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
20
  ${Y?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
21
  ${Be?"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
22
  ${Y?"border border-border":"border-l border-border"}
23
23
  ${Be?"":"w-[30px]"}
24
- `,style:Be?Y?{width:`${ze}px`,height:Ae?"auto":`${tt}px`,left:`${be.x}px`,top:`${be.y}px`}:{width:`${ze}px`}:void 0,onClick:Be?void 0:Ga,children:Be?d.jsxs(d.Fragment,{children:[!Y&&d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Ja,children:d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),Y&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Re(!0)}}),d.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),ft(!0),bn({x:p.clientX-be.x,y:p.clientY-be.y})},children:d.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),d.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Re(!0)}})]}),d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${Y?"cursor-move":""}`,onMouseDown:Y?ec:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${Y&&Ae?"cursor-pointer":""}`,onClick:Y&&Ae?p=>{p.stopPropagation(),kr()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Xa,"aria-label":"New chat",children:d.jsx(me.Plus,{className:"h-4 w-4"})})}),d.jsx(ct,{children:"Start a new conversation"})]}),d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?Qa:Za,"aria-label":Y?"Dock sidebar":"Float sidebar",children:Y?d.jsx(me.Dock,{className:"h-4 w-4"}):d.jsx(me.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(ct,{children:Y?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?kr:Ha,"aria-label":Y?Ae?"Maximize":"Minimize":"Close sidebar",children:Y?Ae?d.jsx(me.Maximize2,{className:"h-4 w-4"}):d.jsx(me.Minimize2,{className:"h-4 w-4"}):d.jsx(me.X,{className:"h-4 w-4"})})}),d.jsx(ct,{children:Y?Ae?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ae&&d.jsxs(d.Fragment,{children:[S&&z.length>0&&d.jsxs("div",{className:`border-b border-border ${ue?"flex flex-col flex-1":""}`,children:[d.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[d.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),d.jsx(Ln,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ue||Zn(),Pe(!ue)},children:ue?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ue?"flex-1 overflow-y-auto":""}`,children:z.slice(0,ue?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs("button",{type:"button",className:pe(wt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Wa(p),children:[d.jsx("span",{className:"text-xs truncate",children:p.title}),d.jsx("div",{className:"ml-2 flex items-center",children:d.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:za(p.updatedAt)})})]}),d.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:w=>{w.stopPropagation(),_a(p._id)},"aria-label":"Delete conversation",children:d.jsx(me.X,{className:"h-3 w-3"})})]},p._id))})]}),d.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[d.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:He.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&d.jsx("div",{className:"mb-6",children:o}),d.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),P.length>0&&d.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:d.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(V?P:P.slice(0,10)).map(p=>d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Xt(p.sampleUsage),st.current?.focus()},children:p.friendlyName})}),d.jsx(ct,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium",children:p.description}),d.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[d.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&d.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),P.length>10&&!V&&d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsxs(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>I(!0),children:["+",P.length-10," more"]})}),d.jsx(ct,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),d.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:P.slice(10).map(p=>d.jsxs("div",{children:[d.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),d.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),d.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),V&&P.length>10&&d.jsx(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>I(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[He.map(p=>{const D=p.parts.filter(L=>L.type==="text").map(L=>L.text).join("");let R=[],N=new Map,F=[],q,U=!0;if(p.role==="assistant"){const L=p.parts.filter(J=>J.type==="text"&&J.text),K=[],$=[];L.forEach(J=>{const{citations:je,citationMap:xe,groupedCitations:Oe,referencesText:_e}=Xi(J.text);R.push(...je),K.push(xe),Oe&&$.push(...Oe),_e&&(q=_e)}),K.forEach(J=>{J.forEach((je,xe)=>{N.has(xe)||N.set(xe,je)})}),F=Array.from(new Map($.map(J=>[J.url,J])).values()).sort((J,je)=>(J.numbers[0]||0)-(je.numbers[0]||0)),U=!(Ie==="streaming"&&p.id===He.at(-1)?.id)}return d.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:d.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?d.jsx(Qh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:D}):d.jsx("div",{className:"space-y-2",children:p.parts.map((L,K)=>{if(L.type?.startsWith("tool-")){const $=L.type?.replace("tool-","")||"",W=Tn.find(xe=>xe.name===$),J=L.state==="input-available",je=L.state==="output-available";if(J&&en.has($),J){if(en.has($))return null;const xe=ps(L.input);return d.jsx(En,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(nf,{toolName:$,description:W?.description||"",args:xe,onApprove:async()=>{if(Jt.has(L.toolCallId))return;qe(_e=>new Set(_e).add(L.toolCallId));const Oe=Sn.get($);if(Oe)try{const _e=await Oe(...Object.values(xe));vt({toolCallId:L.toolCallId,tool:$,output:_e})}catch(_e){vt({toolCallId:L.toolCallId,tool:$,output:`Error: ${_e}`})}},onDeny:async()=>{Jt.has(L.toolCallId)||(qe(Oe=>new Set(Oe).add(L.toolCallId)),vt({toolCallId:L.toolCallId,tool:$,output:"User denied tool execution"}))}})},`${L.toolCallId}-${K}`)}else if(je){const xe=L.output==="User denied tool execution",Oe=ps(L.input);return d.jsx(sf,{toolName:$,args:Oe,isDenied:xe,isSafe:en.has($)},`${L.toolCallId}-${K}`)}return null}if(L.type==="text"&&L.text&&mt){const{processedText:$}=Xi(L.text),xe=!p.parts.slice(K+1).some(Mr=>Mr.type==="text"&&Mr.text)&&U&&N.size>0,Oe=xe?R:[],_e=xe?N:new Map,tc=xe?F:[],nc=xe?q:void 0;return d.jsx(yf,{text:$,citations:Oe,citationMap:_e,groupedCitations:tc,referencesText:nc,ResponseComponent:mt,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:C,showReferences:xe},`${p.id}-${K}`)}return L.type==="reasoning"&&L.text?d.jsxs(Fa,{className:"w-full",isStreaming:Ie==="streaming"&&K===p.parts.length-1&&p.id===He.at(-1)?.id,children:[d.jsx($a,{}),d.jsx(Ba,{children:L.text})]},`${p.id}-${K}`):null})})})},p.id)}),d.jsx("div",{ref:Ht})]})}),Cr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Cr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(wu,{mode:"wait",children:(Ie==="streaming"||Ie==="submitted")&&d.jsxs(En,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[d.jsx(En,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),d.jsx("p",{className:"text-xs text-muted-foreground",children:Gn})]})}),d.jsxs("form",{onSubmit:jr,className:"relative",children:[d.jsx(Qi,{ref:st,value:rt,onChange:Ya,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),jr(p))}}),Ie==="streaming"||Ie==="submitted"?d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:An,children:d.jsx(me.Square,{className:"h-4 w-4"})})}),d.jsxs(ct,{children:[d.jsx(Nr,{children:"Escape"})," to stop"]})]}):d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"submit",className:pe(wt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!rt.trim(),children:d.jsx(me.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(ct,{children:[d.jsx(Nr,{children:"Enter"})," to send"]})]})]})]})]}),d.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[d.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),d.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),d.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[d.jsx(me.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),d.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function ln(e){if(typeof e=="string")try{const t=JSON.parse(e);return ln(t)}catch{return e}if(Array.isArray(e))return e.map(ln);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=ln(s);return t}return e}function wf(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return ln(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?ln(e):{}}function Tf({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:h,onStateChange:f,allowStateEdits:g=!0,onToolCall:x,onFinish:v,sources:S,ragConfig:T,ragFilters:b}={}){const y=m.useMemo(()=>T!==void 0?T:b?{enabled:!0,filters:b}:S&&S.length>0?{enabled:!0,organizationId:S[0],autoExecute:!0,filters:void 0}:{enabled:!1},[S,T,b]),[M,k]=m.useState(n||null),C=m.useRef(n||null),[A,E]=m.useState(null),[X,O]=m.useState(null),se=m.useRef(null),[ie,ge]=m.useState([]),[Z,re]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[G,Q]=m.useState(!1),[de,le]=m.useState(new Set),ee=h!==void 0,[Ze,jt]=m.useState({}),ye=m.useRef({}),Qe=ee?h||{}:Ze;ee&&h?ye.current=h:ee||(ye.current=Ze);const[Be,kt]=m.useState(!1),[ze,et]=m.useState(null),tt=m.useRef(!1),Mt=m.useCallback(async(P,j=3)=>{if(!Z||!C.current)return;const V=async()=>{const z=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,H=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Z,updates:P},format:"json"})});if(!H.ok){if(H.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const _=await H.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${H.status} ${_}`)}};for(let I=0;I<j;I++)try{await V(),et(null);return}catch(z){if(I===j-1){const _=z instanceof Error?z:new Error(String(z));throw et(_),console.error("Failed to sync state to Convex after retries:",z),_}await new Promise(_=>setTimeout(_,Math.pow(2,I)*100))}},[Z,e,C]),nt=m.useMemo(()=>function(){return ye.current},[]),Re=m.useMemo(()=>async function(j){const V={...ye.current,...j};ye.current=V,ee||jt(V),f&&f(V);try{await Mt(j)}catch(I){throw I}},[Mt,f,ee]);m.useEffect(()=>{ee&&h&&(ye.current=h)},[ee,h]);const Y=m.useMemo(()=>y?.enabled?async function(j,V=20,I){const z={...y.filters,...I};if(S&&S.length>1){const _=S.map(ne=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...C.current?{Authorization:`Bearer ${C.current}`}:{}},body:JSON.stringify({q:j,k:Math.min(V,100),organizationId:ne,...Object.keys(z).length>0?{filters:z}:{}})}).then(te=>te.ok?te.json():null)),we=await Promise.all(_),ue=[];for(const ne of we)ne?.candidates&&ue.push(...ne.candidates);ue.sort((ne,te)=>{const Nt=ne.scores?.rerank||ne.scores?.dense||0;return(te.scores?.rerank||te.scores?.dense||0)-Nt});const Pe=ue.slice(0,V).map((ne,te)=>{const Nt=ne.citation||ne.url;return{rank:te+1,doc_id:ne.doc_id,block_id:ne.block_id,url:ne.url,citation:Nt,title:ne.title||"Untitled",snippet:ne.snippet,score:ne.scores?.rerank||ne.scores?.dense||0,metadata:{site:ne.metadata?.site,lang:ne.metadata?.lang,contentType:ne.metadata?.content_type}}});return{success:!0,query:j,total:ue.length,results:Pe,summary:`Found ${ue.length} relevant results across ${S.length} source(s) for "${j}". Top result: ${Pe[0]?.title||"N/A"}`}}const H=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const _={q:j,k:Math.min(V,100)};H&&(_.organizationId=H),Object.keys(z).length>0&&(_.filters=z);const we={"Content-Type":"application/json"};C.current&&(we.Authorization=`Bearer ${C.current}`);const ue=await fetch(`${e}/search`,{method:"POST",headers:we,body:JSON.stringify(_)});if(!ue.ok){const te=await ue.text();return{success:!1,error:`Search failed: ${ue.status} ${te}`}}const Pe=await ue.json(),ne=Pe.candidates.map((te,Nt)=>{const pt=te.citation||te.url;return{rank:Nt+1,doc_id:te.doc_id,block_id:te.block_id,url:te.url,citation:pt,title:te.title||"Untitled",snippet:te.snippet,score:te.scores?.rerank||te.scores?.dense||0,metadata:{site:te.metadata?.site,lang:te.metadata?.lang,contentType:te.metadata?.content_type}}});return{success:!0,query:Pe.query,total:Pe.total,results:ne,summary:`Found ${Pe.total} relevant results for "${j}". Top result: ${ne[0]?.title||"N/A"}`}}catch(_){return{success:!1,error:_ instanceof Error?_.message:"Unknown error occurred"}}}:null,[y,e,C]),Ve=m.useMemo(()=>y?.enabled?async function(j,V){const I=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const z={"Content-Type":"application/json"};C.current&&(z.Authorization=`Bearer ${C.current}`);const H=await fetch(`${e}/fetch`,{method:"POST",headers:z,body:JSON.stringify({doc_id:j,block_ids:V,...I?{organizationId:I}:{}})});if(!H.ok){const we=await H.text();return{success:!1,error:`Fetch failed: ${H.status} ${we}`}}const _=await H.json();return{success:!0,blocks:_.blocks||[],fullContent:_.fullContent||"",pageUrl:_.pageUrl||"",pageTitle:_.pageTitle||"",summary:`Fetched ${_.blocks?.length||0} blocks from ${_.pageTitle||j}`}}catch(z){return{success:!1,error:z instanceof Error?z.message:"Unknown error occurred"}}}:null,[y,e,C]),Ae=m.useMemo(()=>{const P=[...o,...i,nt];return(!ee||g)&&P.push(Re),y?.enabled&&(Y&&P.push(Y),Ve&&P.push(Ve)),P},[o,i,nt,Re,Y,Ve,y,ee,g]),ke=m.useMemo(()=>Oa(Ae,a),[Ae,a]),be=m.useMemo(()=>{const P=new Map,j=new Map(ke.map(V=>[V.name,V]));return P.set("getState",nt),(!ee||g)&&P.set("setState",Re),y?.enabled&&(Y&&P.set("searchDocs",Y),Ve&&P.set("fetchDocContent",Ve)),Ae.forEach(V=>{if(V===nt||V===Re||V===Y||V===Ve)return;const I=V[We];if(I){const H=j.get(I);if(H){P.set(H.name,V);return}}const z=ke.find(H=>H.name===V.name);z&&P.set(z.name,V)}),P},[Ae,ke,nt,Re,Y,Ve,y,ee,g]),Et=m.useMemo(()=>new Set(ke.map(P=>P.name)),[ke]),Gt=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:[]}}];(!ee||g)&&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 j=[];return y?.enabled&&j.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"]}}),[...ke,...P,...j]},[ke,y,ee,g]),ft=m.useMemo(()=>Gt.filter(P=>P.name==="getState"?!0:P.name==="setState"?!ee||g:y?.enabled&&(P.name==="searchDocs"||P.name==="fetchDocContent")?!0:Et.has(P.name)),[Gt,Et,ee,g,y]),Dt=m.useMemo(()=>{const P=new Set;return P.add("getState"),P.add("setState"),y?.enabled&&y.autoExecute!==!1&&(P.add("searchDocs"),P.add("fetchDocContent")),i.forEach(j=>{for(const[V,I]of be.entries())if(I===j){P.add(V);break}}),P},[i,be,y]);m.useEffect(()=>s||n?void 0:((async()=>{try{const j=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!j.ok)throw new Error("Failed to fetch token");const V=await j.json();k(V.clientToken),C.current=V.clientToken,O(V.expiresAt),E(null)}catch(j){console.error("[useAgent] Token fetch failed:",j),E(j instanceof Error?j.message:"Failed to fetch token")}})(),()=>{se.current&&clearTimeout(se.current)}),[t,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!X||s||n)return;se.current&&clearTimeout(se.current);const P=Math.floor(Date.now()/1e3),j=X-P,I=Math.max(0,j-5);return se.current=setTimeout(async()=>{try{const z=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!z.ok)throw new Error("Failed to refresh token");const H=await z.json();k(H.clientToken),C.current=H.clientToken,O(H.expiresAt),E(null)}catch(z){console.error("[useAgent] Token refresh failed:",z),E(z instanceof Error?z.message:"Failed to refresh token")}},I*1e3),()=>{se.current&&clearTimeout(se.current)}},[X,t,JSON.stringify(r),s,n]);const bn=async(P,j={})=>{const V=j.headers?new Headers(j.headers):new Headers;V.delete("user-agent"),V.delete("User-Agent"),console.log("[useAgent] Making request to:",P),console.log("[useAgent] Method:",j.method||"GET"),console.log("[useAgent] Has Authorization header:",V.has("Authorization")),console.log("[useAgent] Client token available:",!!C.current);try{const I=await fetch(P,{...j,headers:V});if(!I.ok){console.error("[useAgent] Request failed:",I.status,I.statusText);const z=await I.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",z)}return I}catch(I){throw console.error("[useAgent] Fetch error:",I),I}},wn=`${e}/chat`;console.log("[useAgent] Chat API URL:",wn);const{messages:Ue,sendMessage:Ht,status:st,error:rt,stop:Xt,addToolResult:mt,setMessages:Yt}=Yi.useChat({id:Z||void 0,messages:u,transport:new On.DefaultChatTransport({api:wn,fetch:bn,headers:()=>{const P={};return C.current?(P.Authorization=`Bearer ${C.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),P},body:()=>{const P=ft.map(I=>({name:I.name,description:I.description,inputSchema:I.jsonSchema})),j=P.filter(I=>I.name==="getState"||I.name==="setState").map(I=>I.name),V=P.filter(I=>I.name==="searchDocs"||I.name==="fetchDocContent").map(I=>I.name);return j.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",j),V.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",V):y?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:P,systemPrompt:c,state:ye.current,...b&&{ragFilters:b}}}}),sendAutomaticallyWhen:On.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ue.forEach(P=>{P.role==="assistant"&&P.parts.forEach(j=>{if(!j.type?.startsWith("tool-")||j.state!=="input-available")return;const V=j.type.replace("tool-",""),I=j.toolCallId;if(de.has(I))return;le(H=>new Set(H).add(I));const z=wf(j.input);if(Dt.has(V)){const H=be.get(V);H?(async()=>{try{const _=ft.find(ue=>ue.name===V);let we;if(_&&_.jsonSchema?.properties){const Pe=Object.keys(_.jsonSchema.properties).map(ne=>z[ne]);we=await H(...Pe)}else if(V==="getState")we=H();else if(V==="setState"){const ue=z.updates||z;we=await H(ue)}else we=await H(...Object.values(z));mt({toolCallId:I,tool:V,output:we})}catch(_){console.error(`[useAgent] Error executing tool ${V}:`,_),mt({toolCallId:I,tool:V,output:`Error: ${_}`})}})():console.warn(`[useAgent] Tool ${V} not found in toolsMap`)}else x&&x({toolCall:{toolCallId:I,toolName:V,args:z}})})})},[Ue,Dt,be,x,mt,de,Re,ft]),m.useEffect(()=>{if(st==="ready"&&Ue.length>0&&v){const P=Ue[Ue.length-1];P&&P.role==="assistant"&&v({message:P,messages:Ue,isAbort:!1,isDisconnect:!1,isError:!!rt})}},[st,Ue,rt,v]);async function Gn(){if(!(!r?.id||!M)){Q(!0);try{const j=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${M}`}})).json();ge(j.conversations||[])}catch(P){console.error("Failed to fetch conversations:",P)}finally{Q(!1)}}}m.useEffect(()=>{r?.id&&M&&Gn()},[JSON.stringify(r),M,e]),m.useEffect(()=>{if(!Z||!C.current)return;(async()=>{kt(!0),et(null);try{const j=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Z},format:"json"})});if(!j.ok){const z=await j.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${j.status} ${z}`)}const I=(await j.json())?.value||{};ye.current=I,ee||jt(I),f&&f(I),tt.current=!0}catch(j){console.error("Failed to fetch state:",j);const V=j instanceof Error?j:new Error(String(j));et(V),tt.current||(ye.current={},ee?f&&f({}):(jt({}),f&&f({})),tt.current=!0)}finally{kt(!1)}})()},[Z,e,ee,f]);async function Hn(P){re(P),Q(!0);try{const j=await fetch(`${e}/conversations/${P}/messages`,{headers:{Authorization:`Bearer ${C.current}`}});if(!j.ok)throw new Error(`Failed to fetch messages: ${j.statusText}`);const I=(await j.json()).messages||[];Yt(I)}catch(j){console.error("Failed to load conversation messages:",j)}finally{Q(!1)}}async function Jt(P){if(M)try{await fetch(`${e}/conversations/${P}`,{method:"DELETE",headers:{Authorization:`Bearer ${M}`}}),ge(ie.filter(j=>j._id!==P)),P===Z&&qe()}catch(j){console.error("Failed to delete conversation:",j)}}function qe(){const P=crypto.randomUUID();re(P),Yt([]),le(new Set),ye.current={},ee?f&&f({}):(jt({}),f&&f({})),tt.current=!1}function Xn(P){mt(P)}async function Yn(P){const j={...ye.current,...P};ye.current=j,ee||jt(j),f&&f(j);try{await Mt(P)}catch(V){throw V}}return{id:Z,messages:Ue,status:st,error:rt,sendMessage:Ht,stop:Xt,addToolOutput:Xn,setMessages:Yt,conversations:ie,loadConversation:Hn,deleteConversation:Jt,startNewConversation:qe,isLoadingConversations:G,clientToken:M,tokenError:A,state:Qe,setState:Yn,isStateLoading:Be,stateError:ze}}exports.verifyToken=pc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=We;exports.ArctenAgent=bf;exports.preserveToolName=ef;exports.useAgent=Tf;
24
+ `,style:Be?Y?{width:`${ze}px`,height:Ae?"auto":`${tt}px`,left:`${be.x}px`,top:`${be.y}px`}:{width:`${ze}px`}:void 0,onClick:Be?void 0:Ga,children:Be?d.jsxs(d.Fragment,{children:[!Y&&d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Ja,children:d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),Y&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Re(!0)}}),d.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),ft(!0),bn({x:p.clientX-be.x,y:p.clientY-be.y})},children:d.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),d.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Re(!0)}})]}),d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${Y?"cursor-move":""}`,onMouseDown:Y?ec:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${Y&&Ae?"cursor-pointer":""}`,onClick:Y&&Ae?p=>{p.stopPropagation(),kr()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Xa,"aria-label":"New chat",children:d.jsx(me.Plus,{className:"h-4 w-4"})})}),d.jsx(ct,{children:"Start a new conversation"})]}),d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?Qa:Za,"aria-label":Y?"Dock sidebar":"Float sidebar",children:Y?d.jsx(me.Dock,{className:"h-4 w-4"}):d.jsx(me.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(ct,{children:Y?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Y?kr:Ha,"aria-label":Y?Ae?"Maximize":"Minimize":"Close sidebar",children:Y?Ae?d.jsx(me.Maximize2,{className:"h-4 w-4"}):d.jsx(me.Minimize2,{className:"h-4 w-4"}):d.jsx(me.X,{className:"h-4 w-4"})})}),d.jsx(ct,{children:Y?Ae?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ae&&d.jsxs(d.Fragment,{children:[S&&U.length>0&&d.jsxs("div",{className:`border-b border-border ${ue?"flex flex-col flex-1":""}`,children:[d.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[d.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),d.jsx(Ln,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ue||Zn(),Pe(!ue)},children:ue?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ue?"flex-1 overflow-y-auto":""}`,children:U.slice(0,ue?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs("button",{type:"button",className:pe(wt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Wa(p),children:[d.jsx("span",{className:"text-xs truncate",children:p.title}),d.jsx("div",{className:"ml-2 flex items-center",children:d.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:za(p.updatedAt)})})]}),d.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:w=>{w.stopPropagation(),_a(p._id)},"aria-label":"Delete conversation",children:d.jsx(me.X,{className:"h-3 w-3"})})]},p._id))})]}),d.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[d.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:He.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&d.jsx("div",{className:"mb-6",children:o}),d.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),P.length>0&&d.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:d.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(V?P:P.slice(0,10)).map(p=>d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Xt(p.sampleUsage),st.current?.focus()},children:p.friendlyName})}),d.jsx(ct,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium",children:p.description}),d.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[d.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&d.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),P.length>10&&!V&&d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsxs(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>I(!0),children:["+",P.length-10," more"]})}),d.jsx(ct,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),d.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:P.slice(10).map(p=>d.jsxs("div",{children:[d.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),d.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),d.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),V&&P.length>10&&d.jsx(Qn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>I(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[He.map(p=>{const D=p.parts.filter(O=>O.type==="text").map(O=>O.text).join("");let R=[],N=new Map,$=[],q,_=!0;if(p.role==="assistant"){const O=p.parts.filter(J=>J.type==="text"&&J.text),K=[],F=[];O.forEach(J=>{const{citations:je,citationMap:xe,groupedCitations:Oe,referencesText:_e}=Xi(J.text);R.push(...je),K.push(xe),Oe&&F.push(...Oe),_e&&(q=_e)}),K.forEach(J=>{J.forEach((je,xe)=>{N.has(xe)||N.set(xe,je)})}),$=Array.from(new Map(F.map(J=>[J.url,J])).values()).sort((J,je)=>(J.numbers[0]||0)-(je.numbers[0]||0)),_=!(Ie==="streaming"&&p.id===He.at(-1)?.id)}return d.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:d.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?d.jsx(Qh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:D}):d.jsx("div",{className:"space-y-2",children:p.parts.map((F,z)=>({part:F,originalIdx:z})).sort((F,z)=>F.part.timestamp&&z.part.timestamp?F.part.timestamp-z.part.timestamp:F.originalIdx-z.originalIdx).map(({part:F})=>F).map((O,K)=>{if(O.type?.startsWith("tool-")){const F=O.type?.replace("tool-","")||"",z=Tn.find(xe=>xe.name===F),J=O.state==="input-available",je=O.state==="output-available";if(J&&en.has(F),J){if(en.has(F))return null;const xe=ps(O.input);return d.jsx(En,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(nf,{toolName:F,description:z?.description||"",args:xe,onApprove:async()=>{if(Jt.has(O.toolCallId))return;qe(_e=>new Set(_e).add(O.toolCallId));const Oe=Sn.get(F);if(Oe)try{const _e=await Oe(...Object.values(xe));vt({toolCallId:O.toolCallId,tool:F,output:_e})}catch(_e){vt({toolCallId:O.toolCallId,tool:F,output:`Error: ${_e}`})}},onDeny:async()=>{Jt.has(O.toolCallId)||(qe(Oe=>new Set(Oe).add(O.toolCallId)),vt({toolCallId:O.toolCallId,tool:F,output:"User denied tool execution"}))}})},`${O.toolCallId}-${K}`)}else if(je){const xe=O.output==="User denied tool execution",Oe=ps(O.input);return d.jsx(sf,{toolName:F,args:Oe,isDenied:xe,isSafe:en.has(F)},`${O.toolCallId}-${K}`)}return null}if(O.type==="text"&&O.text&&mt){const{processedText:F}=Xi(O.text),xe=!p.parts.slice(K+1).some(Mr=>Mr.type==="text"&&Mr.text)&&_&&N.size>0,Oe=xe?R:[],_e=xe?N:new Map,tc=xe?$:[],nc=xe?q:void 0;return d.jsx(yf,{text:F,citations:Oe,citationMap:_e,groupedCitations:tc,referencesText:nc,ResponseComponent:mt,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:C,showReferences:xe},`${p.id}-${K}`)}return O.type==="reasoning"&&O.text?d.jsxs(Fa,{className:"w-full",isStreaming:Ie==="streaming"&&K===p.parts.length-1&&p.id===He.at(-1)?.id,children:[d.jsx($a,{}),d.jsx(Ba,{children:O.text})]},`${p.id}-${K}`):null})})})},p.id)}),d.jsx("div",{ref:Ht})]})}),Cr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Cr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(wu,{mode:"wait",children:(Ie==="streaming"||Ie==="submitted")&&d.jsxs(En,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[d.jsx(En,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),d.jsx("p",{className:"text-xs text-muted-foreground",children:Gn})]})}),d.jsxs("form",{onSubmit:jr,className:"relative",children:[d.jsx(Qi,{ref:st,value:rt,onChange:Ya,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),jr(p))}}),Ie==="streaming"||Ie==="submitted"?d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"button",className:pe(wt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:An,children:d.jsx(me.Square,{className:"h-4 w-4"})})}),d.jsxs(ct,{children:[d.jsx(Nr,{children:"Escape"})," to stop"]})]}):d.jsxs(ot,{children:[d.jsx(at,{asChild:!0,children:d.jsx("button",{type:"submit",className:pe(wt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!rt.trim(),children:d.jsx(me.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(ct,{children:[d.jsx(Nr,{children:"Enter"})," to send"]})]})]})]})]}),d.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[d.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),d.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),d.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[d.jsx(me.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),d.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function ln(e){if(typeof e=="string")try{const t=JSON.parse(e);return ln(t)}catch{return e}if(Array.isArray(e))return e.map(ln);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=ln(s);return t}return e}function wf(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return ln(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?ln(e):{}}function Tf({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:h,onStateChange:f,allowStateEdits:g=!0,onToolCall:x,onFinish:v,sources:S,ragConfig:T,ragFilters:b}={}){const y=m.useMemo(()=>T!==void 0?T:b?{enabled:!0,filters:b}:S&&S.length>0?{enabled:!0,organizationId:S[0],autoExecute:!0,filters:void 0}:{enabled:!1},[S,T,b]),[M,k]=m.useState(n||null),C=m.useRef(n||null),[A,E]=m.useState(null),[X,L]=m.useState(null),se=m.useRef(null),[ie,ge]=m.useState([]),[Z,re]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[G,Q]=m.useState(!1),[de,le]=m.useState(new Set),ee=h!==void 0,[Ze,jt]=m.useState({}),ye=m.useRef({}),Qe=ee?h||{}:Ze;ee&&h?ye.current=h:ee||(ye.current=Ze);const[Be,kt]=m.useState(!1),[ze,et]=m.useState(null),tt=m.useRef(!1),Mt=m.useCallback(async(P,j=3)=>{if(!Z||!C.current)return;const V=async()=>{const U=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,H=await fetch(U,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Z,updates:P},format:"json"})});if(!H.ok){if(H.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const W=await H.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${H.status} ${W}`)}};for(let I=0;I<j;I++)try{await V(),et(null);return}catch(U){if(I===j-1){const W=U instanceof Error?U:new Error(String(U));throw et(W),console.error("Failed to sync state to Convex after retries:",U),W}await new Promise(W=>setTimeout(W,Math.pow(2,I)*100))}},[Z,e,C]),nt=m.useMemo(()=>function(){return ye.current},[]),Re=m.useMemo(()=>async function(j){const V={...ye.current,...j};ye.current=V,ee||jt(V),f&&f(V);try{await Mt(j)}catch(I){throw I}},[Mt,f,ee]);m.useEffect(()=>{ee&&h&&(ye.current=h)},[ee,h]);const Y=m.useMemo(()=>y?.enabled?async function(j,V=20,I){const U={...y.filters,...I};if(S&&S.length>1){const W=S.map(ne=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...C.current?{Authorization:`Bearer ${C.current}`}:{}},body:JSON.stringify({q:j,k:Math.min(V,100),organizationId:ne,...Object.keys(U).length>0?{filters:U}:{}})}).then(te=>te.ok?te.json():null)),we=await Promise.all(W),ue=[];for(const ne of we)ne?.candidates&&ue.push(...ne.candidates);ue.sort((ne,te)=>{const Nt=ne.scores?.rerank||ne.scores?.dense||0;return(te.scores?.rerank||te.scores?.dense||0)-Nt});const Pe=ue.slice(0,V).map((ne,te)=>{const Nt=ne.citation||ne.url;return{rank:te+1,doc_id:ne.doc_id,block_id:ne.block_id,url:ne.url,citation:Nt,title:ne.title||"Untitled",snippet:ne.snippet,score:ne.scores?.rerank||ne.scores?.dense||0,metadata:{site:ne.metadata?.site,lang:ne.metadata?.lang,contentType:ne.metadata?.content_type}}});return{success:!0,query:j,total:ue.length,results:Pe,summary:`Found ${ue.length} relevant results across ${S.length} source(s) for "${j}". Top result: ${Pe[0]?.title||"N/A"}`}}const H=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const W={q:j,k:Math.min(V,100)};H&&(W.organizationId=H),Object.keys(U).length>0&&(W.filters=U);const we={"Content-Type":"application/json"};C.current&&(we.Authorization=`Bearer ${C.current}`);const ue=await fetch(`${e}/search`,{method:"POST",headers:we,body:JSON.stringify(W)});if(!ue.ok){const te=await ue.text();return{success:!1,error:`Search failed: ${ue.status} ${te}`}}const Pe=await ue.json(),ne=Pe.candidates.map((te,Nt)=>{const pt=te.citation||te.url;return{rank:Nt+1,doc_id:te.doc_id,block_id:te.block_id,url:te.url,citation:pt,title:te.title||"Untitled",snippet:te.snippet,score:te.scores?.rerank||te.scores?.dense||0,metadata:{site:te.metadata?.site,lang:te.metadata?.lang,contentType:te.metadata?.content_type}}});return{success:!0,query:Pe.query,total:Pe.total,results:ne,summary:`Found ${Pe.total} relevant results for "${j}". Top result: ${ne[0]?.title||"N/A"}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[y,e,C]),Ve=m.useMemo(()=>y?.enabled?async function(j,V){const I=y.organizationId&&y.organizationId!=="default"?y.organizationId:S&&S.length>0?S[0]:void 0;try{const U={"Content-Type":"application/json"};C.current&&(U.Authorization=`Bearer ${C.current}`);const H=await fetch(`${e}/fetch`,{method:"POST",headers:U,body:JSON.stringify({doc_id:j,block_ids:V,...I?{organizationId:I}:{}})});if(!H.ok){const we=await H.text();return{success:!1,error:`Fetch failed: ${H.status} ${we}`}}const W=await H.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||j}`}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Unknown error occurred"}}}:null,[y,e,C]),Ae=m.useMemo(()=>{const P=[...o,...i,nt];return(!ee||g)&&P.push(Re),y?.enabled&&(Y&&P.push(Y),Ve&&P.push(Ve)),P},[o,i,nt,Re,Y,Ve,y,ee,g]),ke=m.useMemo(()=>Oa(Ae,a),[Ae,a]),be=m.useMemo(()=>{const P=new Map,j=new Map(ke.map(V=>[V.name,V]));return P.set("getState",nt),(!ee||g)&&P.set("setState",Re),y?.enabled&&(Y&&P.set("searchDocs",Y),Ve&&P.set("fetchDocContent",Ve)),Ae.forEach(V=>{if(V===nt||V===Re||V===Y||V===Ve)return;const I=V[We];if(I){const H=j.get(I);if(H){P.set(H.name,V);return}}const U=ke.find(H=>H.name===V.name);U&&P.set(U.name,V)}),P},[Ae,ke,nt,Re,Y,Ve,y,ee,g]),Et=m.useMemo(()=>new Set(ke.map(P=>P.name)),[ke]),Gt=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:[]}}];(!ee||g)&&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 j=[];return y?.enabled&&j.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"]}}),[...ke,...P,...j]},[ke,y,ee,g]),ft=m.useMemo(()=>Gt.filter(P=>P.name==="getState"?!0:P.name==="setState"?!ee||g:y?.enabled&&(P.name==="searchDocs"||P.name==="fetchDocContent")?!0:Et.has(P.name)),[Gt,Et,ee,g,y]),Dt=m.useMemo(()=>{const P=new Set;return P.add("getState"),P.add("setState"),y?.enabled&&y.autoExecute!==!1&&(P.add("searchDocs"),P.add("fetchDocContent")),i.forEach(j=>{for(const[V,I]of be.entries())if(I===j){P.add(V);break}}),P},[i,be,y]);m.useEffect(()=>s||n?void 0:((async()=>{try{const j=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!j.ok)throw new Error("Failed to fetch token");const V=await j.json();k(V.clientToken),C.current=V.clientToken,L(V.expiresAt),E(null)}catch(j){console.error("[useAgent] Token fetch failed:",j),E(j instanceof Error?j.message:"Failed to fetch token")}})(),()=>{se.current&&clearTimeout(se.current)}),[t,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!X||s||n)return;se.current&&clearTimeout(se.current);const P=Math.floor(Date.now()/1e3),j=X-P,I=Math.max(0,j-5);return se.current=setTimeout(async()=>{try{const U=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!U.ok)throw new Error("Failed to refresh token");const H=await U.json();k(H.clientToken),C.current=H.clientToken,L(H.expiresAt),E(null)}catch(U){console.error("[useAgent] Token refresh failed:",U),E(U instanceof Error?U.message:"Failed to refresh token")}},I*1e3),()=>{se.current&&clearTimeout(se.current)}},[X,t,JSON.stringify(r),s,n]);const bn=async(P,j={})=>{const V=j.headers?new Headers(j.headers):new Headers;V.delete("user-agent"),V.delete("User-Agent"),console.log("[useAgent] Making request to:",P),console.log("[useAgent] Method:",j.method||"GET"),console.log("[useAgent] Has Authorization header:",V.has("Authorization")),console.log("[useAgent] Client token available:",!!C.current);try{const I=await fetch(P,{...j,headers:V});if(!I.ok){console.error("[useAgent] Request failed:",I.status,I.statusText);const U=await I.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",U)}return I}catch(I){throw console.error("[useAgent] Fetch error:",I),I}},wn=`${e}/chat`;console.log("[useAgent] Chat API URL:",wn);const{messages:Ue,sendMessage:Ht,status:st,error:rt,stop:Xt,addToolResult:mt,setMessages:Yt}=Yi.useChat({id:Z||void 0,messages:u,transport:new On.DefaultChatTransport({api:wn,fetch:bn,headers:()=>{const P={};return C.current?(P.Authorization=`Bearer ${C.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),P},body:()=>{const P=ft.map(I=>({name:I.name,description:I.description,inputSchema:I.jsonSchema})),j=P.filter(I=>I.name==="getState"||I.name==="setState").map(I=>I.name),V=P.filter(I=>I.name==="searchDocs"||I.name==="fetchDocContent").map(I=>I.name);return j.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",j),V.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",V):y?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:P,systemPrompt:c,state:ye.current,...b&&{ragFilters:b}}}}),sendAutomaticallyWhen:On.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ue.forEach(P=>{P.role==="assistant"&&P.parts.forEach(j=>{if(!j.type?.startsWith("tool-")||j.state!=="input-available")return;const V=j.type.replace("tool-",""),I=j.toolCallId;if(de.has(I))return;le(H=>new Set(H).add(I));const U=wf(j.input);if(Dt.has(V)){const H=be.get(V);H?(async()=>{try{const W=ft.find(ue=>ue.name===V);let we;if(W&&W.jsonSchema?.properties){const Pe=Object.keys(W.jsonSchema.properties).map(ne=>U[ne]);we=await H(...Pe)}else if(V==="getState")we=H();else if(V==="setState"){const ue=U.updates||U;we=await H(ue)}else we=await H(...Object.values(U));mt({toolCallId:I,tool:V,output:we})}catch(W){console.error(`[useAgent] Error executing tool ${V}:`,W),mt({toolCallId:I,tool:V,output:`Error: ${W}`})}})():console.warn(`[useAgent] Tool ${V} not found in toolsMap`)}else x&&x({toolCall:{toolCallId:I,toolName:V,args:U}})})})},[Ue,Dt,be,x,mt,de,Re,ft]),m.useEffect(()=>{if(st==="ready"&&Ue.length>0&&v){const P=Ue[Ue.length-1];P&&P.role==="assistant"&&v({message:P,messages:Ue,isAbort:!1,isDisconnect:!1,isError:!!rt})}},[st,Ue,rt,v]);async function Gn(){if(!(!r?.id||!M)){Q(!0);try{const j=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${M}`}})).json();ge(j.conversations||[])}catch(P){console.error("Failed to fetch conversations:",P)}finally{Q(!1)}}}m.useEffect(()=>{r?.id&&M&&Gn()},[JSON.stringify(r),M,e]),m.useEffect(()=>{if(!Z||!C.current)return;(async()=>{kt(!0),et(null);try{const j=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Z},format:"json"})});if(!j.ok){const U=await j.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${j.status} ${U}`)}const I=(await j.json())?.value||{};ye.current=I,ee||jt(I),f&&f(I),tt.current=!0}catch(j){console.error("Failed to fetch state:",j);const V=j instanceof Error?j:new Error(String(j));et(V),tt.current||(ye.current={},ee?f&&f({}):(jt({}),f&&f({})),tt.current=!0)}finally{kt(!1)}})()},[Z,e,ee,f]);async function Hn(P){re(P),Q(!0);try{const j=await fetch(`${e}/conversations/${P}/messages`,{headers:{Authorization:`Bearer ${C.current}`}});if(!j.ok)throw new Error(`Failed to fetch messages: ${j.statusText}`);const I=(await j.json()).messages||[];Yt(I)}catch(j){console.error("Failed to load conversation messages:",j)}finally{Q(!1)}}async function Jt(P){if(M)try{await fetch(`${e}/conversations/${P}`,{method:"DELETE",headers:{Authorization:`Bearer ${M}`}}),ge(ie.filter(j=>j._id!==P)),P===Z&&qe()}catch(j){console.error("Failed to delete conversation:",j)}}function qe(){const P=crypto.randomUUID();re(P),Yt([]),le(new Set),ye.current={},ee?f&&f({}):(jt({}),f&&f({})),tt.current=!1}function Xn(P){mt(P)}async function Yn(P){const j={...ye.current,...P};ye.current=j,ee||jt(j),f&&f(j);try{await Mt(P)}catch(V){throw V}}return{id:Z,messages:Ue,status:st,error:rt,sendMessage:Ht,stop:Xt,addToolOutput:Xn,setMessages:Yt,conversations:ie,loadConversation:Hn,deleteConversation:Jt,startNewConversation:qe,isLoadingConversations:G,clientToken:M,tokenError:A,state:Qe,setState:Yn,isStateLoading:Be,stateError:ze}}exports.verifyToken=pc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=We;exports.ArctenAgent=bf;exports.preserveToolName=ef;exports.useAgent=Tf;