@arcteninc/core 0.0.91 → 0.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var ec=Object.create;var Dr=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var sc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,ic=Object.prototype.hasOwnProperty;var oc=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sc(e))!ic.call(t,r)&&r!==n&&Dr(t,r,{get:()=>e[r],enumerable:!(s=nc(e,r))||s.enumerable});return t};var ac=(t,e,n)=>(n=t!=null?ec(rc(t)):{},oc(e||!t||!t.__esModule?Dr(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),gt=require("lucide-react"),Ji=require("@ai-sdk/react"),Ln=require("ai"),Zi=require("@radix-ui/react-slot"),Qi=require("class-variance-authority"),cc=require("clsx"),lc=require("tailwind-merge"),uc=require("@radix-ui/react-tooltip"),Nr=require("@radix-ui/react-use-controllable-state"),dc=require("@radix-ui/react-collapsible"),hc=require("react-dom"),fc=require("./server.cjs");function Bs(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Ft=Bs(m),Be=Bs(uc),zs=Bs(dc);function yt(...t){return lc.twMerge(cc.clsx(t))}const Te=Qi.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Fn=Ft.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Zi.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:yt(Te({variant:e,size:n,className:t})),...r})});Fn.displayName="Button";const mc=Qi.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function ts({className:t,variant:e,asChild:n=!1,...s}){const r=n?Zi.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:yt(mc({variant:e}),t),...s})}const pc=({textAreaRef:t,triggerAutoSize:e,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ft.useState(!0);Ft.useEffect(()=>{const a=t.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[t.current,e])},to=Ft.forwardRef(({maxHeight:t=Number.MAX_SAFE_INTEGER,minHeight:e=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ft.useRef(null),[c,u]=Ft.useState("");return pc({textAreaRef:a,triggerAutoSize:c,maxHeight:t,minHeight:e}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:t,minHeight:e})),Ft.useEffect(()=>{u(r)},[o?.defaultValue,r]),d.jsx("textarea",{...o,value:r,ref:a,className:yt("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:l=>{u(l.target.value),s?.(l)}})});to.displayName="AutosizeTextarea";function gc({delayDuration:t=0,...e}){return d.jsx(Be.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function ae({...t}){return d.jsx(gc,{children:d.jsx(Be.Root,{"data-slot":"tooltip",...t})})}function ce({...t}){return d.jsx(Be.Trigger,{"data-slot":"tooltip-trigger",...t})}function le({className:t,sideOffset:e=0,children:n,...s}){return d.jsx(Be.Portal,{children:d.jsxs(Be.Content,{"data-slot":"tooltip-content",sideOffset:e,className:yt("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...s,children:[n,d.jsx(Be.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Rr({className:t,...e}){return d.jsx("kbd",{"data-slot":"kbd",className:yt("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",t),...e})}const Us=m.createContext({});function _s(t){const e=m.useRef(null);return e.current===null&&(e.current=t()),e.current}const Ws=typeof window<"u",eo=Ws?m.useLayoutEffect:m.useEffect,Wn=m.createContext(null);function Ks(t,e){t.indexOf(e)===-1&&t.push(e)}function qs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Ht=(t,e,n)=>n>e?e:n<t?t:n;function ys(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let We=()=>{},Xt=()=>{};process.env.NODE_ENV!=="production"&&(We=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(ys(e,n))},Xt=(t,e,n)=>{if(!t)throw new Error(ys(e,n))});const Yt={},no=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function so(t){return typeof t=="object"&&t!==null}const ro=t=>/^0[^.\s]+$/u.test(t);function Gs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Rt=t=>t,yc=(t,e)=>n=>e(t(n)),yn=(...t)=>t.reduce(yc),dn=(t,e,n)=>{const s=e-t;return s===0?1:(n-t)/s};class Hs{constructor(){this.subscriptions=[]}add(e){return Ks(this.subscriptions,e),()=>qs(this.subscriptions,e)}notify(e,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(e,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $t=t=>t*1e3,Nt=t=>t/1e3;function io(t,e){return e?t*(1e3/e):0}const Vr=new Set;function Xs(t,e,n){t||Vr.has(e)||(console.warn(ys(e,n)),Vr.add(e))}const oo=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,xc=1e-7,vc=12;function bc(t,e,n,s,r){let o,i,a=0;do i=e+(n-e)/2,o=oo(i,s,r)-t,o>0?n=i:e=i;while(Math.abs(o)>xc&&++a<vc);return i}function xn(t,e,n,s){if(t===e&&n===s)return Rt;const r=o=>bc(o,0,1,t,n);return o=>o===0||o===1?o:oo(r(o),e,s)}const ao=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,co=t=>e=>1-t(1-e),lo=xn(.33,1.53,.69,.99),Ys=co(lo),uo=ao(Ys),ho=t=>(t*=2)<1?.5*Ys(t):.5*(2-Math.pow(2,-10*(t-1))),Js=t=>1-Math.sin(Math.acos(t)),fo=co(Js),mo=ao(Js),wc=xn(.42,0,1,1),Tc=xn(0,0,.58,1),po=xn(.42,0,.58,1),Sc=t=>Array.isArray(t)&&typeof t[0]!="number",go=t=>Array.isArray(t)&&typeof t[0]=="number",Ir={linear:Rt,easeIn:wc,easeInOut:po,easeOut:Tc,circIn:Js,circInOut:mo,circOut:fo,backIn:Ys,backInOut:uo,backOut:lo,anticipate:ho},Ac=t=>typeof t=="string",Or=t=>{if(go(t)){Xt(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,s,r]=t;return xn(e,n,s,r)}else if(Ac(t))return Xt(Ir[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Ir[t];return t},jn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Cc(t,e){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(l){i.has(l)&&(u.schedule(l),t()),l(a)}const u={schedule:(l,h=!1,f=!1)=>{const 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 Pc=40;function yo(t,e){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=jn.reduce((v,k)=>(v[k]=Cc(o),v),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:x}=i,y=()=>{const v=Yt.useManualTiming?r.timestamp:performance.now();n=!1,Yt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(v-r.timestamp,Pc),1)),r.timestamp=v,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),x.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(y))},S=()=>{n=!0,s=!0,r.isProcessing||t(y)};return{schedule:jn.reduce((v,k)=>{const V=i[k];return v[k]=(E,D=!1,A=!1)=>(n||S(),V.schedule(E,D,A)),v},{}),cancel:v=>{for(let k=0;k<jn.length;k++)i[jn[k]].cancel(v)},state:r,steps:i}}const{schedule:ot,cancel:de,state:vt,steps:es}=yo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Rt,!0);let Nn;function jc(){Nn=void 0}const jt={now:()=>(Nn===void 0&&jt.set(vt.isProcessing||Yt.useManualTiming?vt.timestamp:performance.now()),Nn),set:t=>{Nn=t,queueMicrotask(jc)}},xo=t=>e=>typeof e=="string"&&e.startsWith(t),Zs=xo("--"),Mc=xo("var(--"),Qs=t=>Mc(t)?kc.test(t.split("/*")[0].trim()):!1,kc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ke={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},hn={...Ke,transform:t=>Ht(0,1,t)},Mn={...Ke,default:1},rn=t=>Math.round(t*1e5)/1e5,tr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ec(t){return t==null}const Dc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,er=(t,e)=>n=>!!(typeof n=="string"&&Dc.test(n)&&n.startsWith(t)||e&&!Ec(n)&&Object.prototype.hasOwnProperty.call(n,e)),vo=(t,e,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(tr);return{[t]:parseFloat(r),[e]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Nc=t=>Ht(0,255,t),ns={...Ke,transform:t=>Math.round(Nc(t))},Ae={test:er("rgb","red"),parse:vo("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+ns.transform(t)+", "+ns.transform(e)+", "+ns.transform(n)+", "+rn(hn.transform(s))+")"};function Rc(t){let e="",n="",s="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,s+=s,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const xs={test:er("#"),parse:Rc,transform:Ae.transform},vn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),ue=vn("deg"),Wt=vn("%"),z=vn("px"),Vc=vn("vh"),Ic=vn("vw"),Lr={...Wt,parse:t=>Wt.parse(t)/100,transform:t=>Wt.transform(t*100)},Ve={test:er("hsl","hue"),parse:vo("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+Wt.transform(rn(e))+", "+Wt.transform(rn(n))+", "+rn(hn.transform(s))+")"},pt={test:t=>Ae.test(t)||xs.test(t)||Ve.test(t),parse:t=>Ae.test(t)?Ae.parse(t):Ve.test(t)?Ve.parse(t):xs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ae.transform(t):Ve.transform(t),getAnimatableNone:t=>{const e=pt.parse(t);return e.alpha=0,pt.transform(e)}},Oc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Lc(t){return isNaN(t)&&typeof t=="string"&&(t.match(tr)?.length||0)+(t.match(Oc)?.length||0)>0}const bo="number",wo="color",Fc="var",$c="var(",Fr="${}",Bc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function fn(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=e.replace(Bc,c=>(pt.test(c)?(s.color.push(o),r.push(wo),n.push(pt.parse(c))):c.startsWith($c)?(s.var.push(o),r.push(Fc),n.push(c)):(s.number.push(o),r.push(bo),n.push(parseFloat(c))),++o,Fr)).split(Fr);return{values:n,split:a,indexes:s,types:r}}function To(t){return fn(t).values}function So(t){const{split:e,types:n}=fn(t),s=e.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=e[i],r[i]!==void 0){const a=n[i];a===bo?o+=rn(r[i]):a===wo?o+=pt.transform(r[i]):o+=r[i]}return o}}const zc=t=>typeof t=="number"?0:pt.test(t)?pt.getAnimatableNone(t):t;function Uc(t){const e=To(t);return So(t)(e.map(zc))}const he={test:Lc,parse:To,createTransformer:So,getAnimatableNone:Uc};function ss(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function _c({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,e/=100,n/=100;let r=0,o=0,i=0;if(!e)r=o=i=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=ss(c,a,t+1/3),o=ss(c,a,t),i=ss(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function $n(t,e){return n=>n>0?e:t}const ct=(t,e,n)=>t+(e-t)*n,rs=(t,e,n)=>{const s=t*t,r=n*(e*e-s)+s;return r<0?0:Math.sqrt(r)},Wc=[xs,Ae,Ve],Kc=t=>Wc.find(e=>e.test(t));function $r(t){const e=Kc(t);if(We(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let n=e.parse(t);return e===Ve&&(n=_c(n)),n}const Br=(t,e)=>{const n=$r(t),s=$r(e);if(!n||!s)return $n(t,e);const r={...n};return o=>(r.red=rs(n.red,s.red,o),r.green=rs(n.green,s.green,o),r.blue=rs(n.blue,s.blue,o),r.alpha=ct(n.alpha,s.alpha,o),Ae.transform(r))},vs=new Set(["none","hidden"]);function qc(t,e){return vs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Gc(t,e){return n=>ct(t,e,n)}function nr(t){return typeof t=="number"?Gc:typeof t=="string"?Qs(t)?$n:pt.test(t)?Br:Yc:Array.isArray(t)?Ao:typeof t=="object"?pt.test(t)?Br:Hc:$n}function Ao(t,e){const n=[...t],s=n.length,r=t.map((o,i)=>nr(o)(o,e[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Hc(t,e){const n={...t,...e},s={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(s[r]=nr(t[r])(t[r],e[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Xc(t,e){const n=[],s={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const o=e.types[r],i=t.indexes[o][s[o]],a=t.values[i]??0;n[r]=a,s[o]++}return n}const Yc=(t,e)=>{const n=he.createTransformer(e),s=fn(t),r=fn(e);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?vs.has(t)&&!r.values.length||vs.has(e)&&!s.values.length?qc(t,e):yn(Ao(Xc(s,r),r.values),n):(We(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),$n(t,e))};function Co(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ct(t,e,n):nr(t)(t,e)}const Jc=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ot.update(e,n),stop:()=>de(e),now:()=>vt.isProcessing?vt.timestamp:jt.now()}},Po=(t,e,n=10)=>{let s="";const r=Math.max(Math.round(e/n),2);for(let o=0;o<r;o++)s+=Math.round(t(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},Bn=2e4;function sr(t){let e=0;const n=50;let s=t.next(e);for(;!s.done&&e<Bn;)e+=n,s=t.next(e);return e>=Bn?1/0:e}function Zc(t,e=100,n){const s=n({...t,keyframes:[0,e]}),r=Math.min(sr(s),Bn);return{type:"keyframes",ease:o=>s.next(r*o).value/e,duration:Nt(r)}}const Qc=5;function jo(t,e,n){const s=Math.max(e-Qc,0);return io(n-t(s),e-s)}const at={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},is=.001;function tl({duration:t=at.duration,bounce:e=at.bounce,velocity:n=at.velocity,mass:s=at.mass}){let r,o;We(t<=$t(at.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-e;i=Ht(at.minDamping,at.maxDamping,i),t=Ht(at.minDuration,at.maxDuration,Nt(t)),i<1?(r=u=>{const l=u*i,h=l*t,f=l-n,g=bs(u,i),x=Math.exp(-h);return is-f/g*x},o=u=>{const h=u*i*t,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*t,x=Math.exp(-h),y=bs(Math.pow(u,2),i);return(-r(u)+is>0?-1:1)*((f-g)*x)/y}):(r=u=>{const l=Math.exp(-u*t),h=(u-n)*t+1;return-is+l*h},o=u=>{const l=Math.exp(-u*t),h=(n-u)*(t*t);return l*h});const a=5/t,c=nl(r,o,a);if(t=$t(t),isNaN(c))return{stiffness:at.stiffness,damping:at.damping,duration:t};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:t}}}const el=12;function nl(t,e,n){let s=n;for(let r=1;r<el;r++)s=s-t(s)/e(s);return s}function bs(t,e){return t*Math.sqrt(1-e*e)}const sl=["duration","bounce"],rl=["stiffness","damping","mass"];function zr(t,e){return e.some(n=>t[n]!==void 0)}function il(t){let e={velocity:at.velocity,stiffness:at.stiffness,damping:at.damping,mass:at.mass,isResolvedFromDuration:!1,...t};if(!zr(t,rl)&&zr(t,sl))if(t.visualDuration){const n=t.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Ht(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:at.mass,stiffness:r,damping:o}}else{const n=tl(t);e={...e,...n,mass:at.mass},e.isResolvedFromDuration=!0}return e}function zn(t=at.visualDuration,e=at.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:l,duration:h,velocity:f,isResolvedFromDuration:g}=il({...n,velocity:-Nt(n.velocity||0)}),x=f||0,y=u/(2*Math.sqrt(c*l)),S=i-o,T=Nt(Math.sqrt(c/l)),w=Math.abs(S)<5;s||(s=w?at.restSpeed.granular:at.restSpeed.default),r||(r=w?at.restDelta.granular:at.restDelta.default);let v;if(y<1){const V=bs(T,y);v=E=>{const D=Math.exp(-y*T*E);return i-D*((x+y*T*S)/V*Math.sin(V*E)+S*Math.cos(V*E))}}else if(y===1)v=V=>i-Math.exp(-T*V)*(S+(x+T*S)*V);else{const V=T*Math.sqrt(y*y-1);v=E=>{const D=Math.exp(-y*T*E),A=Math.min(V*E,300);return i-D*((x+y*T*S)*Math.sinh(A)+V*S*Math.cosh(A))/V}}const k={calculatedDuration:g&&h||null,next:V=>{const E=v(V);if(g)a.done=V>=h;else{let D=V===0?x:0;y<1&&(D=V===0?$t(x):jo(v,V,E));const A=Math.abs(D)<=s,F=Math.abs(i-E)<=r;a.done=A&&F}return a.value=a.done?i:E,a},toString:()=>{const V=Math.min(sr(k),Bn),E=Po(D=>k.next(V*D).value,V,30);return V+"ms "+E},toTransition:()=>{}};return k}zn.applyToOptions=t=>{const e=Zc(t,100,zn);return t.ease=e.ease,t.duration=$t(e.duration),t.type="keyframes",t};function ws({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:l}){const h=t[0],f={done:!1,value:h},g=A=>a!==void 0&&A<a||c!==void 0&&A>c,x=A=>a===void 0?c:c===void 0||Math.abs(a-A)<Math.abs(c-A)?a:c;let y=n*e;const S=h+y,T=i===void 0?S:i(S);T!==S&&(y=T-h);const w=A=>-y*Math.exp(-A/s),v=A=>T+w(A),k=A=>{const F=w(A),M=v(A);f.done=Math.abs(F)<=u,f.value=f.done?T:M};let V,E;const D=A=>{g(f.value)&&(V=A,E=zn({keyframes:[f.value,x(f.value)],velocity:jo(v,A,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return D(0),{calculatedDuration:null,next:A=>{let F=!1;return!E&&V===void 0&&(F=!0,k(A),D(A)),V!==void 0&&A>=V?E.next(A-V):(!F&&k(A),f)}}}function ol(t,e,n){const s=[],r=n||Yt.mix||Co,o=t.length-1;for(let i=0;i<o;i++){let a=r(t[i],t[i+1]);if(e){const c=Array.isArray(e)?e[i]||Rt:e;a=yn(c,a)}s.push(a)}return s}function al(t,e,{clamp:n=!0,ease:s,mixer:r}={}){const o=t.length;if(Xt(o===e.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const i=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=ol(e,s,r),c=a.length,u=l=>{if(i&&l<t[0])return e[0];let h=0;if(c>1)for(;h<t.length-2&&!(l<t[h+1]);h++);const f=dn(t[h],t[h+1],l);return a[h](f)};return n?l=>u(Ht(t[0],t[o-1],l)):u}function cl(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const r=dn(0,e,s);t.push(ct(n,1,r))}}function ll(t){const e=[0];return cl(e,t.length-1),e}function ul(t,e){return t.map(n=>n*e)}function dl(t,e){return t.map(()=>e||po).splice(0,t.length-1)}function Ie({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const r=Sc(s)?s.map(Or):Or(s),o={done:!1,value:e[0]},i=ul(n&&n.length===e.length?n:ll(e),t),a=al(i,e,{ease:Array.isArray(r)?r:dl(e,r)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const hl=t=>t!==null;function rr(t,{repeat:e,repeatType:n="loop"},s,r=1){const o=t.filter(hl),a=r<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const fl={decay:ws,inertia:ws,tween:Ie,keyframes:Ie,spring:zn};function Mo(t){typeof t.type=="string"&&(t.type=fl[t.type])}class ir{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const ml=t=>t/100;class or extends ir{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==jt.now()&&this.tick(jt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Mo(e);const{type:n=Ie,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=e;let{keyframes:a}=e;const c=n||Ie;process.env.NODE_ENV!=="production"&&c!==Ie&&Xt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Ie&&typeof a[0]!="number"&&(this.mixKeyframes=yn(ml,Co(a[0],a[1])),a=[0,100]);const u=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=sr(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:h,repeatType:f,repeatDelay:g,type:x,onUpdate:y,finalKeyframe:S}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const T=this.currentTime-u*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?T<0:T>r;this.currentTime=Math.max(T,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,k=s;if(h){const A=Math.min(this.currentTime,r)/a;let F=Math.floor(A),M=A%1;!M&&A>=1&&(M=1),M===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(f==="reverse"?(M=1-M,g&&(M-=g/a)):f==="mirror"&&(k=i)),v=Ht(0,1,M)*a}const V=w?{done:!1,value:l[0]}:k.next(v);o&&(V.value=o(V.value));let{done:E}=V;!w&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return D&&x!==ws&&(V.value=rr(l,this.options,S,this.speed)),y&&y(V.value),D&&this.finish(),V}then(e,n){return this.finished.then(e,n)}get duration(){return Nt(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(this.currentTime)}set time(e){e=$t(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(jt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=Nt(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=Jc,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(jt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}}function pl(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Ce=t=>t*180/Math.PI,Ts=t=>{const e=Ce(Math.atan2(t[1],t[0]));return Ss(e)},gl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ts,rotateZ:Ts,skewX:t=>Ce(Math.atan(t[1])),skewY:t=>Ce(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ss=t=>(t=t%360,t<0&&(t+=360),t),Ur=Ts,_r=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Wr=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),yl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:_r,scaleY:Wr,scale:t=>(_r(t)+Wr(t))/2,rotateX:t=>Ss(Ce(Math.atan2(t[6],t[5]))),rotateY:t=>Ss(Ce(Math.atan2(-t[2],t[0]))),rotateZ:Ur,rotate:Ur,skewX:t=>Ce(Math.atan(t[4])),skewY:t=>Ce(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function As(t){return t.includes("scale")?1:0}function Cs(t,e){if(!t||t==="none")return As(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=yl,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=gl,r=a}if(!r)return As(e);const o=s[e],i=r[1].split(",").map(vl);return typeof o=="function"?o(i):i[o]}const xl=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Cs(n,e)};function vl(t){return parseFloat(t.trim())}const qe=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ge=new Set(qe),Kr=t=>t===Ke||t===z,bl=new Set(["x","y","z"]),wl=qe.filter(t=>!bl.has(t));function Tl(t){const e=[];return wl.forEach(n=>{const s=t.getValue(n);s!==void 0&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}const Pe={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Cs(e,"x"),y:(t,{transform:e})=>Cs(e,"y")};Pe.translateX=Pe.x;Pe.translateY=Pe.y;const je=new Set;let Ps=!1,js=!1,Ms=!1;function ko(){if(js){const t=Array.from(je).filter(s=>s.needsMeasurement),e=new Set(t.map(s=>s.element)),n=new Map;e.forEach(s=>{const r=Tl(s);r.length&&(n.set(s,r),s.render())}),t.forEach(s=>s.measureInitialState()),e.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),t.forEach(s=>s.measureEndState()),t.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}js=!1,Ps=!1,je.forEach(t=>t.complete(Ms)),je.clear()}function Eo(){je.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(js=!0)})}function Sl(){Ms=!0,Eo(),ko(),Ms=!1}class ar{constructor(e,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(je.add(this),Ps||(Ps=!0,ot.read(Eo),ot.resolveKeyframes(ko))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:s,motionValue:r}=this;if(e[0]===null){const o=r?.get(),i=e[e.length-1];if(o!==void 0)e[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=i),r&&o===void 0&&r.set(e[0])}pl(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),je.delete(this)}cancel(){this.state==="scheduled"&&(je.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Al=t=>t.startsWith("--");function Cl(t,e,n){Al(e)?t.style.setProperty(e,n):t.style[e]=n}const Pl=Gs(()=>window.ScrollTimeline!==void 0),jl={};function Ml(t,e){const n=Gs(t);return()=>jl[e]??n()}const Do=Ml(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),sn=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,qr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:sn([0,.65,.55,1]),circOut:sn([.55,0,1,.45]),backIn:sn([.31,.01,.66,-.59]),backOut:sn([.33,1.53,.69,.99])};function No(t,e){if(t)return typeof t=="function"?Do()?Po(t,e):"ease-out":go(t)?sn(t):Array.isArray(t)?t.map(n=>No(n,e)||qr.easeOut):qr[t]}function kl(t,e,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[e]:n};c&&(l.offset=c);const h=No(a,r);Array.isArray(h)&&(l.easing=h);const f={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(f.pseudoElement=u),t.animate(l,f)}function Ro(t){return typeof t=="function"&&"applyToOptions"in t}function El({type:t,...e}){return Ro(t)&&Do()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Dl extends ir{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=e,Xt(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=El(e);this.animation=kl(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):Cl(n,s,l),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return Nt(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=$t(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&Pl()?(this.animation.timeline=e,Rt):n(this)}}const Vo={anticipate:ho,backInOut:uo,circInOut:mo};function Nl(t){return t in Vo}function Rl(t){typeof t.ease=="string"&&Nl(t.ease)&&(t.ease=Vo[t.ease])}const Gr=10;class Vl extends Dl{constructor(e){Rl(e),Mo(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new or({...i,autoplay:!1}),c=$t(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Gr).value,a.sample(c).value,Gr),a.stop()}}const Hr=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(he.test(t)||t==="0")&&!t.startsWith("url("));function Il(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function Ol(t,e,n,s){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],i=Hr(r,e),a=Hr(o,e);return We(i===a,`You are trying to animate ${e} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Il(t)||(n==="spring"||Ro(n))&&s}function ks(t){t.duration=0,t.type="keyframes"}const Ll=new Set(["opacity","clipPath","filter","transform"]),Fl=Gs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function $l(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=t;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=e.owner.getProps();return Fl()&&n&&Ll.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Bl=40;class zl extends ir{constructor({autoplay:e=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=jt.now();const f={autoplay:e,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...h},g=l?.KeyframeResolver||ar;this.keyframeResolver=new g(a,(x,y,S)=>this.onKeyframesResolved(x,y,f,!S),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=jt.now(),Ol(e,o,i,a)||((Yt.instantAnimations||!c)&&l?.(rr(e,s,n)),e[0]=e[e.length-1],ks(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Bl?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:e},g=!u&&$l(f)?new Vl({...f,element:f.motionValue.owner.current}):new or(f);g.finished.then(()=>this.notifyFinished()).catch(Rt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Sl()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Ul=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function _l(t){const e=Ul.exec(t);if(!e)return[,];const[,n,s,r]=e;return[`--${n??s}`,r]}const Wl=4;function Io(t,e,n=1){Xt(n<=Wl,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=_l(t);if(!s)return;const o=window.getComputedStyle(e).getPropertyValue(s);if(o){const i=o.trim();return no(i)?parseFloat(i):i}return Qs(r)?Io(r,e,n+1):r}function cr(t,e){return t?.[e]??t?.default??t}const Oo=new Set(["width","height","top","left","right","bottom",...qe]),Kl={test:t=>t==="auto",parse:t=>t},Lo=t=>e=>e.test(t),Fo=[Ke,z,Wt,ue,Ic,Vc,Kl],Xr=t=>Fo.find(Lo(t));function ql(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ro(t):!0}const Gl=new Set(["brightness","contrast","saturate","opacity"]);function Hl(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[s]=n.match(tr)||[];if(!s)return t;const r=n.replace(s,"");let o=Gl.has(e)?1:0;return s!==n&&(o*=100),e+"("+o+r+")"}const Xl=/\b([a-z-]*)\(.*?\)/gu,Es={...he,getAnimatableNone:t=>{const e=t.match(Xl);return e?e.map(Hl).join(" "):t}},Yr={...Ke,transform:Math.round},Yl={rotate:ue,rotateX:ue,rotateY:ue,rotateZ:ue,scale:Mn,scaleX:Mn,scaleY:Mn,scaleZ:Mn,skew:ue,skewX:ue,skewY:ue,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:hn,originX:Lr,originY:Lr,originZ:z},lr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...Yl,zIndex:Yr,fillOpacity:hn,strokeOpacity:hn,numOctaves:Yr},Jl={...lr,color:pt,backgroundColor:pt,outlineColor:pt,fill:pt,stroke:pt,borderColor:pt,borderTopColor:pt,borderRightColor:pt,borderBottomColor:pt,borderLeftColor:pt,filter:Es,WebkitFilter:Es},$o=t=>Jl[t];function Bo(t,e){let n=$o(t);return n!==Es&&(n=he),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Zl=new Set(["auto","none","0"]);function Ql(t,e,n){let s=0,r;for(;s<t.length&&!r;){const o=t[s];typeof o=="string"&&!Zl.has(o)&&fn(o).values.length&&(r=t[s]),s++}if(r&&n)for(const o of e)t[o]=Bo(n,r)}class tu extends ar{constructor(e,n,s,r,o){super(e,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let u=e[c];if(typeof u=="string"&&(u=u.trim(),Qs(u))){const l=Io(u,n.current);l!==void 0&&(e[c]=l),c===e.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Oo.has(s)||e.length!==2)return;const[r,o]=e,i=Xr(r),a=Xr(o);if(i!==a)if(Kr(i)&&Kr(a))for(let c=0;c<e.length;c++){const u=e[c];typeof u=="string"&&(e[c]=parseFloat(u))}else Pe[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,s=[];for(let r=0;r<e.length;r++)(e[r]===null||ql(e[r]))&&s.push(r);s.length&&Ql(e,s,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:s}=this;if(!e||!e.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Pe[s](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(s,r).jump(r,!1)}measureEndState(){const{element:e,name:n,unresolvedKeyframes:s}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Pe[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{e.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function eu(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let s=document;const r=n?.[t]??s.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t)}const zo=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function Uo(t){return so(t)&&"offsetHeight"in t}const Jr=30,nu=t=>!isNaN(parseFloat(t));class su{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=jt.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=jt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=nu(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Xs(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new Hs);const s=this.events[e].add(n);return e==="change"?()=>{s(),ot.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-s}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=jt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Jr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Jr);return io(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ue(t,e){return new su(t,e)}const{schedule:ur}=yo(queueMicrotask,!1),Lt={x:!1,y:!1};function _o(){return Lt.x||Lt.y}function ru(t){return t==="x"||t==="y"?Lt[t]?null:(Lt[t]=!0,()=>{Lt[t]=!1}):Lt.x||Lt.y?null:(Lt.x=Lt.y=!0,()=>{Lt.x=Lt.y=!1})}function Wo(t,e){const n=eu(t),s=new AbortController,r={passive:!0,...e,signal:s.signal};return[n,r,()=>s.abort()]}function Zr(t){return!(t.pointerType==="touch"||_o())}function iu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{if(!Zr(a))return;const{target:c}=a,u=e(c,a);if(typeof u!="function"||!c)return;const l=h=>{Zr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Ko=(t,e)=>e?t===e?!0:Ko(t,e.parentElement):!1,dr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,ou=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function au(t){return ou.has(t.tagName)||t.tabIndex!==-1}const Rn=new WeakSet;function Qr(t){return e=>{e.key==="Enter"&&t(e)}}function os(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const cu=(t,e)=>{const n=t.currentTarget;if(!n)return;const s=Qr(()=>{if(Rn.has(n))return;os(n,"down");const r=Qr(()=>{os(n,"up")}),o=()=>os(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",s,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),e)};function ti(t){return dr(t)&&!_o()}function lu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{const c=a.currentTarget;if(!ti(a))return;Rn.add(c);const u=e(c,a),l=(g,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),Rn.has(c)&&Rn.delete(c),ti(g)&&typeof u=="function"&&u(g,{success:x})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Ko(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),Uo(a)&&(a.addEventListener("focus",u=>cu(u,r)),!au(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function qo(t){return so(t)&&"ownerSVGElement"in t}function uu(t){return qo(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),du=[...Fo,pt,he],hu=t=>du.find(Lo(t)),hr=m.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function ei(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fu(...t){return e=>{let n=!1;const s=t.map(r=>{const o=ei(r,e);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():ei(t[r],null)}}}}function mu(...t){return Ft.useCallback(fu(...t),t)}class pu extends Ft.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=Uo(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function gu({children:t,isPresent:e,anchorX:n,root:s}){const r=m.useId(),o=m.useRef(null),i=m.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=m.useContext(hr),c=mu(o,t?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:h,left:f,right:g}=i.current;if(e||!o.current||!u||!l)return;const x=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const y=document.createElement("style");a&&(y.nonce=a);const S=s??document.head;return S.appendChild(y),y.sheet&&y.sheet.insertRule(`
1
+ "use strict";var ec=Object.create;var Dr=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var sc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,ic=Object.prototype.hasOwnProperty;var oc=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sc(e))!ic.call(t,r)&&r!==n&&Dr(t,r,{get:()=>e[r],enumerable:!(s=nc(e,r))||s.enumerable});return t};var ac=(t,e,n)=>(n=t!=null?ec(rc(t)):{},oc(e||!t||!t.__esModule?Dr(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),yt=require("lucide-react"),Ji=require("@ai-sdk/react"),Ln=require("ai"),Zi=require("@radix-ui/react-slot"),Qi=require("class-variance-authority"),cc=require("clsx"),lc=require("tailwind-merge"),uc=require("@radix-ui/react-tooltip"),Nr=require("@radix-ui/react-use-controllable-state"),dc=require("@radix-ui/react-collapsible"),hc=require("react-dom"),fc=require("./server.cjs");function Bs(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Ft=Bs(m),Be=Bs(uc),zs=Bs(dc);function mt(...t){return lc.twMerge(cc.clsx(t))}const Te=Qi.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Fn=Ft.forwardRef(({className:t,variant:e,size:n,asChild:s=!1,...r},o)=>{const i=s?Zi.Slot:"button";return d.jsx(i,{ref:o,"data-slot":"button",className:mt(Te({variant:e,size:n,className:t})),...r})});Fn.displayName="Button";const mc=Qi.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function ts({className:t,variant:e,asChild:n=!1,...s}){const r=n?Zi.Slot:"span";return d.jsx(r,{"data-slot":"badge",className:mt(mc({variant:e}),t),...s})}const pc=({textAreaRef:t,triggerAutoSize:e,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ft.useState(!0);Ft.useEffect(()=>{const a=t.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const c=a.scrollHeight;c>n?a.style.height=`${n}px`:a.style.height=`${c+6}px`}},[t.current,e])},to=Ft.forwardRef(({maxHeight:t=Number.MAX_SAFE_INTEGER,minHeight:e=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ft.useRef(null),[c,u]=Ft.useState("");return pc({textAreaRef:a,triggerAutoSize:c,maxHeight:t,minHeight:e}),m.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:t,minHeight:e})),Ft.useEffect(()=>{u(r)},[o?.defaultValue,r]),d.jsx("textarea",{...o,value:r,ref:a,className:mt("flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),onChange:l=>{u(l.target.value),s?.(l)}})});to.displayName="AutosizeTextarea";function gc({delayDuration:t=0,...e}){return d.jsx(Be.Provider,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function ae({...t}){return d.jsx(gc,{children:d.jsx(Be.Root,{"data-slot":"tooltip",...t})})}function ce({...t}){return d.jsx(Be.Trigger,{"data-slot":"tooltip-trigger",...t})}function le({className:t,sideOffset:e=0,children:n,...s}){return d.jsx(Be.Portal,{children:d.jsxs(Be.Content,{"data-slot":"tooltip-content",sideOffset:e,className:mt("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...s,children:[n,d.jsx(Be.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Rr({className:t,...e}){return d.jsx("kbd",{"data-slot":"kbd",className:mt("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",t),...e})}const Us=m.createContext({});function _s(t){const e=m.useRef(null);return e.current===null&&(e.current=t()),e.current}const Ws=typeof window<"u",eo=Ws?m.useLayoutEffect:m.useEffect,Wn=m.createContext(null);function Ks(t,e){t.indexOf(e)===-1&&t.push(e)}function qs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Ht=(t,e,n)=>n>e?e:n<t?t:n;function ys(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let We=()=>{},Xt=()=>{};process.env.NODE_ENV!=="production"&&(We=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(ys(e,n))},Xt=(t,e,n)=>{if(!t)throw new Error(ys(e,n))});const Yt={},no=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function so(t){return typeof t=="object"&&t!==null}const ro=t=>/^0[^.\s]+$/u.test(t);function Gs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Rt=t=>t,yc=(t,e)=>n=>e(t(n)),yn=(...t)=>t.reduce(yc),dn=(t,e,n)=>{const s=e-t;return s===0?1:(n-t)/s};class Hs{constructor(){this.subscriptions=[]}add(e){return Ks(this.subscriptions,e),()=>qs(this.subscriptions,e)}notify(e,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(e,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $t=t=>t*1e3,Nt=t=>t/1e3;function io(t,e){return e?t*(1e3/e):0}const Vr=new Set;function Xs(t,e,n){t||Vr.has(e)||(console.warn(ys(e,n)),Vr.add(e))}const oo=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,xc=1e-7,vc=12;function bc(t,e,n,s,r){let o,i,a=0;do i=e+(n-e)/2,o=oo(i,s,r)-t,o>0?n=i:e=i;while(Math.abs(o)>xc&&++a<vc);return i}function xn(t,e,n,s){if(t===e&&n===s)return Rt;const r=o=>bc(o,0,1,t,n);return o=>o===0||o===1?o:oo(r(o),e,s)}const ao=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,co=t=>e=>1-t(1-e),lo=xn(.33,1.53,.69,.99),Ys=co(lo),uo=ao(Ys),ho=t=>(t*=2)<1?.5*Ys(t):.5*(2-Math.pow(2,-10*(t-1))),Js=t=>1-Math.sin(Math.acos(t)),fo=co(Js),mo=ao(Js),wc=xn(.42,0,1,1),Tc=xn(0,0,.58,1),po=xn(.42,0,.58,1),Sc=t=>Array.isArray(t)&&typeof t[0]!="number",go=t=>Array.isArray(t)&&typeof t[0]=="number",Ir={linear:Rt,easeIn:wc,easeInOut:po,easeOut:Tc,circIn:Js,circInOut:mo,circOut:fo,backIn:Ys,backInOut:uo,backOut:lo,anticipate:ho},Ac=t=>typeof t=="string",Or=t=>{if(go(t)){Xt(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,s,r]=t;return xn(e,n,s,r)}else if(Ac(t))return Xt(Ir[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Ir[t];return t},jn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Cc(t,e){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(l){i.has(l)&&(u.schedule(l),t()),l(a)}const u={schedule:(l,h=!1,f=!1)=>{const S=f&&r?n:s;return h&&i.add(l),S.has(l)||S.add(l),l},cancel:l=>{s.delete(l),i.delete(l)},process:l=>{if(a=l,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(c),n.clear(),r=!1,o&&(o=!1,u.process(l))}};return u}const Pc=40;function yo(t,e){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=jn.reduce((x,M)=>(x[M]=Cc(o),x),{}),{setup:a,read:c,resolveKeyframes:u,preUpdate:l,update:h,preRender:f,render:g,postRender:S}=i,T=()=>{const x=Yt.useManualTiming?r.timestamp:performance.now();n=!1,Yt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(x-r.timestamp,Pc),1)),r.timestamp=x,r.isProcessing=!0,a.process(r),c.process(r),u.process(r),l.process(r),h.process(r),f.process(r),g.process(r),S.process(r),r.isProcessing=!1,n&&e&&(s=!1,t(T))},w=()=>{n=!0,s=!0,r.isProcessing||t(T)};return{schedule:jn.reduce((x,M)=>{const j=i[M];return x[M]=(E,D=!1,A=!1)=>(n||w(),j.schedule(E,D,A)),x},{}),cancel:x=>{for(let M=0;M<jn.length;M++)i[jn[M]].cancel(x)},state:r,steps:i}}const{schedule:ct,cancel:de,state:vt,steps:es}=yo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Rt,!0);let Nn;function jc(){Nn=void 0}const jt={now:()=>(Nn===void 0&&jt.set(vt.isProcessing||Yt.useManualTiming?vt.timestamp:performance.now()),Nn),set:t=>{Nn=t,queueMicrotask(jc)}},xo=t=>e=>typeof e=="string"&&e.startsWith(t),Zs=xo("--"),kc=xo("var(--"),Qs=t=>kc(t)?Mc.test(t.split("/*")[0].trim()):!1,Mc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ke={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},hn={...Ke,transform:t=>Ht(0,1,t)},kn={...Ke,default:1},rn=t=>Math.round(t*1e5)/1e5,tr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ec(t){return t==null}const Dc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,er=(t,e)=>n=>!!(typeof n=="string"&&Dc.test(n)&&n.startsWith(t)||e&&!Ec(n)&&Object.prototype.hasOwnProperty.call(n,e)),vo=(t,e,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(tr);return{[t]:parseFloat(r),[e]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},Nc=t=>Ht(0,255,t),ns={...Ke,transform:t=>Math.round(Nc(t))},Ae={test:er("rgb","red"),parse:vo("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+ns.transform(t)+", "+ns.transform(e)+", "+ns.transform(n)+", "+rn(hn.transform(s))+")"};function Rc(t){let e="",n="",s="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,s+=s,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const xs={test:er("#"),parse:Rc,transform:Ae.transform},vn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),ue=vn("deg"),Wt=vn("%"),z=vn("px"),Vc=vn("vh"),Ic=vn("vw"),Lr={...Wt,parse:t=>Wt.parse(t)/100,transform:t=>Wt.transform(t*100)},Ve={test:er("hsl","hue"),parse:vo("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+Wt.transform(rn(e))+", "+Wt.transform(rn(n))+", "+rn(hn.transform(s))+")"},gt={test:t=>Ae.test(t)||xs.test(t)||Ve.test(t),parse:t=>Ae.test(t)?Ae.parse(t):Ve.test(t)?Ve.parse(t):xs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ae.transform(t):Ve.transform(t),getAnimatableNone:t=>{const e=gt.parse(t);return e.alpha=0,gt.transform(e)}},Oc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Lc(t){return isNaN(t)&&typeof t=="string"&&(t.match(tr)?.length||0)+(t.match(Oc)?.length||0)>0}const bo="number",wo="color",Fc="var",$c="var(",Fr="${}",Bc=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function fn(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=e.replace(Bc,c=>(gt.test(c)?(s.color.push(o),r.push(wo),n.push(gt.parse(c))):c.startsWith($c)?(s.var.push(o),r.push(Fc),n.push(c)):(s.number.push(o),r.push(bo),n.push(parseFloat(c))),++o,Fr)).split(Fr);return{values:n,split:a,indexes:s,types:r}}function To(t){return fn(t).values}function So(t){const{split:e,types:n}=fn(t),s=e.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=e[i],r[i]!==void 0){const a=n[i];a===bo?o+=rn(r[i]):a===wo?o+=gt.transform(r[i]):o+=r[i]}return o}}const zc=t=>typeof t=="number"?0:gt.test(t)?gt.getAnimatableNone(t):t;function Uc(t){const e=To(t);return So(t)(e.map(zc))}const he={test:Lc,parse:To,createTransformer:So,getAnimatableNone:Uc};function ss(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function _c({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,e/=100,n/=100;let r=0,o=0,i=0;if(!e)r=o=i=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=ss(c,a,t+1/3),o=ss(c,a,t),i=ss(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function $n(t,e){return n=>n>0?e:t}const ut=(t,e,n)=>t+(e-t)*n,rs=(t,e,n)=>{const s=t*t,r=n*(e*e-s)+s;return r<0?0:Math.sqrt(r)},Wc=[xs,Ae,Ve],Kc=t=>Wc.find(e=>e.test(t));function $r(t){const e=Kc(t);if(We(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let n=e.parse(t);return e===Ve&&(n=_c(n)),n}const Br=(t,e)=>{const n=$r(t),s=$r(e);if(!n||!s)return $n(t,e);const r={...n};return o=>(r.red=rs(n.red,s.red,o),r.green=rs(n.green,s.green,o),r.blue=rs(n.blue,s.blue,o),r.alpha=ut(n.alpha,s.alpha,o),Ae.transform(r))},vs=new Set(["none","hidden"]);function qc(t,e){return vs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Gc(t,e){return n=>ut(t,e,n)}function nr(t){return typeof t=="number"?Gc:typeof t=="string"?Qs(t)?$n:gt.test(t)?Br:Yc:Array.isArray(t)?Ao:typeof t=="object"?gt.test(t)?Br:Hc:$n}function Ao(t,e){const n=[...t],s=n.length,r=t.map((o,i)=>nr(o)(o,e[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Hc(t,e){const n={...t,...e},s={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(s[r]=nr(t[r])(t[r],e[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Xc(t,e){const n=[],s={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const o=e.types[r],i=t.indexes[o][s[o]],a=t.values[i]??0;n[r]=a,s[o]++}return n}const Yc=(t,e)=>{const n=he.createTransformer(e),s=fn(t),r=fn(e);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?vs.has(t)&&!r.values.length||vs.has(e)&&!s.values.length?qc(t,e):yn(Ao(Xc(s,r),r.values),n):(We(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),$n(t,e))};function Co(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ut(t,e,n):nr(t)(t,e)}const Jc=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ct.update(e,n),stop:()=>de(e),now:()=>vt.isProcessing?vt.timestamp:jt.now()}},Po=(t,e,n=10)=>{let s="";const r=Math.max(Math.round(e/n),2);for(let o=0;o<r;o++)s+=Math.round(t(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},Bn=2e4;function sr(t){let e=0;const n=50;let s=t.next(e);for(;!s.done&&e<Bn;)e+=n,s=t.next(e);return e>=Bn?1/0:e}function Zc(t,e=100,n){const s=n({...t,keyframes:[0,e]}),r=Math.min(sr(s),Bn);return{type:"keyframes",ease:o=>s.next(r*o).value/e,duration:Nt(r)}}const Qc=5;function jo(t,e,n){const s=Math.max(e-Qc,0);return io(n-t(s),e-s)}const lt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},is=.001;function tl({duration:t=lt.duration,bounce:e=lt.bounce,velocity:n=lt.velocity,mass:s=lt.mass}){let r,o;We(t<=$t(lt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-e;i=Ht(lt.minDamping,lt.maxDamping,i),t=Ht(lt.minDuration,lt.maxDuration,Nt(t)),i<1?(r=u=>{const l=u*i,h=l*t,f=l-n,g=bs(u,i),S=Math.exp(-h);return is-f/g*S},o=u=>{const h=u*i*t,f=h*n+n,g=Math.pow(i,2)*Math.pow(u,2)*t,S=Math.exp(-h),T=bs(Math.pow(u,2),i);return(-r(u)+is>0?-1:1)*((f-g)*S)/T}):(r=u=>{const l=Math.exp(-u*t),h=(u-n)*t+1;return-is+l*h},o=u=>{const l=Math.exp(-u*t),h=(n-u)*(t*t);return l*h});const a=5/t,c=nl(r,o,a);if(t=$t(t),isNaN(c))return{stiffness:lt.stiffness,damping:lt.damping,duration:t};{const u=Math.pow(c,2)*s;return{stiffness:u,damping:i*2*Math.sqrt(s*u),duration:t}}}const el=12;function nl(t,e,n){let s=n;for(let r=1;r<el;r++)s=s-t(s)/e(s);return s}function bs(t,e){return t*Math.sqrt(1-e*e)}const sl=["duration","bounce"],rl=["stiffness","damping","mass"];function zr(t,e){return e.some(n=>t[n]!==void 0)}function il(t){let e={velocity:lt.velocity,stiffness:lt.stiffness,damping:lt.damping,mass:lt.mass,isResolvedFromDuration:!1,...t};if(!zr(t,rl)&&zr(t,sl))if(t.visualDuration){const n=t.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*Ht(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:lt.mass,stiffness:r,damping:o}}else{const n=tl(t);e={...e,...n,mass:lt.mass},e.isResolvedFromDuration=!0}return e}function zn(t=lt.visualDuration,e=lt.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:u,mass:l,duration:h,velocity:f,isResolvedFromDuration:g}=il({...n,velocity:-Nt(n.velocity||0)}),S=f||0,T=u/(2*Math.sqrt(c*l)),w=i-o,y=Nt(Math.sqrt(c/l)),v=Math.abs(w)<5;s||(s=v?lt.restSpeed.granular:lt.restSpeed.default),r||(r=v?lt.restDelta.granular:lt.restDelta.default);let x;if(T<1){const j=bs(y,T);x=E=>{const D=Math.exp(-T*y*E);return i-D*((S+T*y*w)/j*Math.sin(j*E)+w*Math.cos(j*E))}}else if(T===1)x=j=>i-Math.exp(-y*j)*(w+(S+y*w)*j);else{const j=y*Math.sqrt(T*T-1);x=E=>{const D=Math.exp(-T*y*E),A=Math.min(j*E,300);return i-D*((S+T*y*w)*Math.sinh(A)+j*w*Math.cosh(A))/j}}const M={calculatedDuration:g&&h||null,next:j=>{const E=x(j);if(g)a.done=j>=h;else{let D=j===0?S:0;T<1&&(D=j===0?$t(S):jo(x,j,E));const A=Math.abs(D)<=s,F=Math.abs(i-E)<=r;a.done=A&&F}return a.value=a.done?i:E,a},toString:()=>{const j=Math.min(sr(M),Bn),E=Po(D=>M.next(j*D).value,j,30);return j+"ms "+E},toTransition:()=>{}};return M}zn.applyToOptions=t=>{const e=Zc(t,100,zn);return t.ease=e.ease,t.duration=$t(e.duration),t.type="keyframes",t};function ws({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:c,restDelta:u=.5,restSpeed:l}){const h=t[0],f={done:!1,value:h},g=A=>a!==void 0&&A<a||c!==void 0&&A>c,S=A=>a===void 0?c:c===void 0||Math.abs(a-A)<Math.abs(c-A)?a:c;let T=n*e;const w=h+T,y=i===void 0?w:i(w);y!==w&&(T=y-h);const v=A=>-T*Math.exp(-A/s),x=A=>y+v(A),M=A=>{const F=v(A),I=x(A);f.done=Math.abs(F)<=u,f.value=f.done?y:I};let j,E;const D=A=>{g(f.value)&&(j=A,E=zn({keyframes:[f.value,S(f.value)],velocity:jo(x,A,f.value),damping:r,stiffness:o,restDelta:u,restSpeed:l}))};return D(0),{calculatedDuration:null,next:A=>{let F=!1;return!E&&j===void 0&&(F=!0,M(A),D(A)),j!==void 0&&A>=j?E.next(A-j):(!F&&M(A),f)}}}function ol(t,e,n){const s=[],r=n||Yt.mix||Co,o=t.length-1;for(let i=0;i<o;i++){let a=r(t[i],t[i+1]);if(e){const c=Array.isArray(e)?e[i]||Rt:e;a=yn(c,a)}s.push(a)}return s}function al(t,e,{clamp:n=!0,ease:s,mixer:r}={}){const o=t.length;if(Xt(o===e.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const i=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=ol(e,s,r),c=a.length,u=l=>{if(i&&l<t[0])return e[0];let h=0;if(c>1)for(;h<t.length-2&&!(l<t[h+1]);h++);const f=dn(t[h],t[h+1],l);return a[h](f)};return n?l=>u(Ht(t[0],t[o-1],l)):u}function cl(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const r=dn(0,e,s);t.push(ut(n,1,r))}}function ll(t){const e=[0];return cl(e,t.length-1),e}function ul(t,e){return t.map(n=>n*e)}function dl(t,e){return t.map(()=>e||po).splice(0,t.length-1)}function Ie({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const r=Sc(s)?s.map(Or):Or(s),o={done:!1,value:e[0]},i=ul(n&&n.length===e.length?n:ll(e),t),a=al(i,e,{ease:Array.isArray(r)?r:dl(e,r)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const hl=t=>t!==null;function rr(t,{repeat:e,repeatType:n="loop"},s,r=1){const o=t.filter(hl),a=r<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const fl={decay:ws,inertia:ws,tween:Ie,keyframes:Ie,spring:zn};function ko(t){typeof t.type=="string"&&(t.type=fl[t.type])}class ir{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const ml=t=>t/100;class or extends ir{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==jt.now()&&this.tick(jt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;ko(e);const{type:n=Ie,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=e;let{keyframes:a}=e;const c=n||Ie;process.env.NODE_ENV!=="production"&&c!==Ie&&Xt(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Ie&&typeof a[0]!="number"&&(this.mixKeyframes=yn(ml,Co(a[0],a[1])),a=[0,100]);const u=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-i})),u.calculatedDuration===null&&(u.calculatedDuration=sr(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=u}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:u=0,keyframes:l,repeat:h,repeatType:f,repeatDelay:g,type:S,onUpdate:T,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-u*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>r;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let x=this.currentTime,M=s;if(h){const A=Math.min(this.currentTime,r)/a;let F=Math.floor(A),I=A%1;!I&&A>=1&&(I=1),I===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(f==="reverse"?(I=1-I,g&&(I-=g/a)):f==="mirror"&&(M=i)),x=Ht(0,1,I)*a}const j=v?{done:!1,value:l[0]}:M.next(x);o&&(j.value=o(j.value));let{done:E}=j;!v&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return D&&S!==ws&&(j.value=rr(l,this.options,w,this.speed)),T&&T(j.value),D&&this.finish(),j}then(e,n){return this.finished.then(e,n)}get duration(){return Nt(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(this.currentTime)}set time(e){e=$t(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(jt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=Nt(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=Jc,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(jt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}}function pl(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Ce=t=>t*180/Math.PI,Ts=t=>{const e=Ce(Math.atan2(t[1],t[0]));return Ss(e)},gl={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ts,rotateZ:Ts,skewX:t=>Ce(Math.atan(t[1])),skewY:t=>Ce(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ss=t=>(t=t%360,t<0&&(t+=360),t),Ur=Ts,_r=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Wr=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),yl={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:_r,scaleY:Wr,scale:t=>(_r(t)+Wr(t))/2,rotateX:t=>Ss(Ce(Math.atan2(t[6],t[5]))),rotateY:t=>Ss(Ce(Math.atan2(-t[2],t[0]))),rotateZ:Ur,rotate:Ur,skewX:t=>Ce(Math.atan(t[4])),skewY:t=>Ce(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function As(t){return t.includes("scale")?1:0}function Cs(t,e){if(!t||t==="none")return As(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=yl,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=gl,r=a}if(!r)return As(e);const o=s[e],i=r[1].split(",").map(vl);return typeof o=="function"?o(i):i[o]}const xl=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Cs(n,e)};function vl(t){return parseFloat(t.trim())}const qe=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ge=new Set(qe),Kr=t=>t===Ke||t===z,bl=new Set(["x","y","z"]),wl=qe.filter(t=>!bl.has(t));function Tl(t){const e=[];return wl.forEach(n=>{const s=t.getValue(n);s!==void 0&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}const Pe={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Cs(e,"x"),y:(t,{transform:e})=>Cs(e,"y")};Pe.translateX=Pe.x;Pe.translateY=Pe.y;const je=new Set;let Ps=!1,js=!1,ks=!1;function Mo(){if(js){const t=Array.from(je).filter(s=>s.needsMeasurement),e=new Set(t.map(s=>s.element)),n=new Map;e.forEach(s=>{const r=Tl(s);r.length&&(n.set(s,r),s.render())}),t.forEach(s=>s.measureInitialState()),e.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),t.forEach(s=>s.measureEndState()),t.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}js=!1,Ps=!1,je.forEach(t=>t.complete(ks)),je.clear()}function Eo(){je.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(js=!0)})}function Sl(){ks=!0,Eo(),Mo(),ks=!1}class ar{constructor(e,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(je.add(this),Ps||(Ps=!0,ct.read(Eo),ct.resolveKeyframes(Mo))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:s,motionValue:r}=this;if(e[0]===null){const o=r?.get(),i=e[e.length-1];if(o!==void 0)e[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=i),r&&o===void 0&&r.set(e[0])}pl(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),je.delete(this)}cancel(){this.state==="scheduled"&&(je.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Al=t=>t.startsWith("--");function Cl(t,e,n){Al(e)?t.style.setProperty(e,n):t.style[e]=n}const Pl=Gs(()=>window.ScrollTimeline!==void 0),jl={};function kl(t,e){const n=Gs(t);return()=>jl[e]??n()}const Do=kl(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),sn=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,qr={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:sn([0,.65,.55,1]),circOut:sn([.55,0,1,.45]),backIn:sn([.31,.01,.66,-.59]),backOut:sn([.33,1.53,.69,.99])};function No(t,e){if(t)return typeof t=="function"?Do()?Po(t,e):"ease-out":go(t)?sn(t):Array.isArray(t)?t.map(n=>No(n,e)||qr.easeOut):qr[t]}function Ml(t,e,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:c}={},u=void 0){const l={[e]:n};c&&(l.offset=c);const h=No(a,r);Array.isArray(h)&&(l.easing=h);const f={delay:s,duration:r,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return u&&(f.pseudoElement=u),t.animate(l,f)}function Ro(t){return typeof t=="function"&&"applyToOptions"in t}function El({type:t,...e}){return Ro(t)&&Do()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Dl extends ir{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=e,Xt(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const u=El(e);this.animation=Ml(n,s,r,u,o),u.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const l=rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(l):Cl(n,s,l),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return Nt(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Nt(e)}get time(){return Nt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=$t(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&Pl()?(this.animation.timeline=e,Rt):n(this)}}const Vo={anticipate:ho,backInOut:uo,circInOut:mo};function Nl(t){return t in Vo}function Rl(t){typeof t.ease=="string"&&Nl(t.ease)&&(t.ease=Vo[t.ease])}const Gr=10;class Vl extends Dl{constructor(e){Rl(e),ko(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new or({...i,autoplay:!1}),c=$t(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Gr).value,a.sample(c).value,Gr),a.stop()}}const Hr=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(he.test(t)||t==="0")&&!t.startsWith("url("));function Il(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function Ol(t,e,n,s){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],i=Hr(r,e),a=Hr(o,e);return We(i===a,`You are trying to animate ${e} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Il(t)||(n==="spring"||Ro(n))&&s}function Ms(t){t.duration=0,t.type="keyframes"}const Ll=new Set(["opacity","clipPath","filter","transform"]),Fl=Gs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function $l(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=t;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=e.owner.getProps();return Fl()&&n&&Ll.has(n)&&(n!=="transform"||!u)&&!c&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Bl=40;class zl extends ir{constructor({autoplay:e=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:c,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=jt.now();const f={autoplay:e,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:c,motionValue:u,element:l,...h},g=l?.KeyframeResolver||ar;this.keyframeResolver=new g(a,(S,T,w)=>this.onKeyframesResolved(S,T,f,!w),c,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:c,isHandoff:u,onUpdate:l}=s;this.resolvedAt=jt.now(),Ol(e,o,i,a)||((Yt.instantAnimations||!c)&&l?.(rr(e,s,n)),e[0]=e[e.length-1],Ms(s),s.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Bl?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:e},g=!u&&$l(f)?new Vl({...f,element:f.motionValue.owner.current}):new or(f);g.finished.then(()=>this.notifyFinished()).catch(Rt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Sl()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Ul=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function _l(t){const e=Ul.exec(t);if(!e)return[,];const[,n,s,r]=e;return[`--${n??s}`,r]}const Wl=4;function Io(t,e,n=1){Xt(n<=Wl,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=_l(t);if(!s)return;const o=window.getComputedStyle(e).getPropertyValue(s);if(o){const i=o.trim();return no(i)?parseFloat(i):i}return Qs(r)?Io(r,e,n+1):r}function cr(t,e){return t?.[e]??t?.default??t}const Oo=new Set(["width","height","top","left","right","bottom",...qe]),Kl={test:t=>t==="auto",parse:t=>t},Lo=t=>e=>e.test(t),Fo=[Ke,z,Wt,ue,Ic,Vc,Kl],Xr=t=>Fo.find(Lo(t));function ql(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ro(t):!0}const Gl=new Set(["brightness","contrast","saturate","opacity"]);function Hl(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[s]=n.match(tr)||[];if(!s)return t;const r=n.replace(s,"");let o=Gl.has(e)?1:0;return s!==n&&(o*=100),e+"("+o+r+")"}const Xl=/\b([a-z-]*)\(.*?\)/gu,Es={...he,getAnimatableNone:t=>{const e=t.match(Xl);return e?e.map(Hl).join(" "):t}},Yr={...Ke,transform:Math.round},Yl={rotate:ue,rotateX:ue,rotateY:ue,rotateZ:ue,scale:kn,scaleX:kn,scaleY:kn,scaleZ:kn,skew:ue,skewX:ue,skewY:ue,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:hn,originX:Lr,originY:Lr,originZ:z},lr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...Yl,zIndex:Yr,fillOpacity:hn,strokeOpacity:hn,numOctaves:Yr},Jl={...lr,color:gt,backgroundColor:gt,outlineColor:gt,fill:gt,stroke:gt,borderColor:gt,borderTopColor:gt,borderRightColor:gt,borderBottomColor:gt,borderLeftColor:gt,filter:Es,WebkitFilter:Es},$o=t=>Jl[t];function Bo(t,e){let n=$o(t);return n!==Es&&(n=he),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Zl=new Set(["auto","none","0"]);function Ql(t,e,n){let s=0,r;for(;s<t.length&&!r;){const o=t[s];typeof o=="string"&&!Zl.has(o)&&fn(o).values.length&&(r=t[s]),s++}if(r&&n)for(const o of e)t[o]=Bo(n,r)}class tu extends ar{constructor(e,n,s,r,o){super(e,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let u=e[c];if(typeof u=="string"&&(u=u.trim(),Qs(u))){const l=Io(u,n.current);l!==void 0&&(e[c]=l),c===e.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Oo.has(s)||e.length!==2)return;const[r,o]=e,i=Xr(r),a=Xr(o);if(i!==a)if(Kr(i)&&Kr(a))for(let c=0;c<e.length;c++){const u=e[c];typeof u=="string"&&(e[c]=parseFloat(u))}else Pe[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,s=[];for(let r=0;r<e.length;r++)(e[r]===null||ql(e[r]))&&s.push(r);s.length&&Ql(e,s,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:s}=this;if(!e||!e.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Pe[s](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(s,r).jump(r,!1)}measureEndState(){const{element:e,name:n,unresolvedKeyframes:s}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Pe[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,c])=>{e.getValue(a).set(c)}),this.resolveNoneKeyframes()}}function eu(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let s=document;const r=n?.[t]??s.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t)}const zo=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function Uo(t){return so(t)&&"offsetHeight"in t}const Jr=30,nu=t=>!isNaN(parseFloat(t));class su{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=jt.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=jt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=nu(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Xs(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new Hs);const s=this.events[e].add(n);return e==="change"?()=>{s(),ct.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-s}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=jt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Jr)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Jr);return io(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ue(t,e){return new su(t,e)}const{schedule:ur}=yo(queueMicrotask,!1),Lt={x:!1,y:!1};function _o(){return Lt.x||Lt.y}function ru(t){return t==="x"||t==="y"?Lt[t]?null:(Lt[t]=!0,()=>{Lt[t]=!1}):Lt.x||Lt.y?null:(Lt.x=Lt.y=!0,()=>{Lt.x=Lt.y=!1})}function Wo(t,e){const n=eu(t),s=new AbortController,r={passive:!0,...e,signal:s.signal};return[n,r,()=>s.abort()]}function Zr(t){return!(t.pointerType==="touch"||_o())}function iu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{if(!Zr(a))return;const{target:c}=a,u=e(c,a);if(typeof u!="function"||!c)return;const l=h=>{Zr(h)&&(u(h),c.removeEventListener("pointerleave",l))};c.addEventListener("pointerleave",l,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const Ko=(t,e)=>e?t===e?!0:Ko(t,e.parentElement):!1,dr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,ou=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function au(t){return ou.has(t.tagName)||t.tabIndex!==-1}const Rn=new WeakSet;function Qr(t){return e=>{e.key==="Enter"&&t(e)}}function os(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const cu=(t,e)=>{const n=t.currentTarget;if(!n)return;const s=Qr(()=>{if(Rn.has(n))return;os(n,"down");const r=Qr(()=>{os(n,"up")}),o=()=>os(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",s,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),e)};function ti(t){return dr(t)&&!_o()}function lu(t,e,n={}){const[s,r,o]=Wo(t,n),i=a=>{const c=a.currentTarget;if(!ti(a))return;Rn.add(c);const u=e(c,a),l=(g,S)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",f),Rn.has(c)&&Rn.delete(c),ti(g)&&typeof u=="function"&&u(g,{success:S})},h=g=>{l(g,c===window||c===document||n.useGlobalTarget||Ko(c,g.target))},f=g=>{l(g,!1)};window.addEventListener("pointerup",h,r),window.addEventListener("pointercancel",f,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),Uo(a)&&(a.addEventListener("focus",u=>cu(u,r)),!au(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function qo(t){return so(t)&&"ownerSVGElement"in t}function uu(t){return qo(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),du=[...Fo,gt,he],hu=t=>du.find(Lo(t)),hr=m.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function ei(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fu(...t){return e=>{let n=!1;const s=t.map(r=>{const o=ei(r,e);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():ei(t[r],null)}}}}function mu(...t){return Ft.useCallback(fu(...t),t)}class pu extends Ft.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=Uo(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function gu({children:t,isPresent:e,anchorX:n,root:s}){const r=m.useId(),o=m.useRef(null),i=m.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=m.useContext(hr),c=mu(o,t?.ref);return m.useInsertionEffect(()=>{const{width:u,height:l,top:h,left:f,right:g}=i.current;if(e||!o.current||!u||!l)return;const S=n==="left"?`left: ${f}`:`right: ${g}`;o.current.dataset.motionPopId=r;const T=document.createElement("style");a&&(T.nonce=a);const w=s??document.head;return w.appendChild(T),T.sheet&&T.sheet.insertRule(`
2
2
  [data-motion-pop-id="${r}"] {
3
3
  position: absolute !important;
4
4
  width: ${u}px !important;
5
5
  height: ${l}px !important;
6
- ${x}px !important;
6
+ ${S}px !important;
7
7
  top: ${h}px !important;
8
8
  }
9
- `),()=>{S.contains(y)&&S.removeChild(y)}},[e]),d.jsx(pu,{isPresent:e,childRef:o,sizeRef:i,children:Ft.cloneElement(t,{ref:c})})}const yu=({children:t,initial:e,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=_s(xu),l=m.useId();let h=!0,f=m.useMemo(()=>(h=!1,{id:l,initial:e,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const 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]),Ft.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(t=d.jsx(gu,{isPresent:n,anchorX:a,root:c,children:t})),d.jsx(Wn.Provider,{value:f,children:t})};function xu(){return new Map}function Go(t=!0){const e=m.useContext(Wn);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=e,o=m.useId();m.useEffect(()=>{if(t)return r(o)},[t]);const i=m.useCallback(()=>t&&s&&s(o),[o,s,t]);return!n&&s?[!1,i]:[!0]}const kn=t=>t.key||"";function ni(t){const e=[];return m.Children.forEach(t,n=>{m.isValidElement(n)&&e.push(n)}),e}const vu=({children:t,custom:e,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=Go(i),h=m.useMemo(()=>ni(t),[t]),f=i&&!u?[]:h.map(kn),g=m.useRef(!0),x=m.useRef(h),y=_s(()=>new Map),[S,T]=m.useState(h),[w,v]=m.useState(h);eo(()=>{g.current=!1,x.current=h;for(let E=0;E<w.length;E++){const D=kn(w[E]);f.includes(D)?y.delete(D):y.get(D)!==!0&&y.set(D,!1)}},[w,f.length,f.join("-")]);const k=[];if(h!==S){let E=[...h];for(let D=0;D<w.length;D++){const A=w[D],F=kn(A);f.includes(F)||(E.splice(D,0,A),k.push(A))}return o==="wait"&&k.length&&(E=k),v(ni(E)),T(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:V}=m.useContext(Us);return d.jsx(d.Fragment,{children:w.map(E=>{const D=kn(E),A=i&&!u?!1:h===w||f.includes(D),F=()=>{if(y.has(D))y.set(D,!0);else return;let M=!0;y.forEach(G=>{G||(M=!1)}),M&&(V?.(),v(x.current),i&&l?.(),s&&s())};return d.jsx(yu,{isPresent:A,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:A?void 0:F,anchorX:a,children:E},D)})})},fr=m.createContext({strict:!1}),si={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},_e={};for(const t in si)_e[t]={isEnabled:e=>si[t].some(n=>!!e[n])};function Ds(t){for(const e in t)_e[e]={..._e[e],...t[e]}}function bu({children:t,features:e,strict:n=!1}){const[,s]=m.useState(!as(e)),r=m.useRef(void 0);if(!as(e)){const{renderer:o,...i}=e;r.current=o,Ds(i)}return m.useEffect(()=>{as(e)&&e().then(({renderer:o,...i})=>{Ds(i),r.current=o,s(!0)})},[]),d.jsx(fr.Provider,{value:{renderer:r.current,strict:n},children:t})}function as(t){return typeof t=="function"}const wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Un(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||wu.has(t)}let Ho=t=>!Un(t);function Tu(t){typeof t=="function"&&(Ho=e=>e.startsWith("on")?!Un(e):t(e))}try{Tu(require("@emotion/is-prop-valid").default)}catch{}function Su(t,e,n){const s={};for(const r in t)r==="values"&&typeof t.values=="object"||(Ho(r)||n===!0&&Un(r)||!e&&!Un(r)||t.draggable&&r.startsWith("onDrag"))&&(s[r]=t[r]);return s}const Kn=m.createContext({});function qn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function mn(t){return typeof t=="string"||Array.isArray(t)}const mr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],pr=["initial",...mr];function Gn(t){return qn(t.animate)||pr.some(e=>mn(t[e]))}function Xo(t){return!!(Gn(t)||t.variants)}function Au(t,e){if(Gn(t)){const{initial:n,animate:s}=t;return{initial:n===!1||mn(n)?n:void 0,animate:mn(s)?s:void 0}}return t.inherit!==!1?e:{}}function Cu(t){const{initial:e,animate:n}=Au(t,m.useContext(Kn));return m.useMemo(()=>({initial:e,animate:n}),[ri(e),ri(n)])}function ri(t){return Array.isArray(t)?t.join(" "):t}const pn={};function Pu(t){for(const e in t)pn[e]=t[e],Zs(e)&&(pn[e].isCSSVariable=!0)}function Yo(t,{layout:e,layoutId:n}){return Ge.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!pn[t]||t==="opacity")}const ju={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Mu=qe.length;function ku(t,e,n){let s="",r=!0;for(let o=0;o<Mu;o++){const i=qe[o],a=t[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=zo(a,lr[i]);if(!c){r=!1;const l=ju[i]||i;s+=`${l}(${u}) `}n&&(e[i]=u)}}return s=s.trim(),n?s=n(e,r?"":s):r&&(s="none"),s}function gr(t,e,n){const{style:s,vars:r,transformOrigin:o}=t;let i=!1,a=!1;for(const c in e){const u=e[c];if(Ge.has(c)){i=!0;continue}else if(Zs(c)){r[c]=u;continue}else{const l=zo(u,lr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(e.transform||(i||n?s.transform=ku(e,t.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:l=0}=o;s.transformOrigin=`${c} ${u} ${l}`}}const yr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Jo(t,e,n){for(const s in e)!Tt(e[s])&&!Yo(s,n)&&(t[s]=e[s])}function Eu({transformTemplate:t},e){return m.useMemo(()=>{const n=yr();return gr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Du(t,e){const n=t.style||{},s={};return Jo(s,n,t),Object.assign(s,Eu(t,e)),s}function Nu(t,e){const n={},s=Du(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=s,n}const Ru={offset:"stroke-dashoffset",array:"stroke-dasharray"},Vu={offset:"strokeDashoffset",array:"strokeDasharray"};function Iu(t,e,n=1,s=0,r=!0){t.pathLength=1;const o=r?Ru:Vu;t[o.offset]=z.transform(-s);const i=z.transform(e),a=z.transform(n);t[o.array]=`${i} ${a}`}function Zo(t,{attrX:e,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(gr(t,a,u),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:f}=t;h.transform&&(f.transform=h.transform,delete h.transform),(f.transform||h.transformOrigin)&&(f.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete h.transformBox),e!==void 0&&(h.x=e),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Iu(h,r,o,i,!1)}const Qo=()=>({...yr(),attrs:{}}),ta=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Ou(t,e,n,s){const r=m.useMemo(()=>{const o=Qo();return Zo(o,e,ta(s),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Jo(o,t.style,t),r.style={...o,...r.style}}return r}const Lu=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function xr(t){return typeof t!="string"||t.includes("-")?!1:!!(Lu.indexOf(t)>-1||/[A-Z]/u.test(t))}function Fu(t,e,n,{latestValues:s},r,o=!1){const a=(xr(t)?Ou:Nu)(e,s,r,t),c=Su(e,typeof t=="string",o),u=t!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=e,h=m.useMemo(()=>Tt(l)?l.get():l,[l]);return m.createElement(t,{...u,children:h})}function ii(t){const e=[{},{}];return t?.values.forEach((n,s)=>{e[0][s]=n.get(),e[1][s]=n.getVelocity()}),e}function vr(t,e,n,s){if(typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}return e}function Vn(t){return Tt(t)?t.get():t}function $u({scrapeMotionValuesFromProps:t,createRenderState:e},n,s,r){return{latestValues:Bu(n,s,r,t),renderState:e()}}function Bu(t,e,n,s){const r={},o=s(t,{});for(const f in o)r[f]=Vn(o[f]);let{initial:i,animate:a}=t;const c=Gn(t),u=Xo(t);e&&u&&!c&&t.inherit!==!1&&(i===void 0&&(i=e.initial),a===void 0&&(a=e.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const h=l?a:i;if(h&&typeof h!="boolean"&&!qn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const x=vr(t,f[g]);if(x){const{transitionEnd:y,transition:S,...T}=x;for(const w in T){let v=T[w];if(Array.isArray(v)){const k=l?v.length-1:0;v=v[k]}v!==null&&(r[w]=v)}for(const w in y)r[w]=y[w]}}}return r}const ea=t=>(e,n)=>{const s=m.useContext(Kn),r=m.useContext(Wn),o=()=>$u(t,e,s,r);return n?o():_s(o)};function br(t,e,n){const{style:s}=t,r={};for(const o in s)(Tt(s[o])||e.style&&Tt(e.style[o])||Yo(o,t)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const zu=ea({scrapeMotionValuesFromProps:br,createRenderState:yr});function na(t,e,n){const s=br(t,e,n);for(const r in t)if(Tt(t[r])||Tt(e[r])){const o=qe.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=t[r]}return s}const Uu=ea({scrapeMotionValuesFromProps:na,createRenderState:Qo}),_u=Symbol.for("motionComponentSymbol");function Oe(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Wu(t,e,n){return m.useCallback(s=>{s&&t.onMount&&t.onMount(s),e&&(s?e.mount(s):e.unmount()),n&&(typeof n=="function"?n(s):Oe(n)&&(n.current=s))},[e])}const wr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Ku="framerAppearId",sa="data-"+wr(Ku),ra=m.createContext({});function qu(t,e,n,s,r){const{visualElement:o}=m.useContext(Kn),i=m.useContext(fr),a=m.useContext(Wn),c=m.useContext(hr).reducedMotion,u=m.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const l=u.current,h=m.useContext(ra);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Gu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[sa],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 Gu(t,e,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:ia(t.parent)),t.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Oe(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function ia(t){if(t)return t.options.allowProjection!==!1?t.projection:ia(t.parent)}function In(t,{forwardMotionProps:e=!1}={},n,s){n&&Ds(n);const r=xr(t)?Uu:zu;function o(a,c){let u;const l={...m.useContext(hr),...a,layoutId:Hu(a)},{isStatic:h}=l,f=Cu(a),g=r(a,h);if(!h&&Ws){Xu(l,n);const x=Yu(l);u=x.MeasureLayout,f.visualElement=qu(t,g,l,s,x.ProjectionNode)}return d.jsxs(Kn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Fu(t,a,Wu(g,f.visualElement,c),g,h,e)]})}o.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const i=m.forwardRef(o);return i[_u]=t,i}function Hu({layoutId:t}){const e=m.useContext(Us).id;return e&&t!==void 0?e+"-"+t:t}function Xu(t,e){const n=m.useContext(fr).strict;if(process.env.NODE_ENV!=="production"&&e&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";t.ignoreStrict?We(!1,s,"lazy-strict-mode"):Xt(!1,s,"lazy-strict-mode")}}function Yu(t){const{drag:e,layout:n}=_e;if(!e&&!n)return{};const s={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Ju(t,e){if(typeof Proxy>"u")return In;const n=new Map,s=(o,i)=>In(o,i,t,e),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Xs(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,In(i,void 0,t,e)),n.get(i))})}function oa({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}function Zu({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Qu(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function cs(t){return t===void 0||t===1}function Ns({scale:t,scaleX:e,scaleY:n}){return!cs(t)||!cs(e)||!cs(n)}function Se(t){return Ns(t)||aa(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function aa(t){return oi(t.x)||oi(t.y)}function oi(t){return t&&t!=="0%"}function _n(t,e,n){const s=t-n,r=e*s;return n+r}function ai(t,e,n,s,r){return r!==void 0&&(t=_n(t,r,s)),_n(t,n,s)+e}function Rs(t,e=0,n=1,s,r){t.min=ai(t.min,e,n,s,r),t.max=ai(t.max,e,n,s,r)}function ca(t,{x:e,y:n}){Rs(t.x,e.translate,e.scale,e.originPoint),Rs(t.y,n.translate,n.scale,n.originPoint)}const ci=.999999999999,li=1.0000000000001;function td(t,e,n,s=!1){const r=n.length;if(!r)return;e.x=e.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Fe(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(e.x*=i.x.scale,e.y*=i.y.scale,ca(t,i)),s&&Se(o.latestValues)&&Fe(t,o.latestValues))}e.x<li&&e.x>ci&&(e.x=1),e.y<li&&e.y>ci&&(e.y=1)}function Le(t,e){t.min=t.min+e,t.max=t.max+e}function ui(t,e,n,s,r=.5){const o=ct(t.min,t.max,r);Rs(t,e,n,o,s)}function Fe(t,e){ui(t.x,e.x,e.scaleX,e.scale,e.originX),ui(t.y,e.y,e.scaleY,e.scale,e.originY)}function la(t,e){return oa(Qu(t.getBoundingClientRect(),e))}function ed(t,e,n){const s=la(t,n),{scroll:r}=e;return r&&(Le(s.x,r.offset.x),Le(s.y,r.offset.y)),s}const di=()=>({translate:0,scale:1,origin:0,originPoint:0}),$e=()=>({x:di(),y:di()}),hi=()=>({min:0,max:0}),ft=()=>({x:hi(),y:hi()}),Vs={current:null},ua={current:!1};function nd(){if(ua.current=!0,!!Ws)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Vs.current=t.matches;t.addEventListener("change",e),e()}else Vs.current=!1}const sd=new WeakMap;function rd(t,e,n){for(const s in e){const r=e[s],o=n[s];if(Tt(r))t.addValue(s,r);else if(Tt(o))t.addValue(s,Ue(r,{owner:t}));else if(o!==r)if(t.hasValue(s)){const i=t.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=t.getStaticValue(s);t.addValue(s,Ue(i!==void 0?i:r,{owner:t}))}}for(const s in n)e[s]===void 0&&t.removeValue(s);return e}const fi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class id{scrapeMotionValuesFromProps(e,n,s){return{}}constructor({parent:e,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ar,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=jt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ot.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=e,this.props=n,this.presenceContext=s,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Gn(n),this.isVariantNode=Xo(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:l,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const g=h[f];c[f]!==void 0&&Tt(g)&&g.set(c[f])}}mount(e){this.current=e,sd.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),ua.current||nd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Vs.current,process.env.NODE_ENV!=="production"&&Xs(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),de(this.notifyUpdate),de(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const s=Ge.has(e);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[e]=i,this.props.onUpdate&&ot.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in _e){const n=_e[e];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[e]&&r&&s(this.props)&&(this.features[e]=new r(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<fi.length;s++){const r=fi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=e[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=rd(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const s=this.values.get(e);n!==s&&(s&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let s=this.values.get(e);return s===void 0&&n!==void 0&&(s=Ue(n===null?void 0:n,{owner:this}),this.addValue(e,s)),s}readValue(e,n){let s=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return s!=null&&(typeof s=="string"&&(no(s)||ro(s))?s=parseFloat(s):!hu(s)&&he.test(n)&&(s=Bo(e,n)),this.setBaseTarget(e,Tt(s)?s.get():s)),Tt(s)?s.get():s}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=vr(this.props,n,this.presenceContext?.custom);o&&(s=o[e])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Tt(r)?r:this.initialValues[e]!==void 0&&s===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new Hs),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){ur.render(this.render)}}class da extends id{constructor(){super(...arguments),this.KeyframeResolver=tu}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:s}){delete n[e],delete s[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Tt(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function ha(t,{style:e,vars:n},s,r){const o=t.style;let i;for(i in e)o[i]=e[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function od(t){return window.getComputedStyle(t)}class ad extends da{constructor(){super(...arguments),this.type="html",this.renderInstance=ha}readValueFromInstance(e,n){if(Ge.has(n))return this.projection?.isProjecting?As(n):xl(e,n);{const s=od(e),r=(Zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return la(e,n)}build(e,n,s){gr(e,n,s.transformTemplate)}scrapeMotionValuesFromProps(e,n,s){return br(e,n,s)}}const fa=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function cd(t,e,n,s){ha(t,e,void 0,s);for(const r in e.attrs)t.setAttribute(fa.has(r)?r:wr(r),e.attrs[r])}class ld extends da{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Ge.has(n)){const s=$o(n);return s&&s.default||0}return n=fa.has(n)?n:wr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,s){return na(e,n,s)}build(e,n,s){Zo(e,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(e,n,s,r){cd(e,n,s,r)}mount(e){this.isSVGTag=ta(e.tagName),super.mount(e)}}const ma=(t,e)=>xr(t)?new ld(e):new ad(e,{allowProjection:t!==m.Fragment});function ze(t,e,n){const s=t.getProps();return vr(s,e,n!==void 0?n:s.custom,t)}const Is=t=>Array.isArray(t);function ud(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Ue(n))}function dd(t){return Is(t)?t[t.length-1]||0:t}function hd(t,e){const n=ze(t,e);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=dd(o[i]);ud(t,i,a)}}function fd(t){return!!(Tt(t)&&t.add)}function Os(t,e){const n=t.getValue("willChange");if(fd(n))return n.add(e);if(!n&&Yt.WillChange){const s=new Yt.WillChange("auto");t.addValue("willChange",s),s.add(e)}}function pa(t){return t.props[sa]}const md=t=>t!==null;function pd(t,{repeat:e,repeatType:n="loop"},s){const r=t.filter(md),o=e&&n!=="loop"&&e%2===1?0:r.length-1;return r[o]}const gd={type:"spring",stiffness:500,damping:25,restSpeed:10},yd=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),xd={type:"keyframes",duration:.8},vd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},bd=(t,{keyframes:e})=>e.length>2?xd:Ge.has(t)?t.startsWith("scale")?yd(e[1]):gd:vd;function wd({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const Tr=(t,e,n,s={},r,o)=>i=>{const a=cr(s,t)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-$t(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-u,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:r};wd(a)||Object.assign(l,bd(t,l)),l.duration&&(l.duration=$t(l.duration)),l.repeatDelay&&(l.repeatDelay=$t(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(ks(l),l.delay===0&&(h=!0)),(Yt.instantAnimations||Yt.skipAnimations)&&(h=!0,ks(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&e.get()!==void 0){const f=pd(l.keyframes,a);if(f!==void 0){ot.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new or(l):new zl(l)};function Td({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,s}function ga(t,e,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:i,...a}=e;s&&(o=s);const c=[],u=r&&t.animationState&&t.animationState.getState()[r];for(const l in a){const h=t.getValue(l,t.latestValues[l]??null),f=a[l];if(f===void 0||u&&Td(u,l))continue;const g={delay:n,...cr(o||{},l)},x=h.get();if(x!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===x&&!g.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const T=pa(t);if(T){const w=window.MotionHandoffAnimation(T,l,ot);w!==null&&(g.startTime=w,y=!0)}}Os(t,l),h.start(Tr(l,h,f,t.shouldReduceMotion&&Oo.has(l)?{type:!1}:g,t,y));const S=h.animation;S&&c.push(S)}return i&&Promise.all(c).then(()=>{ot.update(()=>{i&&hd(t,i)})}),c}function ya(t,e,n,s=0,r=1){const o=Array.from(t).sort((u,l)=>u.sortNodePosition(l)).indexOf(e),i=t.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Ls(t,e,n={}){const s=ze(t,e,n.type==="exit"?t.presenceContext?.custom:void 0);let{transition:r=t.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(ga(t,s,n)):()=>Promise.resolve(),i=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return Sd(t,e,c,u,l,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,u]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Sd(t,e,n=0,s=0,r=0,o=1,i){const a=[];for(const c of t.variantChildren)c.notify("AnimationStart",e),a.push(Ls(c,e,{...i,delay:n+(typeof s=="function"?0:s)+ya(t.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(a)}function Ad(t,e,n={}){t.notify("AnimationStart",e);let s;if(Array.isArray(e)){const r=e.map(o=>Ls(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Ls(t,e,n);else{const r=typeof e=="function"?ze(t,e,n.custom):e;s=Promise.all(ga(t,r,n))}return s.then(()=>{t.notify("AnimationComplete",e)})}function xa(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let s=0;s<n;s++)if(e[s]!==t[s])return!1;return!0}const Cd=pr.length;function va(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?va(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Cd;n++){const s=pr[n],r=t.props[s];(mn(r)||r===!1)&&(e[s]=r)}return e}const Pd=[...mr].reverse(),jd=mr.length;function Md(t){return e=>Promise.all(e.map(({animation:n,options:s})=>Ad(t,n,s)))}function kd(t){let e=Md(t),n=mi(),s=!0;const r=c=>(u,l)=>{const h=ze(t,l,c==="exit"?t.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...x}=h;u={...u,...x,...g}}return u};function o(c){e=c(t)}function i(c){const{props:u}=t,l=va(t.parent)||{},h=[],f=new Set;let g={},x=1/0;for(let S=0;S<jd;S++){const T=Pd[S],w=n[T],v=u[T]!==void 0?u[T]:l[T],k=mn(v),V=T===c?w.isActive:null;V===!1&&(x=S);let E=v===l[T]&&v!==u[T]&&k;if(E&&s&&t.manuallyAnimateOnMount&&(E=!1),w.protectedKeys={...g},!w.isActive&&V===null||!v&&!w.prevProp||qn(v)||typeof v=="boolean")continue;const D=Ed(w.prevProp,v);let A=D||T===c&&w.isActive&&!E&&k||S>x&&k,F=!1;const M=Array.isArray(v)?v:[v];let G=M.reduce(r(T),{});V===!1&&(G={});const{prevResolvedValues:H={}}=w,_={...H,...G},Y=nt=>{A=!0,f.has(nt)&&(F=!0,f.delete(nt)),w.needsAnimating[nt]=!0;const ht=t.getValue(nt);ht&&(ht.liveStyle=!1)};for(const nt in _){const ht=G[nt],lt=H[nt];if(g.hasOwnProperty(nt))continue;let st=!1;Is(ht)&&Is(lt)?st=!xa(ht,lt):st=ht!==lt,st?ht!=null?Y(nt):f.add(nt):ht!==void 0&&f.has(nt)?Y(nt):w.protectedKeys[nt]=!0}w.prevProp=v,w.prevResolvedValues=G,w.isActive&&(g={...g,...G}),s&&t.blockInitialAnimation&&(A=!1);const et=E&&D;A&&(!et||F)&&h.push(...M.map(nt=>{const ht={type:T};if(typeof nt=="string"&&s&&!et&&t.manuallyAnimateOnMount&&t.parent){const{parent:lt}=t,st=ze(lt,nt);if(lt.enteringChildren&&st){const{delayChildren:Jt}=st.transition||{};ht.delay=ya(lt.enteringChildren,t,Jt)}}return{animation:nt,options:ht}}))}if(f.size){const S={};if(typeof u.initial!="boolean"){const T=ze(t,Array.isArray(u.initial)?u.initial[0]:u.initial);T&&T.transition&&(S.transition=T.transition)}f.forEach(T=>{const w=t.getBaseTarget(T),v=t.getValue(T);v&&(v.liveStyle=!0),S[T]=w??null}),h.push({animation:S})}let y=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(y=!1),s=!1,y?e(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();t.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const h in n)n[h].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=mi()}}}function Ed(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!xa(e,t):!1}function we(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function mi(){return{animate:we(!0),whileInView:we(),whileHover:we(),whileTap:we(),whileDrag:we(),whileFocus:we(),exit:we()}}class fe{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Dd extends fe{constructor(e){super(e),e.animationState||(e.animationState=kd(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();qn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Nd=0;class Rd extends fe{constructor(){super(...arguments),this.id=Nd++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===s)return;const r=this.node.animationState.setActive("exit",!e);n&&!e&&r.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const ba={animation:{Feature:Dd},exit:{Feature:Rd}};function gn(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function bn(t){return{point:{x:t.pageX,y:t.pageY}}}const Vd=t=>e=>dr(e)&&t(e,bn(e));function on(t,e,n,s){return gn(t,e,Vd(n),s)}const wa=1e-4,Id=1-wa,Od=1+wa,Ta=.01,Ld=0-Ta,Fd=0+Ta;function At(t){return t.max-t.min}function $d(t,e,n){return Math.abs(t-e)<=n}function pi(t,e,n,s=.5){t.origin=s,t.originPoint=ct(e.min,e.max,t.origin),t.scale=At(n)/At(e),t.translate=ct(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Id&&t.scale<=Od||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ld&&t.translate<=Fd||isNaN(t.translate))&&(t.translate=0)}function an(t,e,n,s){pi(t.x,e.x,n.x,s?s.originX:void 0),pi(t.y,e.y,n.y,s?s.originY:void 0)}function gi(t,e,n){t.min=n.min+e.min,t.max=t.min+At(e)}function Bd(t,e,n){gi(t.x,e.x,n.x),gi(t.y,e.y,n.y)}function yi(t,e,n){t.min=e.min-n.min,t.max=t.min+At(e)}function cn(t,e,n){yi(t.x,e.x,n.x),yi(t.y,e.y,n.y)}function Dt(t){return[t("x"),t("y")]}const Sa=({current:t})=>t?t.ownerDocument.defaultView:null,xi=(t,e)=>Math.abs(t-e);function zd(t,e){const n=xi(t.x,e.x),s=xi(t.y,e.y);return Math.sqrt(n**2+s**2)}class Aa{constructor(e,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=us(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,x=zd(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!x)return;const{point:y}=f,{timestamp:S}=vt;this.history.push({...y,timestamp:S});const{onStart:T,onMove:w}=this.handlers;g||(T&&T(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=ls(g,this.transformPagePoint),ot.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:x,onSessionEnd:y,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const T=us(f.type==="pointercancel"?this.lastMoveEventInfo:ls(g,this.transformPagePoint),this.history);this.startEvent&&x&&x(f,T),y&&y(f,T)},!dr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=bn(e),c=ls(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=vt;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(e,us(c,this.history)),this.removeListeners=yn(on(this.contextWindow,"pointermove",this.handlePointerMove),on(this.contextWindow,"pointerup",this.handlePointerUp),on(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),de(this.updatePoint)}}function ls(t,e){return e?{point:e(t.point)}:t}function vi(t,e){return{x:t.x-e.x,y:t.y-e.y}}function us({point:t},e){return{point:t,delta:vi(t,Ca(e)),offset:vi(t,Ud(e)),velocity:_d(e,.1)}}function Ud(t){return t[0]}function Ca(t){return t[t.length-1]}function _d(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,s=null;const r=Ca(t);for(;n>=0&&(s=t[n],!(r.timestamp-s.timestamp>$t(e)));)n--;if(!s)return{x:0,y:0};const o=Nt(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function Wd(t,{min:e,max:n},s){return e!==void 0&&t<e?t=s?ct(e,t,s.min):Math.max(t,e):n!==void 0&&t>n&&(t=s?ct(n,t,s.max):Math.min(t,n)),t}function bi(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function Kd(t,{top:e,left:n,bottom:s,right:r}){return{x:bi(t.x,n,r),y:bi(t.y,e,s)}}function wi(t,e){let n=e.min-t.min,s=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,s]=[s,n]),{min:n,max:s}}function qd(t,e){return{x:wi(t.x,e.x),y:wi(t.y,e.y)}}function Gd(t,e){let n=.5;const s=At(t),r=At(e);return r>s?n=dn(e.min,e.max-s,t.min):s>r&&(n=dn(t.min,t.max-r,e.min)),Ht(0,1,n)}function Hd(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Fs=.35;function Xd(t=Fs){return t===!1?t=0:t===!0&&(t=Fs),{x:Ti(t,"left","right"),y:Ti(t,"top","bottom")}}function Ti(t,e,n){return{min:Si(t,e),max:Si(t,n)}}function Si(t,e){return typeof t=="number"?t:t[e]||0}const Yd=new WeakMap;class Jd{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(bn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:x,onDragStart:y}=this.getProps();if(g&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ru(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Dt(T=>{let w=this.getAxisMotionValue(T).get()||0;if(Wt.test(w)){const{projection:v}=this.visualElement;if(v&&v.layout){const k=v.layout.layoutBox[T];k&&(w=At(k)*(parseFloat(w)/100))}}this.originPoint[T]=w}),y&&ot.postRender(()=>y(h,f)),Os(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:y,onDrag:S}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:T}=f;if(x&&this.currentDirection===null){this.currentDirection=Zd(T),this.currentDirection!==null&&y&&y(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=()=>Dt(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new Aa(e,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:Sa(this.visualElement)})}stop(e,n){const s=e||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ot.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,s){const{drag:r}=this.getProps();if(!s||!En(e,r,this.currentDirection))return;const o=this.getAxisMotionValue(e);let i=this.originPoint[e]+s[e];this.constraints&&this.constraints[e]&&(i=Wd(i,this.constraints[e],this.elastic[e])),o.set(i)}resolveConstraints(){const{dragConstraints:e,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Oe(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&s?this.constraints=Kd(s.layoutBox,e):this.constraints=!1,this.elastic=Xd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Dt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Hd(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Oe(e))return!1;const s=e.current;Xt(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=ed(s,r.root,this.visualElement.getTransformPagePoint());let i=qd(r.layout.layoutBox,o);if(n){const a=n(Zu(i));this.hasMutatedConstraints=!!a,a&&(i=oa(a))}return i}startAnimation(e){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Dt(l=>{if(!En(l,n,this.currentDirection))return;let h=c&&c[l]||{};i&&(h={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,x={type:"inertia",velocity:s?e[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,x)});return Promise.all(u).then(a)}startAxisValueAnimation(e,n){const s=this.getAxisMotionValue(e);return Os(this.visualElement,e),s.start(Tr(e,s,0,n,this.visualElement,!1))}stopAnimation(){Dt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Dt(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(e,(s.initial?s.initial[e]:void 0)||0)}snapToCursor(e){Dt(n=>{const{drag:s}=this.getProps();if(!En(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(e[n]-ct(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Oe(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Dt(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Gd({min:c,max:c},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Dt(i=>{if(!En(i,e,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(ct(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Yd.set(this.visualElement,this);const e=this.visualElement.current,n=on(e,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Oe(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),ot.read(s);const i=gn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Dt(l=>{const h=this.getAxisMotionValue(l);h&&(this.originPoint[l]+=c[l].translate,h.set(h.get()+c[l].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=Fs,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function En(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Zd(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Qd extends fe{constructor(e){super(e),this.removeGroupControls=Rt,this.removeListeners=Rt,this.controls=new Jd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Rt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ai=t=>(e,n)=>{t&&ot.postRender(()=>t(e,n))};class th extends fe{constructor(){super(...arguments),this.removePointerDownListener=Rt}onPointerDown(e){this.session=new Aa(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Sa(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ai(e),onStart:Ai(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ot.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=on(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const On={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ci(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const nn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ci(t,e.target.x),s=Ci(t,e.target.y);return`${n}% ${s}%`}},eh={correct:(t,{treeScale:e,projectionDelta:n})=>{const s=t,r=he.parse(t);if(r.length>5)return s;const o=he.createTransformer(t),i=typeof r[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;r[0+i]/=a,r[1+i]/=c;const u=ct(a,c,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let ds=!1;class nh extends m.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=e;Pu(sh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),ds&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),On.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,ds=!0,r||e.layoutDependency!==n||n===void 0||e.isPresent!==o?i.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?i.promote():i.relegate()||ot.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ur.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=e;ds=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Pa(t){const[e,n]=Go(),s=m.useContext(Us);return d.jsx(nh,{...t,layoutGroup:s,switchLayoutGroup:m.useContext(ra),isPresent:e,safeToRemove:n})}const sh={borderRadius:{...nn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:nn,borderTopRightRadius:nn,borderBottomLeftRadius:nn,borderBottomRightRadius:nn,boxShadow:eh};function rh(t,e,n){const s=Tt(t)?t:Ue(t);return s.start(Tr("",s,e,n)),s.animation}const ih=(t,e)=>t.depth-e.depth;class oh{constructor(){this.children=[],this.isDirty=!1}add(e){Ks(this.children,e),this.isDirty=!0}remove(e){qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(ih),this.isDirty=!1,this.children.forEach(e)}}function ah(t,e){const n=jt.now(),s=({timestamp:r})=>{const o=r-n;o>=e&&(de(s),t(o-e))};return ot.setup(s,!0),()=>de(s)}const ja=["TopLeft","TopRight","BottomLeft","BottomRight"],ch=ja.length,Pi=t=>typeof t=="string"?parseFloat(t):t,ji=t=>typeof t=="number"||z.test(t);function lh(t,e,n,s,r,o){r?(t.opacity=ct(0,n.opacity??1,uh(s)),t.opacityExit=ct(e.opacity??1,0,dh(s))):o&&(t.opacity=ct(e.opacity??1,n.opacity??1,s));for(let i=0;i<ch;i++){const a=`border${ja[i]}Radius`;let c=Mi(e,a),u=Mi(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||ji(c)===ji(u)?(t[a]=Math.max(ct(Pi(c),Pi(u),s),0),(Wt.test(u)||Wt.test(c))&&(t[a]+="%")):t[a]=u}(e.rotate||n.rotate)&&(t.rotate=ct(e.rotate||0,n.rotate||0,s))}function Mi(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const uh=Ma(0,.5,fo),dh=Ma(.5,.95,Rt);function Ma(t,e,n){return s=>s<t?0:s>e?1:n(dn(t,e,s))}function ki(t,e){t.min=e.min,t.max=e.max}function Et(t,e){ki(t.x,e.x),ki(t.y,e.y)}function Ei(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Di(t,e,n,s,r){return t-=e,t=_n(t,1/n,s),r!==void 0&&(t=_n(t,1/r,s)),t}function hh(t,e=0,n=1,s=.5,r,o=t,i=t){if(Wt.test(e)&&(e=parseFloat(e),e=ct(i.min,i.max,e/100)-i.min),typeof e!="number")return;let a=ct(o.min,o.max,s);t===o&&(a-=e),t.min=Di(t.min,e,n,a,r),t.max=Di(t.max,e,n,a,r)}function Ni(t,e,[n,s,r],o,i){hh(t,e[n],e[s],e[r],e.scale,o,i)}const fh=["x","scaleX","originX"],mh=["y","scaleY","originY"];function Ri(t,e,n,s){Ni(t.x,e,fh,n?n.x:void 0,s?s.x:void 0),Ni(t.y,e,mh,n?n.y:void 0,s?s.y:void 0)}function Vi(t){return t.translate===0&&t.scale===1}function ka(t){return Vi(t.x)&&Vi(t.y)}function Ii(t,e){return t.min===e.min&&t.max===e.max}function ph(t,e){return Ii(t.x,e.x)&&Ii(t.y,e.y)}function Oi(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ea(t,e){return Oi(t.x,e.x)&&Oi(t.y,e.y)}function Li(t){return At(t.x)/At(t.y)}function Fi(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class gh{constructor(){this.members=[]}add(e){Ks(this.members,e),e.scheduleRender()}remove(e){if(qs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(r=>e===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(e,n){const s=this.lead;if(e!==s&&(this.prevLead=s,this.lead=e,e.show(),s)){s.instance&&s.scheduleRender(),e.scheduleRender(),e.resumeFrom=s,n&&(e.resumeFrom.preserveOpacity=!0),s.snapshot&&(e.snapshot=s.snapshot,e.snapshot.latestValues=s.animationValues||s.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:r}=e.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:s}=e;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function yh(t,e,n){let s="";const r=t.x.translate/e.x,o=t.y.translate/e.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(e.x!==1||e.y!==1)&&(s+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:u,rotate:l,rotateX:h,rotateY:f,skewX:g,skewY:x}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),h&&(s+=`rotateX(${h}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),x&&(s+=`skewY(${x}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const hs=["","X","Y","Z"],xh=1e3;let vh=0;function fs(t,e,n,s){const{latestValues:r}=e;r[t]&&(n[t]=r[t],e.setStaticValue(t,0),s&&(s[t]=0))}function Da(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=pa(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ot,!(r||o))}const{parent:s}=t;s&&!s.hasCheckedOptimisedAppear&&Da(s)}function Na({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=e?.()){this.id=vh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Th),this.nodes.forEach(Ph),this.nodes.forEach(jh),this.nodes.forEach(Sh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new oh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Hs),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const c=this.eventHandlers.get(i);c&&c.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=qo(i)&&!uu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let l,h=0;const f=()=>this.root.updateBlockedByResize=!1;ot.read(()=>{h=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=ah(f,250),On.hasAnimatedSinceResize&&(On.hasAnimatedSinceResize=!1,this.nodes.forEach(zi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:h,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const x=this.options.transition||u.getDefaultTransition()||Nh,{onLayoutAnimationStart:y,onLayoutAnimationComplete:S}=u.getProps(),T=!this.targetLayout||!Ea(this.targetLayout,g),w=!h&&f;if(this.options.layoutRoot||this.resumeFrom||w||h&&(T||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...cr(x,"layout"),onPlay:y,onComplete:S};(u.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(l,w)}else h||zi(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),de(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Mh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Da(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const h=this.path[l];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach($i);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bi);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Ch),this.nodes.forEach(bh),this.nodes.forEach(wh)):this.nodes.forEach(Bi),this.clearAllSnapshots();const a=jt.now();vt.delta=Ht(0,1e3/60,a-vt.timestamp),vt.timestamp=a,vt.isProcessing=!0,es.update.process(vt),es.preRender.process(vt),es.render.process(vt),vt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ur.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ah),this.sharedNodes.forEach(kh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ot.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ot.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!At(this.snapshot.measuredBox.x)&&!At(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ft(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const c=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!ka(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Se(this.latestValues)||l)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return i&&(c=this.removeTransform(c)),Rh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ft();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Vh))){const{scroll:u}=this.root;u&&(Le(a.x,u.offset.x),Le(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ft();if(Et(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:h}=u;u!==this.root&&l&&h.layoutScroll&&(l.wasRoot&&Et(a,i),Le(a.x,l.offset.x),Le(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=ft();Et(c,i);for(let u=0;u<this.path.length;u++){const l=this.path[u];!a&&l.options.layoutScroll&&l.scroll&&l!==l.root&&Fe(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),Se(l.latestValues)&&Fe(c,l.latestValues)}return Se(this.latestValues)&&Fe(c,this.latestValues),c}removeTransform(i){const a=ft();Et(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Se(u.latestValues))continue;Ns(u.latestValues)&&u.updateSnapshot();const l=ft(),h=u.measurePageBox();Et(l,h),Ri(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return Se(this.latestValues)&&Ri(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==vt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:l,layoutId:h}=this.options;if(!(!this.layout||!(l||h))){if(this.resolvedRelativeTargetAt=vt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ft(),this.targetWithTransforms=ft()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Bd(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Et(this.target,this.layout.layoutBox),ca(this.target,this.targetDelta)):Et(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const f=this.getClosestProjectingParent();f&&!!f.resumingFrom==!!this.resumingFrom&&!f.options.layoutScroll&&f.target&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.target,f.target),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ns(this.parent.latestValues)||aa(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let c=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===vt.timestamp&&(c=!1),c)return;const{layout:u,layoutId:l}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||l))return;Et(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;td(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ft());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ei(this.prevProjectionDelta.x,this.projectionDelta.x),Ei(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Fi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Fi(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=$e(),this.projectionDelta=$e(),this.projectionDeltaWithTransform=$e()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=$e();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ft(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,y=g!==x,S=this.getStack(),T=!S||S.members.length<=1,w=!!(y&&!T&&this.options.crossfade===!0&&!this.path.some(Dh));this.animationProgress=0;let v;this.mixTargetDelta=k=>{const V=k/1e3;Ui(h.x,i.x,V),Ui(h.y,i.y,V),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Eh(this.relativeTarget,this.relativeTargetOrigin,f,V),v&&ph(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=ft()),Et(v,this.relativeTarget)),y&&(this.animationValues=l,lh(l,u,this.latestValues,V,w,T)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=V},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(de(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ot.update(()=>{On.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ue(0)),this.currentAnimation=rh(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(xh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:c,layout:u,latestValues:l}=i;if(!(!a||!c||!u)){if(this!==i&&this.layout&&u&&Ra(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||ft();const h=At(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=At(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Et(a,c),Fe(a,l),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new gh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:c}={}){const u=this.getStack();u&&u.promote(this,c),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:c}=i;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const u={};c.z&&fs("z",i,u,this.animationValues);for(let l=0;l<hs.length;l++)fs(`rotate${hs[l]}`,i,u,this.animationValues),fs(`skew${hs[l]}`,i,u,this.animationValues);i.render();for(const l in u)i.setStaticValue(l,u[l]),this.animationValues&&(this.animationValues[l]=u[l]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=Vn(a?.pointerEvents)||"",i.transform=c?c(this.latestValues,""):"none";return}const u=this.getLead();if(!this.projectionDelta||!this.layout||!u.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=Vn(a?.pointerEvents)||""),this.hasProjected&&!Se(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=yh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(h=c(l,h)),i.transform=h;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?l.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:l.opacityExit:i.opacity=u===this?l.opacity!==void 0?l.opacity:"":l.opacityExit!==void 0?l.opacityExit:0;for(const x in pn){if(l[x]===void 0)continue;const{correct:y,applyTo:S,isCSSVariable:T}=pn[x],w=h==="none"?l[x]:y(l[x],u);if(S){const v=S.length;for(let k=0;k<v;k++)i[S[k]]=w}else T?this.options.visualElement.renderState.vars[x]=w:i[x]=w}this.options.layoutId&&(i.pointerEvents=u===this?Vn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach($i),this.root.sharedNodes.clear()}}}function bh(t){t.updateLayout()}function wh(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:r}=t.options,o=e.source!==t.layout.source;r==="size"?Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(h);h.min=n[l].min,h.max=h.min+f}):Ra(r,e.layoutBox,n)&&Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(n[l]);h.max=h.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[l].max=t.relativeTarget[l].min+f)});const i=$e();an(i,n,e.layoutBox);const a=$e();o?an(a,t.applyTransform(s,!0),e.measuredBox):an(a,n,e.layoutBox);const c=!ka(i);let u=!1;if(!t.resumeFrom){const l=t.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:h,layout:f}=l;if(h&&f){const g=ft();cn(g,e.layoutBox,h.layoutBox);const x=ft();cn(x,n,f.layoutBox),Ea(g,x)||(u=!0),l.options.layoutRoot&&(t.relativeTarget=x,t.relativeTargetOrigin=g,t.relativeParent=l)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Th(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Sh(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Ah(t){t.clearSnapshot()}function $i(t){t.clearMeasurements()}function Bi(t){t.isLayoutDirty=!1}function Ch(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function zi(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Ph(t){t.resolveTargetDelta()}function jh(t){t.calcProjection()}function Mh(t){t.resetSkewAndRotation()}function kh(t){t.removeLeadSnapshot()}function Ui(t,e,n){t.translate=ct(e.translate,0,n),t.scale=ct(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function _i(t,e,n,s){t.min=ct(e.min,n.min,s),t.max=ct(e.max,n.max,s)}function Eh(t,e,n,s){_i(t.x,e.x,n.x,s),_i(t.y,e.y,n.y,s)}function Dh(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Nh={duration:.45,ease:[.4,0,.1,1]},Wi=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Ki=Wi("applewebkit/")&&!Wi("chrome/")?Math.round:Rt;function qi(t){t.min=Ki(t.min),t.max=Ki(t.max)}function Rh(t){qi(t.x),qi(t.y)}function Ra(t,e,n){return t==="position"||t==="preserve-aspect"&&!$d(Li(e),Li(n),.2)}function Vh(t){return t!==t.root&&t.scroll?.wasRoot}const Ih=Na({attachResizeListener:(t,e)=>gn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ms={current:void 0},Va=Na({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ms.current){const t=new Ih({});t.mount(window),t.setOptions({layoutScroll:!0}),ms.current=t}return ms.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Oh={pan:{Feature:th},drag:{Feature:Qd,ProjectionNode:Va,MeasureLayout:Pa}};function Gi(t,e,n){const{props:s}=t;t.animationState&&s.whileHover&&t.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ot.postRender(()=>o(e,bn(e)))}class Lh extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=iu(e,(n,s)=>(Gi(this.node,s,"Start"),r=>Gi(this.node,r,"End"))))}unmount(){}}class Fh extends fe{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=yn(gn(this.node.current,"focus",()=>this.onFocus()),gn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Hi(t,e,n){const{props:s}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&s.whileTap&&t.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ot.postRender(()=>o(e,bn(e)))}class $h extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=lu(e,(n,s)=>(Hi(this.node,s,"Start"),(r,{success:o})=>Hi(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $s=new WeakMap,ps=new WeakMap,Bh=t=>{const e=$s.get(t.target);e&&e(t)},zh=t=>{t.forEach(Bh)};function Uh({root:t,...e}){const n=t||document;ps.has(n)||ps.set(n,{});const s=ps.get(n),r=JSON.stringify(e);return s[r]||(s[r]=new IntersectionObserver(zh,{root:t,...e})),s[r]}function _h(t,e,n){const s=Uh(e);return $s.set(t,n),s.observe(t),()=>{$s.delete(t),s.unobserve(t)}}const Wh={some:0,all:1};class Kh extends fe{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=e,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:Wh[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:l,onViewportLeave:h}=this.node.getProps(),f=u?l:h;f&&f(c)};return _h(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(qh(e,n))&&this.startObserver()}unmount(){}}function qh({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Ia={inView:{Feature:Kh},tap:{Feature:$h},focus:{Feature:Fh},hover:{Feature:Lh}},Gh={layout:{ProjectionNode:Va,MeasureLayout:Pa}},Hh={...ba,...Ia,...Oh,...Gh},Xh=Ju(Hh,ma),Yh={renderer:ma,...ba,...Ia};function Sr(t,e){return In(t,e)}const Jh=Sr("button"),Dn=Sr("div"),Zh=Sr("p"),_t=Symbol.for("@arcteninc/core:originalName");function Qh(t,e){return t[_t]=e,t}function tf(t,e,n,s){if(typeof t!="function")return null;const r=t[_t];if(r){const a=e[r];if(a&&!n.has(a.name))return{fn:t,meta:a}}const o=t.name;let i;if(o&&(i=e[o],i&&!n.has(i.name)))return t[_t]=i.name,{fn:t,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=e[a],i))return t[_t]=i.name,{fn:t,meta:i}}else if(i=Object.values(e).find(c=>!n.has(c.name)),i)return t[_t]=i.name,{fn:t,meta:i};return null}function Oa(t,e){let n,s;if(!e)throw new Error(`❌ toolMetadata is required!
9
+ `),()=>{w.contains(T)&&w.removeChild(T)}},[e]),d.jsx(pu,{isPresent:e,childRef:o,sizeRef:i,children:Ft.cloneElement(t,{ref:c})})}const yu=({children:t,initial:e,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:c})=>{const u=_s(xu),l=m.useId();let h=!0,f=m.useMemo(()=>(h=!1,{id:l,initial:e,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const S of u.values())if(!S)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&h&&(f={...f}),m.useMemo(()=>{u.forEach((g,S)=>u.set(S,!1))},[n]),Ft.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),i==="popLayout"&&(t=d.jsx(gu,{isPresent:n,anchorX:a,root:c,children:t})),d.jsx(Wn.Provider,{value:f,children:t})};function xu(){return new Map}function Go(t=!0){const e=m.useContext(Wn);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=e,o=m.useId();m.useEffect(()=>{if(t)return r(o)},[t]);const i=m.useCallback(()=>t&&s&&s(o),[o,s,t]);return!n&&s?[!1,i]:[!0]}const Mn=t=>t.key||"";function ni(t){const e=[];return m.Children.forEach(t,n=>{m.isValidElement(n)&&e.push(n)}),e}const vu=({children:t,custom:e,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:c})=>{const[u,l]=Go(i),h=m.useMemo(()=>ni(t),[t]),f=i&&!u?[]:h.map(Mn),g=m.useRef(!0),S=m.useRef(h),T=_s(()=>new Map),[w,y]=m.useState(h),[v,x]=m.useState(h);eo(()=>{g.current=!1,S.current=h;for(let E=0;E<v.length;E++){const D=Mn(v[E]);f.includes(D)?T.delete(D):T.get(D)!==!0&&T.set(D,!1)}},[v,f.length,f.join("-")]);const M=[];if(h!==w){let E=[...h];for(let D=0;D<v.length;D++){const A=v[D],F=Mn(A);f.includes(F)||(E.splice(D,0,A),M.push(A))}return o==="wait"&&M.length&&(E=M),x(ni(E)),y(h),null}process.env.NODE_ENV!=="production"&&o==="wait"&&v.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:j}=m.useContext(Us);return d.jsx(d.Fragment,{children:v.map(E=>{const D=Mn(E),A=i&&!u?!1:h===v||f.includes(D),F=()=>{if(T.has(D))T.set(D,!0);else return;let I=!0;T.forEach(X=>{X||(I=!1)}),I&&(j?.(),x(S.current),i&&l?.(),s&&s())};return d.jsx(yu,{isPresent:A,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:r,mode:o,root:c,onExitComplete:A?void 0:F,anchorX:a,children:E},D)})})},fr=m.createContext({strict:!1}),si={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},_e={};for(const t in si)_e[t]={isEnabled:e=>si[t].some(n=>!!e[n])};function Ds(t){for(const e in t)_e[e]={..._e[e],...t[e]}}function bu({children:t,features:e,strict:n=!1}){const[,s]=m.useState(!as(e)),r=m.useRef(void 0);if(!as(e)){const{renderer:o,...i}=e;r.current=o,Ds(i)}return m.useEffect(()=>{as(e)&&e().then(({renderer:o,...i})=>{Ds(i),r.current=o,s(!0)})},[]),d.jsx(fr.Provider,{value:{renderer:r.current,strict:n},children:t})}function as(t){return typeof t=="function"}const wu=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Un(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||wu.has(t)}let Ho=t=>!Un(t);function Tu(t){typeof t=="function"&&(Ho=e=>e.startsWith("on")?!Un(e):t(e))}try{Tu(require("@emotion/is-prop-valid").default)}catch{}function Su(t,e,n){const s={};for(const r in t)r==="values"&&typeof t.values=="object"||(Ho(r)||n===!0&&Un(r)||!e&&!Un(r)||t.draggable&&r.startsWith("onDrag"))&&(s[r]=t[r]);return s}const Kn=m.createContext({});function qn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function mn(t){return typeof t=="string"||Array.isArray(t)}const mr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],pr=["initial",...mr];function Gn(t){return qn(t.animate)||pr.some(e=>mn(t[e]))}function Xo(t){return!!(Gn(t)||t.variants)}function Au(t,e){if(Gn(t)){const{initial:n,animate:s}=t;return{initial:n===!1||mn(n)?n:void 0,animate:mn(s)?s:void 0}}return t.inherit!==!1?e:{}}function Cu(t){const{initial:e,animate:n}=Au(t,m.useContext(Kn));return m.useMemo(()=>({initial:e,animate:n}),[ri(e),ri(n)])}function ri(t){return Array.isArray(t)?t.join(" "):t}const pn={};function Pu(t){for(const e in t)pn[e]=t[e],Zs(e)&&(pn[e].isCSSVariable=!0)}function Yo(t,{layout:e,layoutId:n}){return Ge.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!pn[t]||t==="opacity")}const ju={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ku=qe.length;function Mu(t,e,n){let s="",r=!0;for(let o=0;o<ku;o++){const i=qe[o],a=t[i];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(i.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const u=zo(a,lr[i]);if(!c){r=!1;const l=ju[i]||i;s+=`${l}(${u}) `}n&&(e[i]=u)}}return s=s.trim(),n?s=n(e,r?"":s):r&&(s="none"),s}function gr(t,e,n){const{style:s,vars:r,transformOrigin:o}=t;let i=!1,a=!1;for(const c in e){const u=e[c];if(Ge.has(c)){i=!0;continue}else if(Zs(c)){r[c]=u;continue}else{const l=zo(u,lr[c]);c.startsWith("origin")?(a=!0,o[c]=l):s[c]=l}}if(e.transform||(i||n?s.transform=Mu(e,t.transform,n):s.transform&&(s.transform="none")),a){const{originX:c="50%",originY:u="50%",originZ:l=0}=o;s.transformOrigin=`${c} ${u} ${l}`}}const yr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Jo(t,e,n){for(const s in e)!Tt(e[s])&&!Yo(s,n)&&(t[s]=e[s])}function Eu({transformTemplate:t},e){return m.useMemo(()=>{const n=yr();return gr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Du(t,e){const n=t.style||{},s={};return Jo(s,n,t),Object.assign(s,Eu(t,e)),s}function Nu(t,e){const n={},s=Du(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=s,n}const Ru={offset:"stroke-dashoffset",array:"stroke-dasharray"},Vu={offset:"strokeDashoffset",array:"strokeDasharray"};function Iu(t,e,n=1,s=0,r=!0){t.pathLength=1;const o=r?Ru:Vu;t[o.offset]=z.transform(-s);const i=z.transform(e),a=z.transform(n);t[o.array]=`${i} ${a}`}function Zo(t,{attrX:e,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},c,u,l){if(gr(t,a,u),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:f}=t;h.transform&&(f.transform=h.transform,delete h.transform),(f.transform||h.transformOrigin)&&(f.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),f.transform&&(f.transformBox=l?.transformBox??"fill-box",delete h.transformBox),e!==void 0&&(h.x=e),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),r!==void 0&&Iu(h,r,o,i,!1)}const Qo=()=>({...yr(),attrs:{}}),ta=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Ou(t,e,n,s){const r=m.useMemo(()=>{const o=Qo();return Zo(o,e,ta(s),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Jo(o,t.style,t),r.style={...o,...r.style}}return r}const Lu=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function xr(t){return typeof t!="string"||t.includes("-")?!1:!!(Lu.indexOf(t)>-1||/[A-Z]/u.test(t))}function Fu(t,e,n,{latestValues:s},r,o=!1){const a=(xr(t)?Ou:Nu)(e,s,r,t),c=Su(e,typeof t=="string",o),u=t!==m.Fragment?{...c,...a,ref:n}:{},{children:l}=e,h=m.useMemo(()=>Tt(l)?l.get():l,[l]);return m.createElement(t,{...u,children:h})}function ii(t){const e=[{},{}];return t?.values.forEach((n,s)=>{e[0][s]=n.get(),e[1][s]=n.getVelocity()}),e}function vr(t,e,n,s){if(typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[r,o]=ii(s);e=e(n!==void 0?n:t.custom,r,o)}return e}function Vn(t){return Tt(t)?t.get():t}function $u({scrapeMotionValuesFromProps:t,createRenderState:e},n,s,r){return{latestValues:Bu(n,s,r,t),renderState:e()}}function Bu(t,e,n,s){const r={},o=s(t,{});for(const f in o)r[f]=Vn(o[f]);let{initial:i,animate:a}=t;const c=Gn(t),u=Xo(t);e&&u&&!c&&t.inherit!==!1&&(i===void 0&&(i=e.initial),a===void 0&&(a=e.animate));let l=n?n.initial===!1:!1;l=l||i===!1;const h=l?a:i;if(h&&typeof h!="boolean"&&!qn(h)){const f=Array.isArray(h)?h:[h];for(let g=0;g<f.length;g++){const S=vr(t,f[g]);if(S){const{transitionEnd:T,transition:w,...y}=S;for(const v in y){let x=y[v];if(Array.isArray(x)){const M=l?x.length-1:0;x=x[M]}x!==null&&(r[v]=x)}for(const v in T)r[v]=T[v]}}}return r}const ea=t=>(e,n)=>{const s=m.useContext(Kn),r=m.useContext(Wn),o=()=>$u(t,e,s,r);return n?o():_s(o)};function br(t,e,n){const{style:s}=t,r={};for(const o in s)(Tt(s[o])||e.style&&Tt(e.style[o])||Yo(o,t)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const zu=ea({scrapeMotionValuesFromProps:br,createRenderState:yr});function na(t,e,n){const s=br(t,e,n);for(const r in t)if(Tt(t[r])||Tt(e[r])){const o=qe.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=t[r]}return s}const Uu=ea({scrapeMotionValuesFromProps:na,createRenderState:Qo}),_u=Symbol.for("motionComponentSymbol");function Oe(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Wu(t,e,n){return m.useCallback(s=>{s&&t.onMount&&t.onMount(s),e&&(s?e.mount(s):e.unmount()),n&&(typeof n=="function"?n(s):Oe(n)&&(n.current=s))},[e])}const wr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Ku="framerAppearId",sa="data-"+wr(Ku),ra=m.createContext({});function qu(t,e,n,s,r){const{visualElement:o}=m.useContext(Kn),i=m.useContext(fr),a=m.useContext(Wn),c=m.useContext(hr).reducedMotion,u=m.useRef(null);s=s||i.renderer,!u.current&&s&&(u.current=s(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const l=u.current,h=m.useContext(ra);l&&!l.projection&&r&&(l.type==="html"||l.type==="svg")&&Gu(u.current,n,r,h);const f=m.useRef(!1);m.useInsertionEffect(()=>{l&&f.current&&l.update(n,a)});const g=n[sa],S=m.useRef(!!g&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return eo(()=>{l&&(f.current=!0,window.MotionIsMounted=!0,l.updateFeatures(),l.scheduleRenderMicrotask(),S.current&&l.animationState&&l.animationState.animateChanges())}),m.useEffect(()=>{l&&(!S.current&&l.animationState&&l.animationState.animateChanges(),S.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),S.current=!1),l.enteringChildren=void 0)}),l}function Gu(t,e,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutCrossfade:l}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:ia(t.parent)),t.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Oe(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:l,layoutScroll:c,layoutRoot:u})}function ia(t){if(t)return t.options.allowProjection!==!1?t.projection:ia(t.parent)}function In(t,{forwardMotionProps:e=!1}={},n,s){n&&Ds(n);const r=xr(t)?Uu:zu;function o(a,c){let u;const l={...m.useContext(hr),...a,layoutId:Hu(a)},{isStatic:h}=l,f=Cu(a),g=r(a,h);if(!h&&Ws){Xu(l,n);const S=Yu(l);u=S.MeasureLayout,f.visualElement=qu(t,g,l,s,S.ProjectionNode)}return d.jsxs(Kn.Provider,{value:f,children:[u&&f.visualElement?d.jsx(u,{visualElement:f.visualElement,...l}):null,Fu(t,a,Wu(g,f.visualElement,c),g,h,e)]})}o.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const i=m.forwardRef(o);return i[_u]=t,i}function Hu({layoutId:t}){const e=m.useContext(Us).id;return e&&t!==void 0?e+"-"+t:t}function Xu(t,e){const n=m.useContext(fr).strict;if(process.env.NODE_ENV!=="production"&&e&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";t.ignoreStrict?We(!1,s,"lazy-strict-mode"):Xt(!1,s,"lazy-strict-mode")}}function Yu(t){const{drag:e,layout:n}=_e;if(!e&&!n)return{};const s={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Ju(t,e){if(typeof Proxy>"u")return In;const n=new Map,s=(o,i)=>In(o,i,t,e),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Xs(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,In(i,void 0,t,e)),n.get(i))})}function oa({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}function Zu({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Qu(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function cs(t){return t===void 0||t===1}function Ns({scale:t,scaleX:e,scaleY:n}){return!cs(t)||!cs(e)||!cs(n)}function Se(t){return Ns(t)||aa(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function aa(t){return oi(t.x)||oi(t.y)}function oi(t){return t&&t!=="0%"}function _n(t,e,n){const s=t-n,r=e*s;return n+r}function ai(t,e,n,s,r){return r!==void 0&&(t=_n(t,r,s)),_n(t,n,s)+e}function Rs(t,e=0,n=1,s,r){t.min=ai(t.min,e,n,s,r),t.max=ai(t.max,e,n,s,r)}function ca(t,{x:e,y:n}){Rs(t.x,e.translate,e.scale,e.originPoint),Rs(t.y,n.translate,n.scale,n.originPoint)}const ci=.999999999999,li=1.0000000000001;function td(t,e,n,s=!1){const r=n.length;if(!r)return;e.x=e.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Fe(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(e.x*=i.x.scale,e.y*=i.y.scale,ca(t,i)),s&&Se(o.latestValues)&&Fe(t,o.latestValues))}e.x<li&&e.x>ci&&(e.x=1),e.y<li&&e.y>ci&&(e.y=1)}function Le(t,e){t.min=t.min+e,t.max=t.max+e}function ui(t,e,n,s,r=.5){const o=ut(t.min,t.max,r);Rs(t,e,n,o,s)}function Fe(t,e){ui(t.x,e.x,e.scaleX,e.scale,e.originX),ui(t.y,e.y,e.scaleY,e.scale,e.originY)}function la(t,e){return oa(Qu(t.getBoundingClientRect(),e))}function ed(t,e,n){const s=la(t,n),{scroll:r}=e;return r&&(Le(s.x,r.offset.x),Le(s.y,r.offset.y)),s}const di=()=>({translate:0,scale:1,origin:0,originPoint:0}),$e=()=>({x:di(),y:di()}),hi=()=>({min:0,max:0}),ft=()=>({x:hi(),y:hi()}),Vs={current:null},ua={current:!1};function nd(){if(ua.current=!0,!!Ws)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Vs.current=t.matches;t.addEventListener("change",e),e()}else Vs.current=!1}const sd=new WeakMap;function rd(t,e,n){for(const s in e){const r=e[s],o=n[s];if(Tt(r))t.addValue(s,r);else if(Tt(o))t.addValue(s,Ue(r,{owner:t}));else if(o!==r)if(t.hasValue(s)){const i=t.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=t.getStaticValue(s);t.addValue(s,Ue(i!==void 0?i:r,{owner:t}))}}for(const s in n)e[s]===void 0&&t.removeValue(s);return e}const fi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class id{scrapeMotionValuesFromProps(e,n,s){return{}}constructor({parent:e,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ar,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=jt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ct.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=i;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=e,this.props=n,this.presenceContext=s,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Gn(n),this.isVariantNode=Xo(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:l,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const g=h[f];c[f]!==void 0&&Tt(g)&&g.set(c[f])}}mount(e){this.current=e,sd.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),ua.current||nd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Vs.current,process.env.NODE_ENV!=="production"&&Xs(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),de(this.notifyUpdate),de(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const s=Ge.has(e);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[e]=i,this.props.onUpdate&&ct.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in _e){const n=_e[e];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[e]&&r&&s(this.props)&&(this.features[e]=new r(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<fi.length;s++){const r=fi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=e[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=rd(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const s=this.values.get(e);n!==s&&(s&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let s=this.values.get(e);return s===void 0&&n!==void 0&&(s=Ue(n===null?void 0:n,{owner:this}),this.addValue(e,s)),s}readValue(e,n){let s=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return s!=null&&(typeof s=="string"&&(no(s)||ro(s))?s=parseFloat(s):!hu(s)&&he.test(n)&&(s=Bo(e,n)),this.setBaseTarget(e,Tt(s)?s.get():s)),Tt(s)?s.get():s}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=vr(this.props,n,this.presenceContext?.custom);o&&(s=o[e])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Tt(r)?r:this.initialValues[e]!==void 0&&s===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new Hs),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){ur.render(this.render)}}class da extends id{constructor(){super(...arguments),this.KeyframeResolver=tu}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:s}){delete n[e],delete s[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Tt(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function ha(t,{style:e,vars:n},s,r){const o=t.style;let i;for(i in e)o[i]=e[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function od(t){return window.getComputedStyle(t)}class ad extends da{constructor(){super(...arguments),this.type="html",this.renderInstance=ha}readValueFromInstance(e,n){if(Ge.has(n))return this.projection?.isProjecting?As(n):xl(e,n);{const s=od(e),r=(Zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return la(e,n)}build(e,n,s){gr(e,n,s.transformTemplate)}scrapeMotionValuesFromProps(e,n,s){return br(e,n,s)}}const fa=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function cd(t,e,n,s){ha(t,e,void 0,s);for(const r in e.attrs)t.setAttribute(fa.has(r)?r:wr(r),e.attrs[r])}class ld extends da{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Ge.has(n)){const s=$o(n);return s&&s.default||0}return n=fa.has(n)?n:wr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,s){return na(e,n,s)}build(e,n,s){Zo(e,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(e,n,s,r){cd(e,n,s,r)}mount(e){this.isSVGTag=ta(e.tagName),super.mount(e)}}const ma=(t,e)=>xr(t)?new ld(e):new ad(e,{allowProjection:t!==m.Fragment});function ze(t,e,n){const s=t.getProps();return vr(s,e,n!==void 0?n:s.custom,t)}const Is=t=>Array.isArray(t);function ud(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Ue(n))}function dd(t){return Is(t)?t[t.length-1]||0:t}function hd(t,e){const n=ze(t,e);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=dd(o[i]);ud(t,i,a)}}function fd(t){return!!(Tt(t)&&t.add)}function Os(t,e){const n=t.getValue("willChange");if(fd(n))return n.add(e);if(!n&&Yt.WillChange){const s=new Yt.WillChange("auto");t.addValue("willChange",s),s.add(e)}}function pa(t){return t.props[sa]}const md=t=>t!==null;function pd(t,{repeat:e,repeatType:n="loop"},s){const r=t.filter(md),o=e&&n!=="loop"&&e%2===1?0:r.length-1;return r[o]}const gd={type:"spring",stiffness:500,damping:25,restSpeed:10},yd=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),xd={type:"keyframes",duration:.8},vd={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},bd=(t,{keyframes:e})=>e.length>2?xd:Ge.has(t)?t.startsWith("scale")?yd(e[1]):gd:vd;function wd({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:c,elapsed:u,...l}){return!!Object.keys(l).length}const Tr=(t,e,n,s={},r,o)=>i=>{const a=cr(s,t)||{},c=a.delay||s.delay||0;let{elapsed:u=0}=s;u=u-$t(c);const l={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-u,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:r};wd(a)||Object.assign(l,bd(t,l)),l.duration&&(l.duration=$t(l.duration)),l.repeatDelay&&(l.repeatDelay=$t(l.repeatDelay)),l.from!==void 0&&(l.keyframes[0]=l.from);let h=!1;if((l.type===!1||l.duration===0&&!l.repeatDelay)&&(Ms(l),l.delay===0&&(h=!0)),(Yt.instantAnimations||Yt.skipAnimations)&&(h=!0,Ms(l),l.delay=0),l.allowFlatten=!a.type&&!a.ease,h&&!o&&e.get()!==void 0){const f=pd(l.keyframes,a);if(f!==void 0){ct.update(()=>{l.onUpdate(f),l.onComplete()});return}}return a.isSync?new or(l):new zl(l)};function Td({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,s}function ga(t,e,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:i,...a}=e;s&&(o=s);const c=[],u=r&&t.animationState&&t.animationState.getState()[r];for(const l in a){const h=t.getValue(l,t.latestValues[l]??null),f=a[l];if(f===void 0||u&&Td(u,l))continue;const g={delay:n,...cr(o||{},l)},S=h.get();if(S!==void 0&&!h.isAnimating&&!Array.isArray(f)&&f===S&&!g.velocity)continue;let T=!1;if(window.MotionHandoffAnimation){const y=pa(t);if(y){const v=window.MotionHandoffAnimation(y,l,ct);v!==null&&(g.startTime=v,T=!0)}}Os(t,l),h.start(Tr(l,h,f,t.shouldReduceMotion&&Oo.has(l)?{type:!1}:g,t,T));const w=h.animation;w&&c.push(w)}return i&&Promise.all(c).then(()=>{ct.update(()=>{i&&hd(t,i)})}),c}function ya(t,e,n,s=0,r=1){const o=Array.from(t).sort((u,l)=>u.sortNodePosition(l)).indexOf(e),i=t.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function Ls(t,e,n={}){const s=ze(t,e,n.type==="exit"?t.presenceContext?.custom:void 0);let{transition:r=t.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(ga(t,s,n)):()=>Promise.resolve(),i=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:l,staggerDirection:h}=r;return Sd(t,e,c,u,l,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[c,u]=a==="beforeChildren"?[o,i]:[i,o];return c().then(()=>u())}else return Promise.all([o(),i(n.delay)])}function Sd(t,e,n=0,s=0,r=0,o=1,i){const a=[];for(const c of t.variantChildren)c.notify("AnimationStart",e),a.push(Ls(c,e,{...i,delay:n+(typeof s=="function"?0:s)+ya(t.variantChildren,c,s,r,o)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(a)}function Ad(t,e,n={}){t.notify("AnimationStart",e);let s;if(Array.isArray(e)){const r=e.map(o=>Ls(t,o,n));s=Promise.all(r)}else if(typeof e=="string")s=Ls(t,e,n);else{const r=typeof e=="function"?ze(t,e,n.custom):e;s=Promise.all(ga(t,r,n))}return s.then(()=>{t.notify("AnimationComplete",e)})}function xa(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let s=0;s<n;s++)if(e[s]!==t[s])return!1;return!0}const Cd=pr.length;function va(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?va(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Cd;n++){const s=pr[n],r=t.props[s];(mn(r)||r===!1)&&(e[s]=r)}return e}const Pd=[...mr].reverse(),jd=mr.length;function kd(t){return e=>Promise.all(e.map(({animation:n,options:s})=>Ad(t,n,s)))}function Md(t){let e=kd(t),n=mi(),s=!0;const r=c=>(u,l)=>{const h=ze(t,l,c==="exit"?t.presenceContext?.custom:void 0);if(h){const{transition:f,transitionEnd:g,...S}=h;u={...u,...S,...g}}return u};function o(c){e=c(t)}function i(c){const{props:u}=t,l=va(t.parent)||{},h=[],f=new Set;let g={},S=1/0;for(let w=0;w<jd;w++){const y=Pd[w],v=n[y],x=u[y]!==void 0?u[y]:l[y],M=mn(x),j=y===c?v.isActive:null;j===!1&&(S=w);let E=x===l[y]&&x!==u[y]&&M;if(E&&s&&t.manuallyAnimateOnMount&&(E=!1),v.protectedKeys={...g},!v.isActive&&j===null||!x&&!v.prevProp||qn(x)||typeof x=="boolean")continue;const D=Ed(v.prevProp,x);let A=D||y===c&&v.isActive&&!E&&M||w>S&&M,F=!1;const I=Array.isArray(x)?x:[x];let X=I.reduce(r(y),{});j===!1&&(X={});const{prevResolvedValues:Y={}}=v,q={...Y,...X},G=J=>{A=!0,f.has(J)&&(F=!0,f.delete(J)),v.needsAnimating[J]=!0;const nt=t.getValue(J);nt&&(nt.liveStyle=!1)};for(const J in q){const nt=X[J],ot=Y[J];if(g.hasOwnProperty(J))continue;let st=!1;Is(nt)&&Is(ot)?st=!xa(nt,ot):st=nt!==ot,st?nt!=null?G(J):f.add(J):nt!==void 0&&f.has(J)?G(J):v.protectedKeys[J]=!0}v.prevProp=x,v.prevResolvedValues=X,v.isActive&&(g={...g,...X}),s&&t.blockInitialAnimation&&(A=!1);const it=E&&D;A&&(!it||F)&&h.push(...I.map(J=>{const nt={type:y};if(typeof J=="string"&&s&&!it&&t.manuallyAnimateOnMount&&t.parent){const{parent:ot}=t,st=ze(ot,J);if(ot.enteringChildren&&st){const{delayChildren:Jt}=st.transition||{};nt.delay=ya(ot.enteringChildren,t,Jt)}}return{animation:J,options:nt}}))}if(f.size){const w={};if(typeof u.initial!="boolean"){const y=ze(t,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const v=t.getBaseTarget(y),x=t.getValue(y);x&&(x.liveStyle=!0),w[y]=v??null}),h.push({animation:w})}let T=!!h.length;return s&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(T=!1),s=!1,T?e(h):Promise.resolve()}function a(c,u){if(n[c].isActive===u)return Promise.resolve();t.variantChildren?.forEach(h=>h.animationState?.setActive(c,u)),n[c].isActive=u;const l=i(c);for(const h in n)n[h].protectedKeys={};return l}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=mi()}}}function Ed(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!xa(e,t):!1}function we(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function mi(){return{animate:we(!0),whileInView:we(),whileHover:we(),whileTap:we(),whileDrag:we(),whileFocus:we(),exit:we()}}class fe{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Dd extends fe{constructor(e){super(e),e.animationState||(e.animationState=Md(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();qn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Nd=0;class Rd extends fe{constructor(){super(...arguments),this.id=Nd++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===s)return;const r=this.node.animationState.setActive("exit",!e);n&&!e&&r.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const ba={animation:{Feature:Dd},exit:{Feature:Rd}};function gn(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function bn(t){return{point:{x:t.pageX,y:t.pageY}}}const Vd=t=>e=>dr(e)&&t(e,bn(e));function on(t,e,n,s){return gn(t,e,Vd(n),s)}const wa=1e-4,Id=1-wa,Od=1+wa,Ta=.01,Ld=0-Ta,Fd=0+Ta;function At(t){return t.max-t.min}function $d(t,e,n){return Math.abs(t-e)<=n}function pi(t,e,n,s=.5){t.origin=s,t.originPoint=ut(e.min,e.max,t.origin),t.scale=At(n)/At(e),t.translate=ut(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Id&&t.scale<=Od||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ld&&t.translate<=Fd||isNaN(t.translate))&&(t.translate=0)}function an(t,e,n,s){pi(t.x,e.x,n.x,s?s.originX:void 0),pi(t.y,e.y,n.y,s?s.originY:void 0)}function gi(t,e,n){t.min=n.min+e.min,t.max=t.min+At(e)}function Bd(t,e,n){gi(t.x,e.x,n.x),gi(t.y,e.y,n.y)}function yi(t,e,n){t.min=e.min-n.min,t.max=t.min+At(e)}function cn(t,e,n){yi(t.x,e.x,n.x),yi(t.y,e.y,n.y)}function Dt(t){return[t("x"),t("y")]}const Sa=({current:t})=>t?t.ownerDocument.defaultView:null,xi=(t,e)=>Math.abs(t-e);function zd(t,e){const n=xi(t.x,e.x),s=xi(t.y,e.y);return Math.sqrt(n**2+s**2)}class Aa{constructor(e,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=us(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,S=zd(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!S)return;const{point:T}=f,{timestamp:w}=vt;this.history.push({...T,timestamp:w});const{onStart:y,onMove:v}=this.handlers;g||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=ls(g,this.transformPagePoint),ct.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:S,onSessionEnd:T,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=us(f.type==="pointercancel"?this.lastMoveEventInfo:ls(g,this.transformPagePoint),this.history);this.startEvent&&S&&S(f,y),T&&T(f,y)},!dr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=bn(e),c=ls(a,this.transformPagePoint),{point:u}=c,{timestamp:l}=vt;this.history=[{...u,timestamp:l}];const{onSessionStart:h}=n;h&&h(e,us(c,this.history)),this.removeListeners=yn(on(this.contextWindow,"pointermove",this.handlePointerMove),on(this.contextWindow,"pointerup",this.handlePointerUp),on(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),de(this.updatePoint)}}function ls(t,e){return e?{point:e(t.point)}:t}function vi(t,e){return{x:t.x-e.x,y:t.y-e.y}}function us({point:t},e){return{point:t,delta:vi(t,Ca(e)),offset:vi(t,Ud(e)),velocity:_d(e,.1)}}function Ud(t){return t[0]}function Ca(t){return t[t.length-1]}function _d(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,s=null;const r=Ca(t);for(;n>=0&&(s=t[n],!(r.timestamp-s.timestamp>$t(e)));)n--;if(!s)return{x:0,y:0};const o=Nt(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function Wd(t,{min:e,max:n},s){return e!==void 0&&t<e?t=s?ut(e,t,s.min):Math.max(t,e):n!==void 0&&t>n&&(t=s?ut(n,t,s.max):Math.min(t,n)),t}function bi(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function Kd(t,{top:e,left:n,bottom:s,right:r}){return{x:bi(t.x,n,r),y:bi(t.y,e,s)}}function wi(t,e){let n=e.min-t.min,s=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,s]=[s,n]),{min:n,max:s}}function qd(t,e){return{x:wi(t.x,e.x),y:wi(t.y,e.y)}}function Gd(t,e){let n=.5;const s=At(t),r=At(e);return r>s?n=dn(e.min,e.max-s,t.min):s>r&&(n=dn(t.min,t.max-r,e.min)),Ht(0,1,n)}function Hd(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Fs=.35;function Xd(t=Fs){return t===!1?t=0:t===!0&&(t=Fs),{x:Ti(t,"left","right"),y:Ti(t,"top","bottom")}}function Ti(t,e,n){return{min:Si(t,e),max:Si(t,n)}}function Si(t,e){return typeof t=="number"?t:t[e]||0}const Yd=new WeakMap;class Jd{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=h=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(bn(h).point)},i=(h,f)=>{const{drag:g,dragPropagation:S,onDragStart:T}=this.getProps();if(g&&!S&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ru(g),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Dt(y=>{let v=this.getAxisMotionValue(y).get()||0;if(Wt.test(v)){const{projection:x}=this.visualElement;if(x&&x.layout){const M=x.layout.layoutBox[y];M&&(v=At(M)*(parseFloat(v)/100))}}this.originPoint[y]=v}),T&&ct.postRender(()=>T(h,f)),Os(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:S,onDirectionLock:T,onDrag:w}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(S&&this.currentDirection===null){this.currentDirection=Zd(y),this.currentDirection!==null&&T&&T(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(h,f)},c=(h,f)=>{this.latestPointerEvent=h,this.latestPanInfo=f,this.stop(h,f),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>Dt(h=>this.getAnimationState(h)==="paused"&&this.getAxisMotionValue(h).animation?.play()),{dragSnapToOrigin:l}=this.getProps();this.panSession=new Aa(e,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:s,contextWindow:Sa(this.visualElement)})}stop(e,n){const s=e||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ct.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,s){const{drag:r}=this.getProps();if(!s||!En(e,r,this.currentDirection))return;const o=this.getAxisMotionValue(e);let i=this.originPoint[e]+s[e];this.constraints&&this.constraints[e]&&(i=Wd(i,this.constraints[e],this.elastic[e])),o.set(i)}resolveConstraints(){const{dragConstraints:e,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Oe(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&s?this.constraints=Kd(s.layoutBox,e):this.constraints=!1,this.elastic=Xd(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Dt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Hd(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Oe(e))return!1;const s=e.current;Xt(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=ed(s,r.root,this.visualElement.getTransformPagePoint());let i=qd(r.layout.layoutBox,o);if(n){const a=n(Zu(i));this.hasMutatedConstraints=!!a,a&&(i=oa(a))}return i}startAnimation(e){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=Dt(l=>{if(!En(l,n,this.currentDirection))return;let h=c&&c[l]||{};i&&(h={min:0,max:0});const f=r?200:1e6,g=r?40:1e7,S={type:"inertia",velocity:s?e[l]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...h};return this.startAxisValueAnimation(l,S)});return Promise.all(u).then(a)}startAxisValueAnimation(e,n){const s=this.getAxisMotionValue(e);return Os(this.visualElement,e),s.start(Tr(e,s,0,n,this.visualElement,!1))}stopAnimation(){Dt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Dt(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(e,(s.initial?s.initial[e]:void 0)||0)}snapToCursor(e){Dt(n=>{const{drag:s}=this.getProps();if(!En(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(e[n]-ut(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Oe(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Dt(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const c=a.get();r[i]=Gd({min:c,max:c},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Dt(i=>{if(!En(i,e,null))return;const a=this.getAxisMotionValue(i),{min:c,max:u}=this.constraints[i];a.set(ut(c,u,r[i]))})}addListeners(){if(!this.visualElement.current)return;Yd.set(this.visualElement,this);const e=this.visualElement.current,n=on(e,"pointerdown",c=>{const{drag:u,dragListener:l=!0}=this.getProps();u&&l&&this.start(c)}),s=()=>{const{dragConstraints:c}=this.getProps();Oe(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),ct.read(s);const i=gn(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Dt(l=>{const h=this.getAxisMotionValue(l);h&&(this.originPoint[l]+=c[l].translate,h.set(h.get()+c[l].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=Fs,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function En(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Zd(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Qd extends fe{constructor(e){super(e),this.removeGroupControls=Rt,this.removeListeners=Rt,this.controls=new Jd(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Rt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ai=t=>(e,n)=>{t&&ct.postRender(()=>t(e,n))};class th extends fe{constructor(){super(...arguments),this.removePointerDownListener=Rt}onPointerDown(e){this.session=new Aa(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Sa(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ai(e),onStart:Ai(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ct.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=on(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const On={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ci(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const nn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ci(t,e.target.x),s=Ci(t,e.target.y);return`${n}% ${s}%`}},eh={correct:(t,{treeScale:e,projectionDelta:n})=>{const s=t,r=he.parse(t);if(r.length>5)return s;const o=he.createTransformer(t),i=typeof r[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;r[0+i]/=a,r[1+i]/=c;const u=ut(a,c,.5);return typeof r[2+i]=="number"&&(r[2+i]/=u),typeof r[3+i]=="number"&&(r[3+i]/=u),o(r)}};let ds=!1;class nh extends m.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=e;Pu(sh),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),ds&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),On.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,ds=!0,r||e.layoutDependency!==n||n===void 0||e.isPresent!==o?i.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?i.promote():i.relegate()||ct.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ur.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=e;ds=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Pa(t){const[e,n]=Go(),s=m.useContext(Us);return d.jsx(nh,{...t,layoutGroup:s,switchLayoutGroup:m.useContext(ra),isPresent:e,safeToRemove:n})}const sh={borderRadius:{...nn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:nn,borderTopRightRadius:nn,borderBottomLeftRadius:nn,borderBottomRightRadius:nn,boxShadow:eh};function rh(t,e,n){const s=Tt(t)?t:Ue(t);return s.start(Tr("",s,e,n)),s.animation}const ih=(t,e)=>t.depth-e.depth;class oh{constructor(){this.children=[],this.isDirty=!1}add(e){Ks(this.children,e),this.isDirty=!0}remove(e){qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(ih),this.isDirty=!1,this.children.forEach(e)}}function ah(t,e){const n=jt.now(),s=({timestamp:r})=>{const o=r-n;o>=e&&(de(s),t(o-e))};return ct.setup(s,!0),()=>de(s)}const ja=["TopLeft","TopRight","BottomLeft","BottomRight"],ch=ja.length,Pi=t=>typeof t=="string"?parseFloat(t):t,ji=t=>typeof t=="number"||z.test(t);function lh(t,e,n,s,r,o){r?(t.opacity=ut(0,n.opacity??1,uh(s)),t.opacityExit=ut(e.opacity??1,0,dh(s))):o&&(t.opacity=ut(e.opacity??1,n.opacity??1,s));for(let i=0;i<ch;i++){const a=`border${ja[i]}Radius`;let c=ki(e,a),u=ki(n,a);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||ji(c)===ji(u)?(t[a]=Math.max(ut(Pi(c),Pi(u),s),0),(Wt.test(u)||Wt.test(c))&&(t[a]+="%")):t[a]=u}(e.rotate||n.rotate)&&(t.rotate=ut(e.rotate||0,n.rotate||0,s))}function ki(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const uh=ka(0,.5,fo),dh=ka(.5,.95,Rt);function ka(t,e,n){return s=>s<t?0:s>e?1:n(dn(t,e,s))}function Mi(t,e){t.min=e.min,t.max=e.max}function Et(t,e){Mi(t.x,e.x),Mi(t.y,e.y)}function Ei(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Di(t,e,n,s,r){return t-=e,t=_n(t,1/n,s),r!==void 0&&(t=_n(t,1/r,s)),t}function hh(t,e=0,n=1,s=.5,r,o=t,i=t){if(Wt.test(e)&&(e=parseFloat(e),e=ut(i.min,i.max,e/100)-i.min),typeof e!="number")return;let a=ut(o.min,o.max,s);t===o&&(a-=e),t.min=Di(t.min,e,n,a,r),t.max=Di(t.max,e,n,a,r)}function Ni(t,e,[n,s,r],o,i){hh(t,e[n],e[s],e[r],e.scale,o,i)}const fh=["x","scaleX","originX"],mh=["y","scaleY","originY"];function Ri(t,e,n,s){Ni(t.x,e,fh,n?n.x:void 0,s?s.x:void 0),Ni(t.y,e,mh,n?n.y:void 0,s?s.y:void 0)}function Vi(t){return t.translate===0&&t.scale===1}function Ma(t){return Vi(t.x)&&Vi(t.y)}function Ii(t,e){return t.min===e.min&&t.max===e.max}function ph(t,e){return Ii(t.x,e.x)&&Ii(t.y,e.y)}function Oi(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ea(t,e){return Oi(t.x,e.x)&&Oi(t.y,e.y)}function Li(t){return At(t.x)/At(t.y)}function Fi(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class gh{constructor(){this.members=[]}add(e){Ks(this.members,e),e.scheduleRender()}remove(e){if(qs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(r=>e===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(e,n){const s=this.lead;if(e!==s&&(this.prevLead=s,this.lead=e,e.show(),s)){s.instance&&s.scheduleRender(),e.scheduleRender(),e.resumeFrom=s,n&&(e.resumeFrom.preserveOpacity=!0),s.snapshot&&(e.snapshot=s.snapshot,e.snapshot.latestValues=s.animationValues||s.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:r}=e.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:s}=e;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function yh(t,e,n){let s="";const r=t.x.translate/e.x,o=t.y.translate/e.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(e.x!==1||e.y!==1)&&(s+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:u,rotate:l,rotateX:h,rotateY:f,skewX:g,skewY:S}=n;u&&(s=`perspective(${u}px) ${s}`),l&&(s+=`rotate(${l}deg) `),h&&(s+=`rotateX(${h}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),S&&(s+=`skewY(${S}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(s+=`scale(${a}, ${c})`),s||"none"}const hs=["","X","Y","Z"],xh=1e3;let vh=0;function fs(t,e,n,s){const{latestValues:r}=e;r[t]&&(n[t]=r[t],e.setStaticValue(t,0),s&&(s[t]=0))}function Da(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=pa(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ct,!(r||o))}const{parent:s}=t;s&&!s.hasCheckedOptimisedAppear&&Da(s)}function Na({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=e?.()){this.id=vh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(Th),this.nodes.forEach(Ph),this.nodes.forEach(jh),this.nodes.forEach(Sh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new oh)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Hs),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const c=this.eventHandlers.get(i);c&&c.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=qo(i)&&!uu(i),this.instance=i;const{layoutId:a,layout:c,visualElement:u}=this.options;if(u&&!u.current&&u.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let l,h=0;const f=()=>this.root.updateBlockedByResize=!1;ct.read(()=>{h=window.innerWidth}),t(i,()=>{const g=window.innerWidth;g!==h&&(h=g,this.root.updateBlockedByResize=!0,l&&l(),l=ah(f,250),On.hasAnimatedSinceResize&&(On.hasAnimatedSinceResize=!1,this.nodes.forEach(zi)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&u&&(a||c)&&this.addEventListener("didUpdate",({delta:l,hasLayoutChanged:h,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const S=this.options.transition||u.getDefaultTransition()||Nh,{onLayoutAnimationStart:T,onLayoutAnimationComplete:w}=u.getProps(),y=!this.targetLayout||!Ea(this.targetLayout,g),v=!h&&f;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const x={...cr(S,"layout"),onPlay:T,onComplete:w};(u.shouldReduceMotion||this.options.layoutRoot)&&(x.delay=0,x.type=!1),this.startAnimation(x),this.setAnimationOrigin(l,v)}else h||zi(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),de(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(kh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Da(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let l=0;l<this.path.length;l++){const h=this.path[l];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach($i);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bi);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Ch),this.nodes.forEach(bh),this.nodes.forEach(wh)):this.nodes.forEach(Bi),this.clearAllSnapshots();const a=jt.now();vt.delta=Ht(0,1e3/60,a-vt.timestamp),vt.timestamp=a,vt.isProcessing=!0,es.update.process(vt),es.preRender.process(vt),es.render.process(vt),vt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ur.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ah),this.sharedNodes.forEach(Mh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ct.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ct.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!At(this.snapshot.measuredBox.x)&&!At(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ft(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const c=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Ma(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,l=u!==this.prevTransformTemplateValue;i&&this.instance&&(a||Se(this.latestValues)||l)&&(r(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return i&&(c=this.removeTransform(c)),Rh(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ft();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Vh))){const{scroll:u}=this.root;u&&(Le(a.x,u.offset.x),Le(a.y,u.offset.y))}return a}removeElementScroll(i){const a=ft();if(Et(a,i),this.scroll?.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:l,options:h}=u;u!==this.root&&l&&h.layoutScroll&&(l.wasRoot&&Et(a,i),Le(a.x,l.offset.x),Le(a.y,l.offset.y))}return a}applyTransform(i,a=!1){const c=ft();Et(c,i);for(let u=0;u<this.path.length;u++){const l=this.path[u];!a&&l.options.layoutScroll&&l.scroll&&l!==l.root&&Fe(c,{x:-l.scroll.offset.x,y:-l.scroll.offset.y}),Se(l.latestValues)&&Fe(c,l.latestValues)}return Se(this.latestValues)&&Fe(c,this.latestValues),c}removeTransform(i){const a=ft();Et(a,i);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!Se(u.latestValues))continue;Ns(u.latestValues)&&u.updateSnapshot();const l=ft(),h=u.measurePageBox();Et(l,h),Ri(a,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,l)}return Se(this.latestValues)&&Ri(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==vt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(i||c&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:l,layoutId:h}=this.options;if(!(!this.layout||!(l||h))){if(this.resolvedRelativeTargetAt=vt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ft(),this.targetWithTransforms=ft()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Bd(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Et(this.target,this.layout.layoutBox),ca(this.target,this.targetDelta)):Et(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const f=this.getClosestProjectingParent();f&&!!f.resumingFrom==!!this.resumingFrom&&!f.options.layoutScroll&&f.target&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),cn(this.relativeTargetOrigin,this.target,f.target),Et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ns(this.parent.latestValues)||aa(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let c=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===vt.timestamp&&(c=!1),c)return;const{layout:u,layoutId:l}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(u||l))return;Et(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,f=this.treeScale.y;td(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ft());const{target:g}=i;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ei(this.prevProjectionDelta.x,this.projectionDelta.x),Ei(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==f||!Fi(this.projectionDelta.x,this.prevProjectionDelta.x)||!Fi(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=$e(),this.projectionDelta=$e(),this.projectionDeltaWithTransform=$e()}setAnimationOrigin(i,a=!1){const c=this.snapshot,u=c?c.latestValues:{},l={...this.latestValues},h=$e();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ft(),g=c?c.source:void 0,S=this.layout?this.layout.source:void 0,T=g!==S,w=this.getStack(),y=!w||w.members.length<=1,v=!!(T&&!y&&this.options.crossfade===!0&&!this.path.some(Dh));this.animationProgress=0;let x;this.mixTargetDelta=M=>{const j=M/1e3;Ui(h.x,i.x,j),Ui(h.y,i.y,j),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Eh(this.relativeTarget,this.relativeTargetOrigin,f,j),x&&ph(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=ft()),Et(x,this.relativeTarget)),T&&(this.animationValues=l,lh(l,u,this.latestValues,j,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=j},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(de(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ct.update(()=>{On.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ue(0)),this.currentAnimation=rh(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(xh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:c,layout:u,latestValues:l}=i;if(!(!a||!c||!u)){if(this!==i&&this.layout&&u&&Ra(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||ft();const h=At(this.layout.layoutBox.x);c.x.min=i.target.x.min,c.x.max=c.x.min+h;const f=At(this.layout.layoutBox.y);c.y.min=i.target.y.min,c.y.max=c.y.min+f}Et(a,c),Fe(a,l),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,l)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new gh),this.sharedNodes.get(i).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:c}={}){const u=this.getStack();u&&u.promote(this,c),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:c}=i;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const u={};c.z&&fs("z",i,u,this.animationValues);for(let l=0;l<hs.length;l++)fs(`rotate${hs[l]}`,i,u,this.animationValues),fs(`skew${hs[l]}`,i,u,this.animationValues);i.render();for(const l in u)i.setStaticValue(l,u[l]),this.animationValues&&(this.animationValues[l]=u[l]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=Vn(a?.pointerEvents)||"",i.transform=c?c(this.latestValues,""):"none";return}const u=this.getLead();if(!this.projectionDelta||!this.layout||!u.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=Vn(a?.pointerEvents)||""),this.hasProjected&&!Se(this.latestValues)&&(i.transform=c?c({},""):"none",this.hasProjected=!1);return}i.visibility="";const l=u.animationValues||u.latestValues;this.applyTransformsToTarget();let h=yh(this.projectionDeltaWithTransform,this.treeScale,l);c&&(h=c(l,h)),i.transform=h;const{x:f,y:g}=this.projectionDelta;i.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,u.animationValues?i.opacity=u===this?l.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:l.opacityExit:i.opacity=u===this?l.opacity!==void 0?l.opacity:"":l.opacityExit!==void 0?l.opacityExit:0;for(const S in pn){if(l[S]===void 0)continue;const{correct:T,applyTo:w,isCSSVariable:y}=pn[S],v=h==="none"?l[S]:T(l[S],u);if(w){const x=w.length;for(let M=0;M<x;M++)i[w[M]]=v}else y?this.options.visualElement.renderState.vars[S]=v:i[S]=v}this.options.layoutId&&(i.pointerEvents=u===this?Vn(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach($i),this.root.sharedNodes.clear()}}}function bh(t){t.updateLayout()}function wh(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:r}=t.options,o=e.source!==t.layout.source;r==="size"?Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(h);h.min=n[l].min,h.max=h.min+f}):Ra(r,e.layoutBox,n)&&Dt(l=>{const h=o?e.measuredBox[l]:e.layoutBox[l],f=At(n[l]);h.max=h.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[l].max=t.relativeTarget[l].min+f)});const i=$e();an(i,n,e.layoutBox);const a=$e();o?an(a,t.applyTransform(s,!0),e.measuredBox):an(a,n,e.layoutBox);const c=!Ma(i);let u=!1;if(!t.resumeFrom){const l=t.getClosestProjectingParent();if(l&&!l.resumeFrom){const{snapshot:h,layout:f}=l;if(h&&f){const g=ft();cn(g,e.layoutBox,h.layoutBox);const S=ft();cn(S,n,f.layoutBox),Ea(g,S)||(u=!0),l.options.layoutRoot&&(t.relativeTarget=S,t.relativeTargetOrigin=g,t.relativeParent=l)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:i,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Th(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Sh(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Ah(t){t.clearSnapshot()}function $i(t){t.clearMeasurements()}function Bi(t){t.isLayoutDirty=!1}function Ch(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function zi(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Ph(t){t.resolveTargetDelta()}function jh(t){t.calcProjection()}function kh(t){t.resetSkewAndRotation()}function Mh(t){t.removeLeadSnapshot()}function Ui(t,e,n){t.translate=ut(e.translate,0,n),t.scale=ut(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function _i(t,e,n,s){t.min=ut(e.min,n.min,s),t.max=ut(e.max,n.max,s)}function Eh(t,e,n,s){_i(t.x,e.x,n.x,s),_i(t.y,e.y,n.y,s)}function Dh(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Nh={duration:.45,ease:[.4,0,.1,1]},Wi=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Ki=Wi("applewebkit/")&&!Wi("chrome/")?Math.round:Rt;function qi(t){t.min=Ki(t.min),t.max=Ki(t.max)}function Rh(t){qi(t.x),qi(t.y)}function Ra(t,e,n){return t==="position"||t==="preserve-aspect"&&!$d(Li(e),Li(n),.2)}function Vh(t){return t!==t.root&&t.scroll?.wasRoot}const Ih=Na({attachResizeListener:(t,e)=>gn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ms={current:void 0},Va=Na({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ms.current){const t=new Ih({});t.mount(window),t.setOptions({layoutScroll:!0}),ms.current=t}return ms.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Oh={pan:{Feature:th},drag:{Feature:Qd,ProjectionNode:Va,MeasureLayout:Pa}};function Gi(t,e,n){const{props:s}=t;t.animationState&&s.whileHover&&t.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ct.postRender(()=>o(e,bn(e)))}class Lh extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=iu(e,(n,s)=>(Gi(this.node,s,"Start"),r=>Gi(this.node,r,"End"))))}unmount(){}}class Fh extends fe{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=yn(gn(this.node.current,"focus",()=>this.onFocus()),gn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Hi(t,e,n){const{props:s}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&s.whileTap&&t.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ct.postRender(()=>o(e,bn(e)))}class $h extends fe{mount(){const{current:e}=this.node;e&&(this.unmount=lu(e,(n,s)=>(Hi(this.node,s,"Start"),(r,{success:o})=>Hi(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $s=new WeakMap,ps=new WeakMap,Bh=t=>{const e=$s.get(t.target);e&&e(t)},zh=t=>{t.forEach(Bh)};function Uh({root:t,...e}){const n=t||document;ps.has(n)||ps.set(n,{});const s=ps.get(n),r=JSON.stringify(e);return s[r]||(s[r]=new IntersectionObserver(zh,{root:t,...e})),s[r]}function _h(t,e,n){const s=Uh(e);return $s.set(t,n),s.observe(t),()=>{$s.delete(t),s.unobserve(t)}}const Wh={some:0,all:1};class Kh extends fe{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=e,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:Wh[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:l,onViewportLeave:h}=this.node.getProps(),f=u?l:h;f&&f(c)};return _h(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(qh(e,n))&&this.startObserver()}unmount(){}}function qh({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Ia={inView:{Feature:Kh},tap:{Feature:$h},focus:{Feature:Fh},hover:{Feature:Lh}},Gh={layout:{ProjectionNode:Va,MeasureLayout:Pa}},Hh={...ba,...Ia,...Oh,...Gh},Xh=Ju(Hh,ma),Yh={renderer:ma,...ba,...Ia};function Sr(t,e){return In(t,e)}const Jh=Sr("button"),Dn=Sr("div"),Zh=Sr("p"),_t=Symbol.for("@arcteninc/core:originalName");function Qh(t,e){return t[_t]=e,t}function tf(t,e,n,s){if(typeof t!="function")return null;const r=t[_t];if(r){const a=e[r];if(a&&!n.has(a.name))return{fn:t,meta:a}}const o=t.name;let i;if(o&&(i=e[o],i&&!n.has(i.name)))return t[_t]=i.name,{fn:t,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=e[a],i))return t[_t]=i.name,{fn:t,meta:i}}else if(i=Object.values(e).find(c=>!n.has(c.name)),i)return t[_t]=i.name,{fn:t,meta:i};return null}function Oa(t,e){let n,s;if(!e)throw new Error(`❌ toolMetadata is required!
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 e&&typeof e.functions=="object"){const o=e;n=o.functions,s=o.toolOrder}else n=e,s=void 0;const r=new Set;return t.map(o=>{const i=tf(o,n,r,s);if(!i){const a=o.name,u=o[_t]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${u}". This tool will be excluded.
19
- To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function ef({toolName:t,description:e,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return d.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:d.jsx("span",{className:"text-sm font-medium text-foreground",children:t})}),o&&d.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),d.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d.jsxs(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(gt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(gt.X,{className:"h-3 w-3"})})]})]})})}function nf({toolName:t,args:e,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(t==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];t==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return d.jsxs("div",{className:"my-1",children:[d.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${c?"cursor-pointer hover:bg-muted/80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(gt.ChevronDown,{className:"h-3 w-3"}):d.jsx(gt.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(gt.X,{className:"h-3 w-3"}):s?d.jsx(gt.Zap,{className:"h-3 w-3"}):d.jsx(gt.Check,{className:"h-3 w-3"}),d.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),r&&c&&d.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:d.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function sf({...t}){return d.jsx(zs.Root,{"data-slot":"collapsible",...t})}function rf({...t}){return d.jsx(zs.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function of({...t}){return d.jsx(zs.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const af=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),Ar=m.memo(({className:t,...e})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(af,{className:yt("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);Ar.displayName="Response";const cf=Object.freeze(Object.defineProperty({__proto__:null,Response:Ar},Symbol.toStringTag,{value:"Module"})),lf=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=Xh.create(e),i=m.useMemo(()=>(t?.length??0)*r,[t,r]);return d.jsx(o,{animate:{backgroundPosition:"0% center"},className:yt("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:t})},uf=m.memo(lf),La=m.createContext(null),df=()=>{const t=m.useContext(La);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},hf=1e3,ff=1e3,Fa=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Nr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Nr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[x,y]=m.useState(null);m.useEffect(()=>{e?x===null&&y(Date.now()):x!==null&&(h(Math.ceil((Date.now()-x)/ff)),y(null))},[e,x,h]),m.useEffect(()=>{if(s&&!e&&c&&!f){const T=setTimeout(()=>{u(!1),g(!0)},hf);return()=>clearTimeout(T)}},[e,c,s,u,f]);const S=T=>{u(T)};return d.jsx(La.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(sf,{className:yt("not-prose mb-4",t),onOpenChange:S,open:c,...a,children:i})})}),mf=(t,e)=>t||e===0?d.jsx(uf,{duration:1,children:"Thinking..."}):e===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",e," seconds"]}),$a=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=df();return d.jsx(rf,{className:yt("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??d.jsxs(d.Fragment,{children:[d.jsx(gt.BrainIcon,{className:"size-4"}),mf(s,o),d.jsx(gt.ChevronDownIcon,{className:yt("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ba=m.memo(({className:t,children:e,...n})=>d.jsx(of,{className:yt("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",t),...n,children:d.jsx(Ar,{className:"grid gap-2",children:e})}));Fa.displayName="Reasoning";$a.displayName="ReasoningTrigger";Ba.displayName="ReasoningContent";function Xi(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function pf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=Xi(s.domain);return d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs("button",{className:yt("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[d.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),d.jsx("span",{className:"leading-none",children:s.domain})]})}),d.jsx(le,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",t.length]}),t.map(o=>d.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:yt("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:Xi(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 gf({text:t,citations:e,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=m.useRef(null),[l,h]=m.useState([]);m.useEffect(()=>{if(!a||!u.current||e.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const x=u.current;let y,S=!1;const T=new WeakSet,w=()=>{if(!u.current||S)return;S=!0;const k=u.current,V=/\[(\d+)\]/g,E=document.createTreeWalker(k,NodeFilter.SHOW_TEXT,null),D=[];let A;for(;A=E.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!T.has(A)){const M=A,G=M.textContent||"";let H=M.parentElement,_=!1;for(;H&&H!==k;){if(H.tagName==="A"||H.tagName==="CODE"||H.tagName==="PRE"){_=!0;break}H=H.parentElement}if(!_){const et=Array.from(G.matchAll(V)).filter(K=>{if(!K[1])return!1;const nt=parseInt(K[1],10);return n.has(nt)});et.length>0&&D.push({node:M,matches:et})}}if(D.length===0){S=!1;return}const F=[];D.forEach(({node:M,matches:G})=>{T.add(M);const H=M.textContent||"",_=document.createDocumentFragment();let Y=0;G.forEach(et=>{if(!et[1])return;et.index!==void 0&&et.index>Y&&_.appendChild(document.createTextNode(H.slice(Y,et.index)));const K=document.createElement("span");K.className="inline-flex items-center citation-button-container";const nt=parseInt(et[1],10);K.setAttribute("data-citation",et[1]),_.appendChild(K),F.push({element:K,citationNum:nt}),Y=(et.index||0)+et[0].length}),Y<H.length&&_.appendChild(document.createTextNode(H.slice(Y))),M.parentNode&&M.parentNode.replaceChild(_,M)}),F.length>0&&h(M=>{const G=new Set(M.map(Y=>Y.element)),H=M.filter(Y=>Y.element.isConnected),_=F.filter(Y=>!G.has(Y.element));return[...H,..._]}),S=!1},v=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(w,100)});return v.observe(x,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(w,200),()=>{v.disconnect(),clearTimeout(y)}},[t,e,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,y)=>{const S=x.numbers[0],T=x.title||x.baseUrl;return d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium whitespace-nowrap",children:["[",S,"]"]}),d.jsx("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:T})})]},`group-${y}`)}):Array.from(n.entries()).sort(([x],[y])=>x-y).map(([x,y])=>d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("span",{className:"font-medium",children:["[",x,"]"]}),d.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:y})]},x))})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:u,children:d.jsx(o,{children:t})}),a&&l.filter(({element:x})=>x.isConnected).map(({element:x,citationNum:y},S)=>{if(!e.find(v=>v.number===y))return null;const w=Array.from(new Map(e.map(v=>[v.url.replace(/\/+$/,""),{number:v.number,url:v.url,domain:yf(v.url)}])).values());return hc.createPortal(d.jsx(pf,{sources:w,citationNumber:y},`citation-${y}-${x}`),x,`citation-${y}-${S}`)}),g]})}function yf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function xf(t){try{const e=new URL(t),n=`${e.protocol}//${e.host}${e.pathname}`,s=e.hash?e.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const e=t.indexOf("#");return e!==-1?{baseUrl:t.substring(0,e),anchor:t.substring(e+1)}:{baseUrl:t}}}function vf(t){try{const e=new URL(t),s=e.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return e.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||e.hostname}catch{const e=t.indexOf("#"),n=e!==-1?t.substring(0,e):t,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function Yi(t){let e=t.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=e.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const A=s[1],F=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let M;for(;(M=F.exec(A))!==null;)if(M[1]&&M[2]){const G=parseInt(M[1],10),H=M[2].replace(/[.,;:!?]+$/,""),_=H.replace(/\/+$/,"");if(a.has(_)||a.set(_,H),i.has(_)||i.set(_,[]),i.get(_).push(G),!c.has(_))c.set(_,G);else{const Y=c.get(_);G<Y&&c.set(_,G)}}for(const[G,H]of i.entries()){const _=c.get(G);for(const Y of H)Y!==_&&u.set(Y,_)}for(const[G,H]of c.entries()){const _=a.get(G)||G;r.set(H,_),o.push({number:H,url:_})}}let l,h=e;s&&s[0]&&(l=s[0],h=e.replace(n,""));const f=[];let g=0;const x=/```[\s\S]*?```|`[^`]+`/g;let y;for(;(y=x.exec(h))!==null;)y.index>g&&f.push({type:"text",content:h.slice(g,y.index),start:g,end:y.index}),f.push({type:"code",content:y[0],start:y.index,end:y.index+y[0].length}),g=y.index+y[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const S=f.map(A=>{if(A.type==="code")return A.content;let F=A.content;return F=F.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(G,H,_)=>{const Y=parseInt(H,10),et=_.replace(/\/+$/,""),K=u.get(Y)||Y;return c.has(et)||(c.set(et,K),r.has(K)||(r.set(K,_),o.push({number:K,url:_}))),`[${K}]`}),F=F.replace(/\[(\d+)\]/g,(G,H)=>{const _=parseInt(H,10);return`[${u.get(_)||_}]`}),F}),T=[];for(const[A,F]of c.entries()){const M=a.get(A)||A,{baseUrl:G,anchor:H}=xf(M),_=vf(M);T.push({url:M,baseUrl:G,numbers:[F],anchor:H,title:_})}T.sort((A,F)=>(A.numbers[0]||0)-(F.numbers[0]||0));const w=new Map;let v=1;for(const A of T){const F=A.numbers[0];w.set(F,v),A.numbers=[v],v++}const k=new Map;for(const[A,F]of r.entries()){const M=w.get(A);M&&k.set(M,F)}const V=o.map(A=>{const F=w.get(A.number);return F?{number:F,url:A.url}:A}).filter(A=>w.has(A.number)),E=Array.from(w.entries()).sort((A,F)=>F[0]-A[0]);let D=S.join("");for(const[A,F]of E){const M=new RegExp(`\\[${A}\\](?!\\d)`,"g");D=D.replace(M,`[${F}]`)}return{processedText:D,citations:V.sort((A,F)=>A.number-F.number),citationMap:k,groupedCitations:T,referencesText:l}}function ln(t){if(typeof t=="string")try{const e=JSON.parse(t);return ln(e)}catch{return t}if(Array.isArray(t))return t.map(ln);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=ln(s);return e}return t}function gs(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return ln(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?ln(t):{}}function bf({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:h=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:x="/api/arcten/token",apiBaseUrl:y="https://api.arcten.com",user:S,state:T,onStateChange:w,allowStateEdits:v=!0,sources:k,ragConfig:V,showCitations:E=!0}){const D=m.useMemo(()=>V!==void 0?V:k&&k.length>0?{enabled:!0,organizationId:k[0],autoExecute:!0,filters:void 0}:{enabled:!1},[k,V]),[A,F]=m.useState(null),M=m.useRef(null),[G,H]=m.useState(null),[_,Y]=m.useState(null),et=m.useRef(null),K=T!==void 0,[nt,ht]=m.useState({}),lt=m.useRef({});K&&T?lt.current=T:K||(lt.current=nt);const[st,Jt]=m.useState(!1),[Me,xt]=m.useState(null),Zt=m.useRef(!1),[Bt,ke]=m.useState(u),[zt,Qt]=m.useState(i),[te,Ee]=m.useState(600),[ee,Vt]=m.useState(!1),[Q,It]=m.useState(!1),[Ct,Mt]=m.useState(!1),[bt,De]=m.useState({x:100,y:100}),[He,me]=m.useState(!1),[Ne,wn]=m.useState({x:0,y:0}),[Tn,Ut]=m.useState(!1),Xe=m.useRef(null),ne=m.useRef(null),[se,Ye]=m.useState(""),[pe,Je]=m.useState(null),[Hn,Xn]=m.useState("Thinking..."),[Ze,Kt]=m.useState(new Set),[Yn,Jn]=m.useState(""),[C,P]=m.useState([]),[I,O]=m.useState(!1),[W,Z]=m.useState([]),[X,wt]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[ut,Pt]=m.useState(!1),[it,rt]=m.useState(!1),[Re,ge]=m.useState([]),Cr=m.useCallback(async(p,b=3)=>{if(!X||!M.current)return;const j=async()=>{const R=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,$=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:X,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 J=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${$.status} ${J}`)}};for(let N=0;N<b;N++)try{await j(),xt(null);return}catch(R){if(N===b-1){const J=R instanceof Error?R:new Error(String(R));throw xt(J),console.error("Failed to sync state to Convex after retries:",R),J}await new Promise(J=>setTimeout(J,Math.pow(2,N)*100))}},[X,y,M]),Qe=m.useMemo(()=>function(){return lt.current},[]),tn=m.useMemo(()=>async function(b){const j={...lt.current,...b};lt.current=j,K||ht(j),w&&w(j);try{await Cr(b)}catch(N){throw N}},[Cr,w,K]);m.useEffect(()=>{K&&T&&(lt.current=T)},[K,T]);const ye=m.useMemo(()=>D?.enabled?async function(b,j=20,N){if(k&&k.length>1){const J=k.map(U=>fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json",...M.current?{Authorization:`Bearer ${M.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(j,100),organizationId:U,...Object.keys($).length>0?{filters:$}:{}})}).then(B=>B.ok?B.json():null)),q=await Promise.all(J),tt=[];for(const U of q)U?.candidates&&tt.push(...U.candidates);tt.sort((U,B)=>{const mt=U.scores?.rerank||U.scores?.dense||0;return(B.scores?.rerank||B.scores?.dense||0)-mt});const L=tt.slice(0,j).map((U,B)=>{const mt=U.citation||U.url;return{rank:B+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:mt,title:U.title||"Untitled",snippet:U.snippet,score:U.scores?.rerank||U.scores?.dense||0,metadata:{site:U.metadata?.site,lang:U.metadata?.lang,contentType:U.metadata?.content_type}}});return{success:!0,query:b,total:tt.length,results:L,summary:`Found ${tt.length} relevant results across ${k.length} source(s) for "${b}". Top result: ${L[0]?.title||"N/A"}`}}const R=D.organizationId&&D.organizationId!=="default"?D.organizationId:void 0,$={...D.filters,...N};try{const J={q:b,k:Math.min(j,100)};R&&(J.organizationId=R),Object.keys($).length>0&&(J.filters=$);const q={"Content-Type":"application/json"};M.current&&(q.Authorization=`Bearer ${M.current}`);const tt=await fetch(`${y}/search`,{method:"POST",headers:q,body:JSON.stringify(J)});if(!tt.ok){const B=await tt.text();return{success:!1,error:`Search failed: ${tt.status} ${B}`}}const L=await tt.json(),U=L.candidates.map((B,mt)=>{const dt=B.citation||B.url;return{rank:mt+1,doc_id:B.doc_id,block_id:B.block_id,url:B.url,citation:dt,title:B.title||"Untitled",snippet:B.snippet,score:B.scores?.rerank||B.scores?.dense||0,metadata:{site:B.metadata?.site,lang:B.metadata?.lang,contentType:B.metadata?.content_type}}});return{success:!0,query:L.query,total:L.total,results:U,summary:`Found ${L.total} relevant results for "${b}". Top result: ${U[0]?.title||"N/A"}`}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error occurred"}}}:null,[V,y,M]),xe=m.useMemo(()=>D?.enabled?async function(b,j){const N=D.organizationId&&D.organizationId!=="default"?D.organizationId:k&&k.length>0?k[0]:void 0;try{const R={"Content-Type":"application/json"};M.current&&(R.Authorization=`Bearer ${M.current}`);const $=await fetch(`${y}/fetch`,{method:"POST",headers:R,body:JSON.stringify({doc_id:b,block_ids:j,...N?{organizationId:N}:{}})});if(!$.ok){const q=await $.text();return{success:!1,error:`Fetch failed: ${$.status} ${q}`}}const J=await $.json();return{success:!0,blocks:J.blocks||[],fullContent:J.fullContent||"",pageUrl:J.pageUrl||"",pageTitle:J.pageTitle||"",summary:`Fetched ${J.blocks?.length||0} blocks from ${J.pageTitle||b}`}}catch(R){return{success:!1,error:R instanceof Error?R.message:"Unknown error occurred"}}}:null,[V,y,M]),ve=m.useMemo(()=>{const p=[...l,...h,Qe];return(!K||v)&&p.push(tn),D?.enabled&&(ye&&p.push(ye),xe&&p.push(xe)),p},[l,h,Qe,tn,ye,xe,K,v,D]),Zn=m.useMemo(()=>Oa(ve,f),[ve,f]),qt=m.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!K||v)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const b=[];return D?.enabled&&b.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Zn,...p,...b]},[Zn,K,v,D]),Pr=m.useMemo(()=>new Set(qt.map(p=>p.name)),[qt]),Sn=m.useMemo(()=>qt.filter(p=>p.name==="getState"?!0:p.name==="setState"?!K||v:Pr.has(p.name)),[qt,Pr,K,v]),An=m.useMemo(()=>{const p=new Map,b=new Map(Zn.map(j=>[j.name,j]));return p.set("getState",Qe),(!K||v)&&p.set("setState",tn),D?.enabled&&(ye&&p.set("searchDocs",ye),xe&&p.set("fetchDocContent",xe)),ve.forEach(j=>{if(j===Qe||j===tn||j===ye||j===xe)return;const N=j[_t];if(N){const $=b.get(N);if($){p.set($.name,j);return}}const R=qt.find($=>$.name===j.name);R&&p.set(R.name,j)}),p},[ve,qt,Qe,tn,ye,xe,K,v,D]),en=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),D?.enabled&&D.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(qt.map(j=>[j.name,j]));return h.forEach(j=>{const N=j[_t];if(N&&b.has(N))p.add(N);else{const R=qt.find($=>$.name===j.name);R&&p.add(R.name)}}),p},[h,qt,D]),jr=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];m.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&ke(JSON.parse(p));const b=localStorage.getItem("arcten-sidebar-width");b&&Qt(parseInt(b));const j=localStorage.getItem("arcten-sidebar-height");j&&Ee(parseInt(j));const N=localStorage.getItem("arcten-sidebar-detached");N&&It(JSON.parse(N));const R=localStorage.getItem("arcten-sidebar-position");if(R){const J=JSON.parse(R),q=50,tt=Math.max(q-i,Math.min(J.x,window.innerWidth-q)),L=Math.max(0,Math.min(J.y,window.innerHeight-q));De({x:tt,y:L})}const $=localStorage.getItem("arcten-sidebar-minimized");$&&Mt(JSON.parse($)),Ut(!0)}},[]);const re=m.useMemo(()=>S,[S?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!b.ok)throw new Error("Failed to fetch token");const j=await b.json();F(j.clientToken),M.current=j.clientToken,Y(j.expiresAt),H(null)}catch(b){H(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{et.current&&clearTimeout(et.current)}),[x,re]),m.useEffect(()=>{if(!_)return;et.current&&clearTimeout(et.current);const p=Math.floor(Date.now()/1e3),b=_-p,N=Math.max(0,b-5);return et.current=setTimeout(async()=>{try{const R=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!R.ok)throw new Error("Failed to refresh token");const $=await R.json();F($.clientToken),M.current=$.clientToken,Y($.expiresAt),H(null)}catch(R){console.error("Token refresh failed:",R),H(R instanceof Error?R.message:"Failed to refresh token")}},N*1e3),()=>{et.current&&clearTimeout(et.current)}},[_,x,re]),m.useEffect(()=>{(async()=>{if(ve.length!==0)try{const b=ve.map(N=>({name:N.name,code:N.toString()})),j=await fetch(`${y}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(j.ok){const N=await j.json();P(N.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[ve]),m.useEffect(()=>{Promise.resolve().then(()=>cf).then(p=>{Je(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Jn(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Qn=m.useCallback(async()=>{if(!(!re?.id||!A)){rt(!0);try{const b=await(await fetch(`${y}/conversations`,{headers:{Authorization:`Bearer ${A}`}})).json();Z(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{rt(!1)}}},[re?.id,A,y]);m.useEffect(()=>{re?.id&&A&&Qn()},[re?.id,A,Qn]);function za(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Ua(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1);const b=K?T||{}:{};lt.current=b,K||ht(b),w&&w(b),Zt.current=!1}async function _a(p){if(A)try{await fetch(`${y}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${A}`}}),Z(W.filter(b=>b._id!==p)),p===X&&Ua()}catch(b){console.error("Failed to delete conversation:",b)}}async function Wa(p){wt(p.chatId),Pt(!1),rt(!0);try{const b=await fetch(`${y}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${M.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const N=(await b.json()).messages||[];Pn(N),ge(N)}catch(b){console.error("Failed to load conversation messages:",b);const j=p.messages||[];Pn(j),ge(j)}finally{rt(!1)}}const Ka=async(p,b={})=>{const j=b.headers?new Headers(b.headers):new Headers;return j.delete("user-agent"),j.delete("User-Agent"),fetch(p,{...b,headers:j})},{messages:Gt,sendMessage:qa,status:Ot,error:Mr,stop:Cn,addToolResult:be,setMessages:Pn}=Ji.useChat({id:X||void 0,transport:new Ln.DefaultChatTransport({api:`${y}/chat`,fetch:Ka,headers:()=>{const p={};return M.current&&(p.Authorization=`Bearer ${M.current}`),p},body:()=>({tools:Sn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:Yn,state:lt.current})}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Gt[Gt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(j=>j.type?.startsWith("tool-")&&j.state==="input-available"&&typeof j.toolCallId=="string"&&j.input!==void 0)||[];for(const j of b){const N=j,R=N.type?.replace("tool-","")||"",$=N.toolCallId;if(en.has(R)){if(Ze.has($))continue;Kt(q=>q.has($)?q:new Set(q).add($)),(async()=>{try{const q=An.get(R);if(!q){console.warn(`[ArctenAgent] Tool ${R} not found in toolsMap. Available tools:`,Array.from(An.keys())),be({toolCallId:$,tool:R,output:`Error: Tool ${R} not found`}),Kt(B=>{const mt=new Set(B);return mt.delete($),mt});return}const tt=gs(N.input),L=Sn.find(B=>B.name===R);let U;if(L&&L.jsonSchema?.properties){const mt=Object.keys(L.jsonSchema.properties).map(dt=>tt[dt]);console.log(`[ArctenAgent] Executing safe tool ${R} with args:`,mt),U=await q(...mt)}else if(R==="getState")U=q();else if(R==="setState"){const B=tt.updates||tt;U=await q(B)}else U=await q(...Object.values(tt));console.log(`[ArctenAgent] Tool ${R} completed, result:`,U),be({toolCallId:$,tool:R,output:U}),Kt(B=>{const mt=new Set(B);return mt.delete($),mt})}catch(q){console.error(`[ArctenAgent] Error executing safe tool ${R}:`,q),be({toolCallId:$,tool:R,output:`Error: ${q instanceof Error?q.message:String(q)}`}),Kt(tt=>{const L=new Set(tt);return L.delete($),L})}})()}}},[Gt,en,An,Sn,be]),m.useEffect(()=>{if(!X||!M.current)return;(async()=>{Jt(!0),xt(null);try{const j=`${y.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,N=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:X},format:"json"})});if(!N.ok){if(N.status===404||N.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${N.status}), using empty state`);const L=K?T||{}:{};lt.current=L,K||ht(L),w&&w(L),Zt.current=!0,Jt(!1);return}const tt=await N.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${N.status} ${tt}`)}const $=(await N.json())?.value||{},J=!Zt.current;let q;J?(q={...K?T||{}:{},...$},Zt.current=!0):q=$,lt.current=q,K||ht(q),w&&w(q)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const N=b instanceof Error?b:new Error(String(b));if(xt(N),!Zt.current){const R=K?T||{}:{};lt.current=R,K||ht(R),w&&w(R),Zt.current=!0}}finally{Jt(!1)}})()},[X,y,K,T,w]),m.useEffect(()=>{Bt&&ne.current&&ne.current.focus()},[Bt,Gt]);function Ga(){ke(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ha(){ke(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Bt]),m.useEffect(()=>{Xe.current&&Xe.current.scrollIntoView({behavior:"smooth"})},[Gt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Ot==="streaming"||Ot==="submitted")&&(b.preventDefault(),Cn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ot,Cn]);function Xa(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1)}function kr(p){if(p.preventDefault(),!se.trim())return;(Ot==="streaming"||Ot==="submitted")&&Cn();const b=jr[Math.floor(Math.random()*jr.length)]||"Thinking...";Xn(b),qa({text:se}),Ye("")}function Ya(p){const b=p.target.value;Ye(b)}m.useEffect(()=>{if(!ee)return;function p(j){if(Q){const N=j.clientX-bt.x,R=j.clientY-bt.y;N>=a&&N<=c&&Qt(N),R>=400&&R<=1e3&&Ee(R)}else{const N=window.innerWidth-j.clientX;N>=a&&N<=c&&Qt(N)}}function b(){Vt(!1),localStorage.setItem("arcten-sidebar-width",zt.toString()),localStorage.setItem("arcten-sidebar-height",te.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ee,zt,te,Q,bt,a,c]);function Ja(p){p.preventDefault(),Vt(!0)}function Za(){It(!0),Mt(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qa(){It(!1),Mt(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Er(){Mt(!Ct),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ct))}function tc(p){Q&&(me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y}))}return m.useEffect(()=>{if(!Q)return;function p(){De(b=>{const N=window.innerWidth-50,R=window.innerHeight-50,$=50-zt,J=0,q=Math.max($,Math.min(b.x,N)),tt=Math.max(J,Math.min(b.y,R));if(q!==b.x||tt!==b.y){const L={x:q,y:tt};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(L)),L}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[Q,zt]),m.useEffect(()=>{if(!He)return;function p(j){const N=j.clientX-Ne.x,R=j.clientY-Ne.y,$=50,J=window.innerWidth-$,q=window.innerHeight-$,tt=$-zt,L=0,U=Math.max(tt,Math.min(N,J)),B=Math.max(L,Math.min(R,q));De({x:U,y:B})}function b(){me(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(bt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[He,Ne,bt,zt]),Tn?G?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: ",G]})}):A?d.jsx(bu,{features:Yh,children:d.jsx(Dn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:Q?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:Q?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
- ${Q?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
19
+ To fix: Run "arcten-extract-types ." and ensure "${u}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function ef({toolName:t,description:e,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return d.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:d.jsxs("div",{className:"flex items-start gap-2",children:[d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:d.jsx("span",{className:"text-sm font-medium text-foreground",children:t})}),o&&d.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),d.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d.jsxs(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[d.jsx(yt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),d.jsx(Fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:d.jsx(yt.X,{className:"h-3 w-3"})})]})]})})}function nf({toolName:t,args:e,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(t==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];t==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([u])=>!i.includes(u))),c=Object.keys(a).length>0;return d.jsxs("div",{className:"my-1",children:[d.jsxs("button",{onClick:()=>c&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${c?"cursor-pointer hover:bg-muted/80":""}`,children:[c&&d.jsx("span",{className:"transition-transform duration-200",children:r?d.jsx(yt.ChevronDown,{className:"h-3 w-3"}):d.jsx(yt.ChevronRight,{className:"h-3 w-3"})}),n?d.jsx(yt.X,{className:"h-3 w-3"}):s?d.jsx(yt.Zap,{className:"h-3 w-3"}):d.jsx(yt.Check,{className:"h-3 w-3"}),d.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),r&&c&&d.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:d.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,l])=>d.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[d.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),d.jsx("span",{className:"font-mono text-foreground",children:typeof l=="string"?l:JSON.stringify(l)})]},u))})})]})}function sf({...t}){return d.jsx(zs.Root,{"data-slot":"collapsible",...t})}function rf({...t}){return d.jsx(zs.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function of({...t}){return d.jsx(zs.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const af=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),Ar=m.memo(({className:t,...e})=>typeof window>"u"?null:d.jsx(m.Suspense,{fallback:null,children:d.jsx(af,{className:mt("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);Ar.displayName="Response";const cf=Object.freeze(Object.defineProperty({__proto__:null,Response:Ar},Symbol.toStringTag,{value:"Module"})),lf=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=Xh.create(e),i=m.useMemo(()=>(t?.length??0)*r,[t,r]);return d.jsx(o,{animate:{backgroundPosition:"0% center"},className:mt("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:t})},uf=m.memo(lf),La=m.createContext(null),df=()=>{const t=m.useContext(La);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},hf=1e3,ff=1e3,Fa=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,u]=Nr.useControllableState({prop:n,defaultProp:s,onChange:r}),[l,h]=Nr.useControllableState({prop:o,defaultProp:0}),[f,g]=m.useState(!1),[S,T]=m.useState(null);m.useEffect(()=>{e?S===null&&T(Date.now()):S!==null&&(h(Math.ceil((Date.now()-S)/ff)),T(null))},[e,S,h]),m.useEffect(()=>{if(s&&!e&&c&&!f){const y=setTimeout(()=>{u(!1),g(!0)},hf);return()=>clearTimeout(y)}},[e,c,s,u,f]);const w=y=>{u(y)};return d.jsx(La.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:u,duration:l},children:d.jsx(sf,{className:mt("not-prose mb-4",t),onOpenChange:w,open:c,...a,children:i})})}),mf=(t,e)=>t||e===0?d.jsx(uf,{duration:1,children:"Thinking..."}):e===void 0?d.jsx("p",{children:"Thought for a few seconds"}):d.jsxs("p",{children:["Thought for ",e," seconds"]}),$a=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=df();return d.jsx(rf,{className:mt("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??d.jsxs(d.Fragment,{children:[d.jsx(yt.BrainIcon,{className:"size-4"}),mf(s,o),d.jsx(yt.ChevronDownIcon,{className:mt("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ba=m.memo(({className:t,children:e,...n})=>d.jsx(of,{className:mt("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",t),...n,children:d.jsx(Ar,{className:"grid gap-2",children:e})}));Fa.displayName="Reasoning";$a.displayName="ReasoningTrigger";Ba.displayName="ReasoningContent";function Xi(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function pf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=Xi(s.domain);return d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs("button",{className:mt("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[d.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),d.jsx("span",{className:"leading-none",children:s.domain})]})}),d.jsx(le,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",t.length]}),t.map(o=>{const i=o.title||o.domain;return d.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:mt("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[d.jsx("img",{src:Xi(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const c=a.target;c.style.display="none"}}),d.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function gf({text:t,citations:e,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:c=!0}){const u=m.useRef(null),[l,h]=m.useState([]);m.useEffect(()=>{if(!a||!u.current||e.length===0||n.size===0){(n.size===0||!a)&&h([]);return}const w=u.current;let y,v=!1;const x=new WeakSet,M=()=>{if(!u.current||v)return;v=!0;const E=u.current,D=/\[(\d+)\]/g,A=document.createTreeWalker(E,NodeFilter.SHOW_TEXT,null),F=[];let I;for(;I=A.nextNode();)if(I.nodeType===Node.TEXT_NODE&&!x.has(I)){const Y=I,q=Y.textContent||"";let G=Y.parentElement,it=!1;for(;G&&G!==E;){if(G.tagName==="A"||G.tagName==="CODE"||G.tagName==="PRE"){it=!0;break}G=G.parentElement}if(!it){const J=Array.from(q.matchAll(D)).filter(nt=>{if(!nt[1])return!1;const ot=parseInt(nt[1],10);return n.has(ot)});J.length>0&&F.push({node:Y,matches:J})}}if(F.length===0){v=!1;return}const X=[];F.forEach(({node:Y,matches:q})=>{x.add(Y);const G=Y.textContent||"",it=document.createDocumentFragment();let _=0;q.forEach(J=>{if(!J[1])return;J.index!==void 0&&J.index>_&&it.appendChild(document.createTextNode(G.slice(_,J.index)));const nt=document.createElement("span");nt.className="inline-flex items-center citation-button-container";const ot=parseInt(J[1],10);nt.setAttribute("data-citation",J[1]),it.appendChild(nt),X.push({element:nt,citationNum:ot}),_=(J.index||0)+J[0].length}),_<G.length&&it.appendChild(document.createTextNode(G.slice(_))),Y.parentNode&&Y.parentNode.replaceChild(it,Y)}),X.length>0&&h(Y=>{const q=new Set(Y.map(_=>_.element)),G=Y.filter(_=>_.element.isConnected),it=X.filter(_=>!q.has(_.element));return[...G,...it]}),v=!1},j=new MutationObserver(()=>{clearTimeout(y),y=setTimeout(M,100)});return j.observe(w,{childList:!0,subtree:!0,characterData:!0}),y=setTimeout(M,200),()=>{j.disconnect(),clearTimeout(y)}},[t,e,n,a]);const f=s&&s.length>0||n&&n.size>0||r;function g(w){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(w)}&sz=16`}function S(w){try{return new URL(w).hostname.replace(/^www\./,"")}catch{return w}}const T=a&&c&&f?d.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[d.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),d.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((w,y)=>{const v=w.title||w.baseUrl,x=S(w.url),M=g(x);return d.jsxs("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:mt("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[d.jsx("img",{src:M,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:j=>{const E=j.target;E.style.display="none"}}),d.jsx("span",{className:"leading-none",children:v})]},`group-${y}`)}):Array.from(n.entries()).sort(([w],[y])=>w-y).map(([w,y])=>{const v=S(y),x=g(v);return d.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:mt("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[d.jsx("img",{src:x,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:M=>{const j=M.target;j.style.display="none"}}),d.jsx("span",{className:"leading-none",children:y})]},w)})})]}):null;return d.jsxs("div",{className:i,children:[d.jsx("div",{ref:u,children:d.jsx(o,{children:t})}),a&&l.filter(({element:w})=>w.isConnected).map(({element:w,citationNum:y},v)=>{if(!e.find(j=>j.number===y))return null;const M=Array.from(new Map(e.map(j=>{const E=j.url.replace(/\/+$/,""),D=s?.find(A=>A.url.replace(/\/+$/,"")===E);return[E,{number:j.number,url:j.url,domain:S(j.url),title:D?.title}]})).values());return hc.createPortal(d.jsx(pf,{sources:M,citationNumber:y},`citation-${y}-${w}`),w,`citation-${y}-${v}`)}),T]})}function yf(t){try{const e=new URL(t),n=`${e.protocol}//${e.host}${e.pathname}`,s=e.hash?e.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const e=t.indexOf("#");return e!==-1?{baseUrl:t.substring(0,e),anchor:t.substring(e+1)}:{baseUrl:t}}}function xf(t){try{const e=new URL(t),s=e.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return e.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||e.hostname}catch{const e=t.indexOf("#"),n=e!==-1?t.substring(0,e):t,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function Yi(t){let e=t.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=e.match(n),r=new Map,o=[],i=new Map,a=new Map,c=new Map,u=new Map;if(s&&s[1]){const A=s[1],F=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let I;for(;(I=F.exec(A))!==null;)if(I[1]&&I[2]){const X=parseInt(I[1],10),Y=I[2].replace(/[.,;:!?]+$/,""),q=Y.replace(/\/+$/,"");if(a.has(q)||a.set(q,Y),i.has(q)||i.set(q,[]),i.get(q).push(X),!c.has(q))c.set(q,X);else{const G=c.get(q);X<G&&c.set(q,X)}}for(const[X,Y]of i.entries()){const q=c.get(X);for(const G of Y)G!==q&&u.set(G,q)}for(const[X,Y]of c.entries()){const q=a.get(X)||X;r.set(Y,q),o.push({number:Y,url:q})}}let l,h=e;s&&s[0]&&(l=s[0],h=e.replace(n,""));const f=[];let g=0;const S=/```[\s\S]*?```|`[^`]+`/g;let T;for(;(T=S.exec(h))!==null;)T.index>g&&f.push({type:"text",content:h.slice(g,T.index),start:g,end:T.index}),f.push({type:"code",content:T[0],start:T.index,end:T.index+T[0].length}),g=T.index+T[0].length;g<h.length&&f.push({type:"text",content:h.slice(g),start:g,end:h.length});const w=f.map(A=>{if(A.type==="code")return A.content;let F=A.content;return F=F.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(X,Y,q)=>{const G=parseInt(Y,10),it=q.replace(/\/+$/,""),_=u.get(G)||G;return c.has(it)||(c.set(it,_),r.has(_)||(r.set(_,q),o.push({number:_,url:q}))),`[${_}]`}),F=F.replace(/\[(\d+)\]/g,(X,Y)=>{const q=parseInt(Y,10);return`[${u.get(q)||q}]`}),F}),y=[];for(const[A,F]of c.entries()){const I=a.get(A)||A,{baseUrl:X,anchor:Y}=yf(I),q=xf(I);y.push({url:I,baseUrl:X,numbers:[F],anchor:Y,title:q})}y.sort((A,F)=>(A.numbers[0]||0)-(F.numbers[0]||0));const v=new Map;let x=1;for(const A of y){const F=A.numbers[0];v.set(F,x),A.numbers=[x],x++}const M=new Map;for(const[A,F]of r.entries()){const I=v.get(A);I&&M.set(I,F)}const j=o.map(A=>{const F=v.get(A.number);return F?{number:F,url:A.url}:A}).filter(A=>v.has(A.number)),E=Array.from(v.entries()).sort((A,F)=>F[0]-A[0]);let D=w.join("");for(const[A,F]of E){const I=new RegExp(`\\[${A}\\](?!\\d)`,"g");D=D.replace(I,`[${F}]`)}return{processedText:D,citations:j.sort((A,F)=>A.number-F.number),citationMap:M,groupedCitations:y,referencesText:l}}function ln(t){if(typeof t=="string")try{const e=JSON.parse(t);return ln(e)}catch{return t}if(Array.isArray(t))return t.map(ln);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=ln(s);return e}return t}function gs(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return ln(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?ln(t):{}}function vf({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:u=!1,tools:l=[],safeTools:h=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:S="/api/arcten/token",apiBaseUrl:T="https://api.arcten.com",user:w,state:y,onStateChange:v,allowStateEdits:x=!0,sources:M,ragConfig:j,showCitations:E=!0}){const D=m.useMemo(()=>j!==void 0?j:M&&M.length>0?{enabled:!0,organizationId:M[0],autoExecute:!0,filters:void 0}:{enabled:!1},[M,j]),[A,F]=m.useState(null),I=m.useRef(null),[X,Y]=m.useState(null),[q,G]=m.useState(null),it=m.useRef(null),_=y!==void 0,[J,nt]=m.useState({}),ot=m.useRef({});_&&y?ot.current=y:_||(ot.current=J);const[st,Jt]=m.useState(!1),[ke,xt]=m.useState(null),Zt=m.useRef(!1),[Bt,Me]=m.useState(u),[zt,Qt]=m.useState(i),[te,Ee]=m.useState(600),[ee,Vt]=m.useState(!1),[tt,It]=m.useState(!1),[Ct,kt]=m.useState(!1),[bt,De]=m.useState({x:100,y:100}),[He,me]=m.useState(!1),[Ne,wn]=m.useState({x:0,y:0}),[Tn,Ut]=m.useState(!1),Xe=m.useRef(null),ne=m.useRef(null),[se,Ye]=m.useState(""),[pe,Je]=m.useState(null),[Hn,Xn]=m.useState("Thinking..."),[Ze,Kt]=m.useState(new Set),[Yn,Jn]=m.useState(""),[C,P]=m.useState([]),[V,O]=m.useState(!1),[W,Q]=m.useState([]),[H,wt]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[dt,Pt]=m.useState(!1),[at,rt]=m.useState(!1),[Re,ge]=m.useState([]),Cr=m.useCallback(async(p,b=3)=>{if(!H||!I.current)return;const k=async()=>{const R=`${T.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,$=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:H,updates:p},format:"json"})});if(!$.ok){if($.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const Z=await $.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${$.status} ${Z}`)}};for(let N=0;N<b;N++)try{await k(),xt(null);return}catch(R){if(N===b-1){const Z=R instanceof Error?R:new Error(String(R));throw xt(Z),console.error("Failed to sync state to Convex after retries:",R),Z}await new Promise(Z=>setTimeout(Z,Math.pow(2,N)*100))}},[H,T,I]),Qe=m.useMemo(()=>function(){return ot.current},[]),tn=m.useMemo(()=>async function(b){const k={...ot.current,...b};ot.current=k,_||nt(k),v&&v(k);try{await Cr(b)}catch(N){throw N}},[Cr,v,_]);m.useEffect(()=>{_&&y&&(ot.current=y)},[_,y]);const ye=m.useMemo(()=>D?.enabled?async function(b,k=20,N){if(M&&M.length>1){const Z=M.map(U=>fetch(`${T}/search`,{method:"POST",headers:{"Content-Type":"application/json",...I.current?{Authorization:`Bearer ${I.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(k,100),organizationId:U,...Object.keys($).length>0?{filters:$}:{}})}).then(B=>B.ok?B.json():null)),K=await Promise.all(Z),et=[];for(const U of K)U?.candidates&&et.push(...U.candidates);et.sort((U,B)=>{const pt=U.scores?.rerank||U.scores?.dense||0;return(B.scores?.rerank||B.scores?.dense||0)-pt});const L=et.slice(0,k).map((U,B)=>{const pt=U.citation||U.url;return{rank:B+1,doc_id:U.doc_id,block_id:U.block_id,url:U.url,citation:pt,title:U.title||"Untitled",snippet:U.snippet,score:U.scores?.rerank||U.scores?.dense||0,metadata:{site:U.metadata?.site,lang:U.metadata?.lang,contentType:U.metadata?.content_type}}});return{success:!0,query:b,total:et.length,results:L,summary:`Found ${et.length} relevant results across ${M.length} source(s) for "${b}". Top result: ${L[0]?.title||"N/A"}`}}const R=D.organizationId&&D.organizationId!=="default"?D.organizationId:void 0,$={...D.filters,...N};try{const Z={q:b,k:Math.min(k,100)};R&&(Z.organizationId=R),Object.keys($).length>0&&(Z.filters=$);const K={"Content-Type":"application/json"};I.current&&(K.Authorization=`Bearer ${I.current}`);const et=await fetch(`${T}/search`,{method:"POST",headers:K,body:JSON.stringify(Z)});if(!et.ok){const B=await et.text();return{success:!1,error:`Search failed: ${et.status} ${B}`}}const L=await et.json(),U=L.candidates.map((B,pt)=>{const ht=B.citation||B.url;return{rank:pt+1,doc_id:B.doc_id,block_id:B.block_id,url:B.url,citation:ht,title:B.title||"Untitled",snippet:B.snippet,score:B.scores?.rerank||B.scores?.dense||0,metadata:{site:B.metadata?.site,lang:B.metadata?.lang,contentType:B.metadata?.content_type}}});return{success:!0,query:L.query,total:L.total,results:U,summary:`Found ${L.total} relevant results for "${b}". Top result: ${U[0]?.title||"N/A"}`}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Unknown error occurred"}}}:null,[j,T,I]),xe=m.useMemo(()=>D?.enabled?async function(b,k){const N=D.organizationId&&D.organizationId!=="default"?D.organizationId:M&&M.length>0?M[0]:void 0;try{const R={"Content-Type":"application/json"};I.current&&(R.Authorization=`Bearer ${I.current}`);const $=await fetch(`${T}/fetch`,{method:"POST",headers:R,body:JSON.stringify({doc_id:b,block_ids:k,...N?{organizationId:N}:{}})});if(!$.ok){const K=await $.text();return{success:!1,error:`Fetch failed: ${$.status} ${K}`}}const Z=await $.json();return{success:!0,blocks:Z.blocks||[],fullContent:Z.fullContent||"",pageUrl:Z.pageUrl||"",pageTitle:Z.pageTitle||"",summary:`Fetched ${Z.blocks?.length||0} blocks from ${Z.pageTitle||b}`}}catch(R){return{success:!1,error:R instanceof Error?R.message:"Unknown error occurred"}}}:null,[j,T,I]),ve=m.useMemo(()=>{const p=[...l,...h,Qe];return(!_||x)&&p.push(tn),D?.enabled&&(ye&&p.push(ye),xe&&p.push(xe)),p},[l,h,Qe,tn,ye,xe,_,x,D]),Zn=m.useMemo(()=>Oa(ve,f),[ve,f]),qt=m.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!_||x)&&p.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const b=[];return D?.enabled&&b.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Zn,...p,...b]},[Zn,_,x,D]),Pr=m.useMemo(()=>new Set(qt.map(p=>p.name)),[qt]),Sn=m.useMemo(()=>qt.filter(p=>p.name==="getState"?!0:p.name==="setState"?!_||x:Pr.has(p.name)),[qt,Pr,_,x]),An=m.useMemo(()=>{const p=new Map,b=new Map(Zn.map(k=>[k.name,k]));return p.set("getState",Qe),(!_||x)&&p.set("setState",tn),D?.enabled&&(ye&&p.set("searchDocs",ye),xe&&p.set("fetchDocContent",xe)),ve.forEach(k=>{if(k===Qe||k===tn||k===ye||k===xe)return;const N=k[_t];if(N){const $=b.get(N);if($){p.set($.name,k);return}}const R=qt.find($=>$.name===k.name);R&&p.set(R.name,k)}),p},[ve,qt,Qe,tn,ye,xe,_,x,D]),en=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),D?.enabled&&D.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(qt.map(k=>[k.name,k]));return h.forEach(k=>{const N=k[_t];if(N&&b.has(N))p.add(N);else{const R=qt.find($=>$.name===k.name);R&&p.add(R.name)}}),p},[h,qt,D]),jr=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];m.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&Me(JSON.parse(p));const b=localStorage.getItem("arcten-sidebar-width");b&&Qt(parseInt(b));const k=localStorage.getItem("arcten-sidebar-height");k&&Ee(parseInt(k));const N=localStorage.getItem("arcten-sidebar-detached");N&&It(JSON.parse(N));const R=localStorage.getItem("arcten-sidebar-position");if(R){const Z=JSON.parse(R),K=50,et=Math.max(K-i,Math.min(Z.x,window.innerWidth-K)),L=Math.max(0,Math.min(Z.y,window.innerHeight-K));De({x:et,y:L})}const $=localStorage.getItem("arcten-sidebar-minimized");$&&kt(JSON.parse($)),Ut(!0)}},[]);const re=m.useMemo(()=>w,[w?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!b.ok)throw new Error("Failed to fetch token");const k=await b.json();F(k.clientToken),I.current=k.clientToken,G(k.expiresAt),Y(null)}catch(b){Y(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{it.current&&clearTimeout(it.current)}),[S,re]),m.useEffect(()=>{if(!q)return;it.current&&clearTimeout(it.current);const p=Math.floor(Date.now()/1e3),b=q-p,N=Math.max(0,b-5);return it.current=setTimeout(async()=>{try{const R=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:re})});if(!R.ok)throw new Error("Failed to refresh token");const $=await R.json();F($.clientToken),I.current=$.clientToken,G($.expiresAt),Y(null)}catch(R){console.error("Token refresh failed:",R),Y(R instanceof Error?R.message:"Failed to refresh token")}},N*1e3),()=>{it.current&&clearTimeout(it.current)}},[q,S,re]),m.useEffect(()=>{(async()=>{if(ve.length!==0)try{const b=ve.map(N=>({name:N.name,code:N.toString()})),k=await fetch(`${T}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(k.ok){const N=await k.json();P(N.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[ve]),m.useEffect(()=>{Promise.resolve().then(()=>cf).then(p=>{Je(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{Jn(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Qn=m.useCallback(async()=>{if(!(!re?.id||!A)){rt(!0);try{const b=await(await fetch(`${T}/conversations`,{headers:{Authorization:`Bearer ${A}`}})).json();Q(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{rt(!1)}}},[re?.id,A,T]);m.useEffect(()=>{re?.id&&A&&Qn()},[re?.id,A,Qn]);function za(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Ua(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1);const b=_?y||{}:{};ot.current=b,_||nt(b),v&&v(b),Zt.current=!1}async function _a(p){if(A)try{await fetch(`${T}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${A}`}}),Q(W.filter(b=>b._id!==p)),p===H&&Ua()}catch(b){console.error("Failed to delete conversation:",b)}}async function Wa(p){wt(p.chatId),Pt(!1),rt(!0);try{const b=await fetch(`${T}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${I.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const N=(await b.json()).messages||[];Pn(N),ge(N)}catch(b){console.error("Failed to load conversation messages:",b);const k=p.messages||[];Pn(k),ge(k)}finally{rt(!1)}}const Ka=async(p,b={})=>{const k=b.headers?new Headers(b.headers):new Headers;return k.delete("user-agent"),k.delete("User-Agent"),fetch(p,{...b,headers:k})},{messages:Gt,sendMessage:qa,status:Ot,error:kr,stop:Cn,addToolResult:be,setMessages:Pn}=Ji.useChat({id:H||void 0,transport:new Ln.DefaultChatTransport({api:`${T}/chat`,fetch:Ka,headers:()=>{const p={};return I.current&&(p.Authorization=`Bearer ${I.current}`),p},body:()=>({tools:Sn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:Yn,state:ot.current})}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Gt[Gt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(k=>k.type?.startsWith("tool-")&&k.state==="input-available"&&typeof k.toolCallId=="string"&&k.input!==void 0)||[];for(const k of b){const N=k,R=N.type?.replace("tool-","")||"",$=N.toolCallId;if(en.has(R)){if(Ze.has($))continue;Kt(K=>K.has($)?K:new Set(K).add($)),(async()=>{try{const K=An.get(R);if(!K){console.warn(`[ArctenAgent] Tool ${R} not found in toolsMap. Available tools:`,Array.from(An.keys())),be({toolCallId:$,tool:R,output:`Error: Tool ${R} not found`}),Kt(B=>{const pt=new Set(B);return pt.delete($),pt});return}const et=gs(N.input),L=Sn.find(B=>B.name===R);let U;if(L&&L.jsonSchema?.properties){const pt=Object.keys(L.jsonSchema.properties).map(ht=>et[ht]);console.log(`[ArctenAgent] Executing safe tool ${R} with args:`,pt),U=await K(...pt)}else if(R==="getState")U=K();else if(R==="setState"){const B=et.updates||et;U=await K(B)}else U=await K(...Object.values(et));console.log(`[ArctenAgent] Tool ${R} completed, result:`,U),be({toolCallId:$,tool:R,output:U}),Kt(B=>{const pt=new Set(B);return pt.delete($),pt})}catch(K){console.error(`[ArctenAgent] Error executing safe tool ${R}:`,K),be({toolCallId:$,tool:R,output:`Error: ${K instanceof Error?K.message:String(K)}`}),Kt(et=>{const L=new Set(et);return L.delete($),L})}})()}}},[Gt,en,An,Sn,be]),m.useEffect(()=>{if(!H||!I.current)return;(async()=>{Jt(!0),xt(null);try{const k=`${T.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,N=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:H},format:"json"})});if(!N.ok){if(N.status===404||N.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${N.status}), using empty state`);const L=_?y||{}:{};ot.current=L,_||nt(L),v&&v(L),Zt.current=!0,Jt(!1);return}const et=await N.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${N.status} ${et}`)}const $=(await N.json())?.value||{},Z=!Zt.current;let K;Z?(K={..._?y||{}:{},...$},Zt.current=!0):K=$,ot.current=K,_||nt(K),v&&v(K)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const N=b instanceof Error?b:new Error(String(b));if(xt(N),!Zt.current){const R=_?y||{}:{};ot.current=R,_||nt(R),v&&v(R),Zt.current=!0}}finally{Jt(!1)}})()},[H,T,_,y,v]),m.useEffect(()=>{Bt&&ne.current&&ne.current.focus()},[Bt,Gt]);function Ga(){Me(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ha(){Me(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[Bt]),m.useEffect(()=>{Xe.current&&Xe.current.scrollIntoView({behavior:"smooth"})},[Gt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Ot==="streaming"||Ot==="submitted")&&(b.preventDefault(),Cn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Ot,Cn]);function Xa(){const p=crypto.randomUUID();wt(p),Pn([]),ge([]),Pt(!1)}function Mr(p){if(p.preventDefault(),!se.trim())return;(Ot==="streaming"||Ot==="submitted")&&Cn();const b=jr[Math.floor(Math.random()*jr.length)]||"Thinking...";Xn(b),qa({text:se}),Ye("")}function Ya(p){const b=p.target.value;Ye(b)}m.useEffect(()=>{if(!ee)return;function p(k){if(tt){const N=k.clientX-bt.x,R=k.clientY-bt.y;N>=a&&N<=c&&Qt(N),R>=400&&R<=1e3&&Ee(R)}else{const N=window.innerWidth-k.clientX;N>=a&&N<=c&&Qt(N)}}function b(){Vt(!1),localStorage.setItem("arcten-sidebar-width",zt.toString()),localStorage.setItem("arcten-sidebar-height",te.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ee,zt,te,tt,bt,a,c]);function Ja(p){p.preventDefault(),Vt(!0)}function Za(){It(!0),kt(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Qa(){It(!1),kt(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Er(){kt(!Ct),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ct))}function tc(p){tt&&(me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y}))}return m.useEffect(()=>{if(!tt)return;function p(){De(b=>{const N=window.innerWidth-50,R=window.innerHeight-50,$=50-zt,Z=0,K=Math.max($,Math.min(b.x,N)),et=Math.max(Z,Math.min(b.y,R));if(K!==b.x||et!==b.y){const L={x:K,y:et};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(L)),L}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[tt,zt]),m.useEffect(()=>{if(!He)return;function p(k){const N=k.clientX-Ne.x,R=k.clientY-Ne.y,$=50,Z=window.innerWidth-$,K=window.innerHeight-$,et=$-zt,L=0,U=Math.max(et,Math.min(N,Z)),B=Math.max(L,Math.min(R,K));De({x:U,y:B})}function b(){me(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(bt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[He,Ne,bt,zt]),Tn?X?d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",X]})}):A?d.jsx(bu,{features:Yh,children:d.jsx(Dn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:tt?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:tt?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
20
+ ${tt?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
21
21
  ${Bt?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
22
- ${Q?"border border-border":"border-l border-border"}
22
+ ${tt?"border border-border":"border-l border-border"}
23
23
  ${Bt?"":"w-[30px]"}
24
- `,style:Bt?Q?{width:`${zt}px`,height:Ct?"auto":`${te}px`,left:`${bt.x}px`,top:`${bt.y}px`}:{width:`${zt}px`}:void 0,onClick:Bt?void 0:Ga,children:Bt?d.jsxs(d.Fragment,{children:[!Q&&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"})}),Q&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Vt(!0)}}),d.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y})},children:d.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),d.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Vt(!0)}})]}),d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${Q?"cursor-move":""}`,onMouseDown:Q?tc:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${Q&&Ct?"cursor-pointer":""}`,onClick:Q&&Ct?p=>{p.stopPropagation(),Er()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:yt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Xa,"aria-label":"New chat",children:d.jsx(gt.Plus,{className:"h-4 w-4"})})}),d.jsx(le,{children:"Start a new conversation"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:yt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Q?Qa:Za,"aria-label":Q?"Dock sidebar":"Float sidebar",children:Q?d.jsx(gt.Dock,{className:"h-4 w-4"}):d.jsx(gt.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(le,{children:Q?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:yt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Q?Er:Ha,"aria-label":Q?Ct?"Maximize":"Minimize":"Close sidebar",children:Q?Ct?d.jsx(gt.Maximize2,{className:"h-4 w-4"}):d.jsx(gt.Minimize2,{className:"h-4 w-4"}):d.jsx(gt.X,{className:"h-4 w-4"})})}),d.jsx(le,{children:Q?Ct?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ct&&d.jsxs(d.Fragment,{children:[S&&W.length>0&&d.jsxs("div",{className:`border-b border-border ${ut?"flex flex-col flex-1":""}`,children:[d.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[d.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),d.jsx(Fn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ut||Qn(),Pt(!ut)},children:ut?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ut?"flex-1 overflow-y-auto":""}`,children:W.slice(0,ut?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs(Jh,{type:"button",className:yt(Te({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>Wa(p),children:[d.jsx("span",{className:"text-xs truncate",children:p.title}),d.jsx("div",{className:"ml-2 flex items-center",children:d.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:za(p.updatedAt)})})]}),d.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:b=>{b.stopPropagation(),_a(p._id)},"aria-label":"Delete conversation",children:d.jsx(gt.X,{className:"h-3 w-3"})})]},p._id))})]}),d.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[d.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Gt.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&d.jsx("div",{className:"mb-6",children:o}),d.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),C.length>0&&d.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:d.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(I?C:C.slice(0,10)).map(p=>d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ye(p.sampleUsage),ne.current?.focus()},children:p.friendlyName})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium",children:p.description}),d.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[d.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&d.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),C.length>10&&!I&&d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!0),children:["+",C.length-10," more"]})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),d.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:C.slice(10).map(p=>d.jsxs("div",{children:[d.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),d.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),d.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),I&&C.length>10&&d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[Gt.map(p=>{const j=p.parts.filter(L=>L.type==="text").map(L=>L.text).join("");let N=p.parts;p.role==="assistant"&&p.parts.some(U=>U.timestamp)&&(N=[...p.parts].sort((U,B)=>{const mt=U.timestamp||0,dt=B.timestamp||0;return mt-dt}));let R=[],$=new Map,J=[],q,tt=!0;if(p.role==="assistant"){const L=N.filter(dt=>dt.type==="text"&&dt.text),U=[],B=[];L.forEach(dt=>{const{citations:ie,citationMap:St,groupedCitations:kt,referencesText:oe}=Yi(dt.text);R.push(...ie),U.push(St),kt&&B.push(...kt),oe&&(q=oe)}),U.forEach(dt=>{dt.forEach((ie,St)=>{$.has(St)||$.set(St,ie)})}),J=Array.from(new Map(B.map(dt=>[dt.url,dt])).values()).sort((dt,ie)=>(dt.numbers[0]||0)-(ie.numbers[0]||0)),tt=!(Ot==="streaming"&&p.id===Gt.at(-1)?.id)}return d.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:d.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?d.jsx(Zh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:j}):d.jsx("div",{className:"space-y-2",children:N.map((L,U)=>{if(L.type?.startsWith("tool-")){const B=L.type?.replace("tool-","")||"",mt=Sn.find(St=>St.name===B),dt=L.state==="input-available",ie=L.state==="output-available";if(dt&&en.has(B),dt){if(en.has(B))return null;const St=gs(L.input);return d.jsx(Dn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(ef,{toolName:B,description:mt?.description||"",args:St,onApprove:async()=>{if(Ze.has(L.toolCallId))return;Kt(oe=>new Set(oe).add(L.toolCallId));const kt=An.get(B);if(kt)try{const oe=await kt(...Object.values(St));be({toolCallId:L.toolCallId,tool:B,output:oe})}catch(oe){be({toolCallId:L.toolCallId,tool:B,output:`Error: ${oe}`})}},onDeny:async()=>{Ze.has(L.toolCallId)||(Kt(kt=>new Set(kt).add(L.toolCallId)),be({toolCallId:L.toolCallId,tool:B,output:"User denied tool execution"}))}})},`${L.toolCallId}-${U}`)}else if(ie){const St=L.output==="User denied tool execution",kt=gs(L.input);return d.jsx(nf,{toolName:B,args:kt,isDenied:St,isSafe:en.has(B)},`${L.toolCallId}-${U}`)}return null}if(L.type==="text"&&L.text&&pe){const{processedText:B}=Yi(L.text),St=!N.slice(U+1).some(kt=>kt.type==="text"&&kt.text)&&tt&&$.size>0;return d.jsx(gf,{text:B,citations:R,citationMap:$,groupedCitations:St?J:void 0,referencesText:St?q:void 0,ResponseComponent:pe,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:E,showReferences:St},`${p.id}-${U}`)}return L.type==="reasoning"&&L.text?d.jsxs(Fa,{className:"w-full",isStreaming:Ot==="streaming"&&U===p.parts.length-1&&p.id===Gt.at(-1)?.id,children:[d.jsx($a,{}),d.jsx(Ba,{children:L.text})]},`${p.id}-${U}`):null})})})},p.id)}),d.jsx("div",{ref:Xe})]})}),Mr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Mr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(vu,{mode:"wait",children:(Ot==="streaming"||Ot==="submitted")&&d.jsxs(Dn,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[d.jsx(Dn,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),d.jsx("p",{className:"text-xs text-muted-foreground",children:Hn})]})}),d.jsxs("form",{onSubmit:kr,className:"relative",children:[d.jsx(to,{ref:ne,value:se,onChange:Ya,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),kr(p))}}),Ot==="streaming"||Ot==="submitted"?d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:yt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Cn,children:d.jsx(gt.Square,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Escape"})," to stop"]})]}):d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"submit",className:yt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!se.trim(),children:d.jsx(gt.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Enter"})," to send"]})]})]})]})]}),d.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[d.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),d.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),d.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[d.jsx(gt.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),d.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function un(t){if(typeof t=="string")try{const e=JSON.parse(t);return un(e)}catch{return t}if(Array.isArray(t))return t.map(un);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=un(s);return e}return t}function wf(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return un(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?un(t):{}}function Tf({apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:e="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:h,onStateChange:f,allowStateEdits:g=!0,onToolCall:x,onFinish:y,sources:S,ragConfig:T,ragFilters:w}={}){const v=m.useMemo(()=>T!==void 0?T:w?{enabled:!0,filters:w}:S&&S.length>0?{enabled:!0,organizationId:S[0],autoExecute:!0,filters:void 0}:{enabled:!1},[S,T,w]),[k,V]=m.useState(n||null),E=m.useRef(n||null),[D,A]=m.useState(null),[F,M]=m.useState(null),G=m.useRef(null),[H,_]=m.useState([]),[Y,et]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[K,nt]=m.useState(!1),[ht,lt]=m.useState(new Set),st=h!==void 0,[Jt,Me]=m.useState({}),xt=m.useRef({}),Zt=st?h||{}:Jt;st&&h?xt.current=h:st||(xt.current=Jt);const[Bt,ke]=m.useState(!1),[zt,Qt]=m.useState(null),te=m.useRef(!1),Ee=m.useCallback(async(C,P=3)=>{if(!Y||!E.current)return;const I=async()=>{const W=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,Z=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Y,updates:C},format:"json"})});if(!Z.ok){if(Z.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const X=await Z.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${Z.status} ${X}`)}};for(let O=0;O<P;O++)try{await I(),Qt(null);return}catch(W){if(O===P-1){const X=W instanceof Error?W:new Error(String(W));throw Qt(X),console.error("Failed to sync state to Convex after retries:",W),X}await new Promise(X=>setTimeout(X,Math.pow(2,O)*100))}},[Y,t,E]),ee=m.useMemo(()=>function(){return xt.current},[]),Vt=m.useMemo(()=>async function(P){const I={...xt.current,...P};xt.current=I,st||Me(I),f&&f(I);try{await Ee(P)}catch(O){throw O}},[Ee,f,st]);m.useEffect(()=>{st&&h&&(xt.current=h)},[st,h]);const Q=m.useMemo(()=>v?.enabled?async function(P,I=20,O){const W={...v.filters,...O};if(S&&S.length>1){const X=S.map(it=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...E.current?{Authorization:`Bearer ${E.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(I,100),organizationId:it,...Object.keys(W).length>0?{filters:W}:{}})}).then(rt=>rt.ok?rt.json():null)),wt=await Promise.all(X),ut=[];for(const it of wt)it?.candidates&&ut.push(...it.candidates);ut.sort((it,rt)=>{const Re=it.scores?.rerank||it.scores?.dense||0;return(rt.scores?.rerank||rt.scores?.dense||0)-Re});const Pt=ut.slice(0,I).map((it,rt)=>{const Re=it.citation||it.url;return{rank:rt+1,doc_id:it.doc_id,block_id:it.block_id,url:it.url,citation:Re,title:it.title||"Untitled",snippet:it.snippet,score:it.scores?.rerank||it.scores?.dense||0,metadata:{site:it.metadata?.site,lang:it.metadata?.lang,contentType:it.metadata?.content_type}}});return{success:!0,query:P,total:ut.length,results:Pt,summary:`Found ${ut.length} relevant results across ${S.length} source(s) for "${P}". Top result: ${Pt[0]?.title||"N/A"}`}}const Z=v.organizationId&&v.organizationId!=="default"?v.organizationId:S&&S.length>0?S[0]:void 0;try{const X={q:P,k:Math.min(I,100)};Z&&(X.organizationId=Z),Object.keys(W).length>0&&(X.filters=W);const wt={"Content-Type":"application/json"};E.current&&(wt.Authorization=`Bearer ${E.current}`);const ut=await fetch(`${t}/search`,{method:"POST",headers:wt,body:JSON.stringify(X)});if(!ut.ok){const rt=await ut.text();return{success:!1,error:`Search failed: ${ut.status} ${rt}`}}const Pt=await ut.json(),it=Pt.candidates.map((rt,Re)=>{const ge=rt.citation||rt.url;return{rank:Re+1,doc_id:rt.doc_id,block_id:rt.block_id,url:rt.url,citation:ge,title:rt.title||"Untitled",snippet:rt.snippet,score:rt.scores?.rerank||rt.scores?.dense||0,metadata:{site:rt.metadata?.site,lang:rt.metadata?.lang,contentType:rt.metadata?.content_type}}});return{success:!0,query:Pt.query,total:Pt.total,results:it,summary:`Found ${Pt.total} relevant results for "${P}". Top result: ${it[0]?.title||"N/A"}`}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Unknown error occurred"}}}:null,[v,t,E]),It=m.useMemo(()=>v?.enabled?async function(P,I){const O=v.organizationId&&v.organizationId!=="default"?v.organizationId:S&&S.length>0?S[0]:void 0;try{const W={"Content-Type":"application/json"};E.current&&(W.Authorization=`Bearer ${E.current}`);const Z=await fetch(`${t}/fetch`,{method:"POST",headers:W,body:JSON.stringify({doc_id:P,block_ids:I,...O?{organizationId:O}:{}})});if(!Z.ok){const wt=await Z.text();return{success:!1,error:`Fetch failed: ${Z.status} ${wt}`}}const X=await Z.json();return{success:!0,blocks:X.blocks||[],fullContent:X.fullContent||"",pageUrl:X.pageUrl||"",pageTitle:X.pageTitle||"",summary:`Fetched ${X.blocks?.length||0} blocks from ${X.pageTitle||P}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[v,t,E]),Ct=m.useMemo(()=>{const C=[...o,...i,ee];return(!st||g)&&C.push(Vt),v?.enabled&&(Q&&C.push(Q),It&&C.push(It)),C},[o,i,ee,Vt,Q,It,v,st,g]),Mt=m.useMemo(()=>Oa(Ct,a),[Ct,a]),bt=m.useMemo(()=>{const C=new Map,P=new Map(Mt.map(I=>[I.name,I]));return C.set("getState",ee),(!st||g)&&C.set("setState",Vt),v?.enabled&&(Q&&C.set("searchDocs",Q),It&&C.set("fetchDocContent",It)),Ct.forEach(I=>{if(I===ee||I===Vt||I===Q||I===It)return;const O=I[_t];if(O){const Z=P.get(O);if(Z){C.set(Z.name,I);return}}const W=Mt.find(Z=>Z.name===I.name);W&&C.set(W.name,I)}),C},[Ct,Mt,ee,Vt,Q,It,v,st,g]),De=m.useMemo(()=>new Set(Mt.map(C=>C.name)),[Mt]),He=m.useMemo(()=>{const C=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!st||g)&&C.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const P=[];return v?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...Mt,...C,...P]},[Mt,v,st,g]),me=m.useMemo(()=>He.filter(C=>C.name==="getState"?!0:C.name==="setState"?!st||g:v?.enabled&&(C.name==="searchDocs"||C.name==="fetchDocContent")?!0:De.has(C.name)),[He,De,st,g,v]),Ne=m.useMemo(()=>{const C=new Set;return C.add("getState"),C.add("setState"),v?.enabled&&v.autoExecute!==!1&&(C.add("searchDocs"),C.add("fetchDocContent")),i.forEach(P=>{for(const[I,O]of bt.entries())if(O===P){C.add(I);break}}),C},[i,bt,v]);m.useEffect(()=>s||n?void 0:((async()=>{try{const P=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!P.ok)throw new Error("Failed to fetch token");const I=await P.json();V(I.clientToken),E.current=I.clientToken,M(I.expiresAt),A(null)}catch(P){console.error("[useAgent] Token fetch failed:",P),A(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{G.current&&clearTimeout(G.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!F||s||n)return;G.current&&clearTimeout(G.current);const C=Math.floor(Date.now()/1e3),P=F-C,O=Math.max(0,P-5);return G.current=setTimeout(async()=>{try{const W=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!W.ok)throw new Error("Failed to refresh token");const Z=await W.json();V(Z.clientToken),E.current=Z.clientToken,M(Z.expiresAt),A(null)}catch(W){console.error("[useAgent] Token refresh failed:",W),A(W instanceof Error?W.message:"Failed to refresh token")}},O*1e3),()=>{G.current&&clearTimeout(G.current)}},[F,e,JSON.stringify(r),s,n]);const wn=async(C,P={})=>{const I=P.headers?new Headers(P.headers):new Headers;I.delete("user-agent"),I.delete("User-Agent"),console.log("[useAgent] Making request to:",C),console.log("[useAgent] Method:",P.method||"GET"),console.log("[useAgent] Has Authorization header:",I.has("Authorization")),console.log("[useAgent] Client token available:",!!E.current);try{const O=await fetch(C,{...P,headers:I});if(!O.ok){console.error("[useAgent] Request failed:",O.status,O.statusText);const W=await O.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",W)}return O}catch(O){throw console.error("[useAgent] Fetch error:",O),O}},Tn=`${t}/chat`;console.log("[useAgent] Chat API URL:",Tn);const{messages:Ut,sendMessage:Xe,status:ne,error:se,stop:Ye,addToolResult:pe,setMessages:Je}=Ji.useChat({id:Y||void 0,messages:u,transport:new Ln.DefaultChatTransport({api:Tn,fetch:wn,headers:()=>{const C={};return E.current?(C.Authorization=`Bearer ${E.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),C},body:()=>{const C=me.map(O=>({name:O.name,description:O.description,inputSchema:O.jsonSchema})),P=C.filter(O=>O.name==="getState"||O.name==="setState").map(O=>O.name),I=C.filter(O=>O.name==="searchDocs"||O.name==="fetchDocContent").map(O=>O.name);return P.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",P),I.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",I):v?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:C,systemPrompt:c,state:xt.current,...w&&{ragFilters:w}}}}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ut.forEach(C=>{C.role==="assistant"&&C.parts.forEach(P=>{if(!P.type?.startsWith("tool-")||P.state!=="input-available")return;const I=P.type.replace("tool-",""),O=P.toolCallId;if(ht.has(O))return;lt(Z=>new Set(Z).add(O));const W=wf(P.input);if(Ne.has(I)){const Z=bt.get(I);Z?(async()=>{try{const X=me.find(ut=>ut.name===I);let wt;if(X&&X.jsonSchema?.properties){const Pt=Object.keys(X.jsonSchema.properties).map(it=>W[it]);wt=await Z(...Pt)}else if(I==="getState")wt=Z();else if(I==="setState"){const ut=W.updates||W;wt=await Z(ut)}else wt=await Z(...Object.values(W));pe({toolCallId:O,tool:I,output:wt})}catch(X){console.error(`[useAgent] Error executing tool ${I}:`,X),pe({toolCallId:O,tool:I,output:`Error: ${X}`})}})():console.warn(`[useAgent] Tool ${I} not found in toolsMap`)}else x&&x({toolCall:{toolCallId:O,toolName:I,args:W}})})})},[Ut,Ne,bt,x,pe,ht,Vt,me]),m.useEffect(()=>{if(ne==="ready"&&Ut.length>0&&y){const C=Ut[Ut.length-1];C&&C.role==="assistant"&&y({message:C,messages:Ut,isAbort:!1,isDisconnect:!1,isError:!!se})}},[ne,Ut,se,y]);async function Hn(){if(!(!r?.id||!k)){nt(!0);try{const P=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${k}`}})).json();_(P.conversations||[])}catch(C){console.error("Failed to fetch conversations:",C)}finally{nt(!1)}}}m.useEffect(()=>{r?.id&&k&&Hn()},[JSON.stringify(r),k,t]),m.useEffect(()=>{if(!Y||!E.current)return;(async()=>{ke(!0),Qt(null);try{const P=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Y},format:"json"})});if(!P.ok){const W=await P.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${P.status} ${W}`)}const O=(await P.json())?.value||{};xt.current=O,st||Me(O),f&&f(O),te.current=!0}catch(P){console.error("Failed to fetch state:",P);const I=P instanceof Error?P:new Error(String(P));Qt(I),te.current||(xt.current={},st?f&&f({}):(Me({}),f&&f({})),te.current=!0)}finally{ke(!1)}})()},[Y,t,st,f]);async function Xn(C){et(C),nt(!0);try{const P=await fetch(`${t}/conversations/${C}/messages`,{headers:{Authorization:`Bearer ${E.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const O=(await P.json()).messages||[];Je(O)}catch(P){console.error("Failed to load conversation messages:",P)}finally{nt(!1)}}async function Ze(C){if(k)try{await fetch(`${t}/conversations/${C}`,{method:"DELETE",headers:{Authorization:`Bearer ${k}`}}),_(H.filter(P=>P._id!==C)),C===Y&&Kt()}catch(P){console.error("Failed to delete conversation:",P)}}function Kt(){const C=crypto.randomUUID();et(C),Je([]),lt(new Set),xt.current={},st?f&&f({}):(Me({}),f&&f({})),te.current=!1}function Yn(C){pe(C)}async function Jn(C){const P={...xt.current,...C};xt.current=P,st||Me(P),f&&f(P);try{await Ee(C)}catch(I){throw I}}return{id:Y,messages:Ut,status:ne,error:se,sendMessage:Xe,stop:Ye,addToolOutput:Yn,setMessages:Je,conversations:H,loadConversation:Xn,deleteConversation:Ze,startNewConversation:Kt,isLoadingConversations:K,clientToken:k,tokenError:D,state:Zt,setState:Jn,isStateLoading:Bt,stateError:zt}}exports.verifyToken=fc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=_t;exports.ArctenAgent=bf;exports.preserveToolName=Qh;exports.useAgent=Tf;
24
+ `,style:Bt?tt?{width:`${zt}px`,height:Ct?"auto":`${te}px`,left:`${bt.x}px`,top:`${bt.y}px`}:{width:`${zt}px`}:void 0,onClick:Bt?void 0:Ga,children:Bt?d.jsxs(d.Fragment,{children:[!tt&&d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Ja,children:d.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),tt&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Vt(!0)}}),d.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),me(!0),wn({x:p.clientX-bt.x,y:p.clientY-bt.y})},children:d.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),d.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Vt(!0)}})]}),d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${tt?"cursor-move":""}`,onMouseDown:tt?tc:void 0,children:[d.jsx("h2",{className:`text-base font-semibold ${tt&&Ct?"cursor-pointer":""}`,onClick:tt&&Ct?p=>{p.stopPropagation(),Er()}:void 0,children:r}),d.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Xa,"aria-label":"New chat",children:d.jsx(yt.Plus,{className:"h-4 w-4"})})}),d.jsx(le,{children:"Start a new conversation"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:tt?Qa:Za,"aria-label":tt?"Dock sidebar":"Float sidebar",children:tt?d.jsx(yt.Dock,{className:"h-4 w-4"}):d.jsx(yt.PictureInPicture2,{className:"h-4 w-4"})})}),d.jsx(le,{children:tt?"Dock to sidebar":"Undock to floating window"})]}),d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:tt?Er:Ha,"aria-label":tt?Ct?"Maximize":"Minimize":"Close sidebar",children:tt?Ct?d.jsx(yt.Maximize2,{className:"h-4 w-4"}):d.jsx(yt.Minimize2,{className:"h-4 w-4"}):d.jsx(yt.X,{className:"h-4 w-4"})})}),d.jsx(le,{children:tt?Ct?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ct&&d.jsxs(d.Fragment,{children:[w&&W.length>0&&d.jsxs("div",{className:`border-b border-border ${dt?"flex flex-col flex-1":""}`,children:[d.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[d.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),d.jsx(Fn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{dt||Qn(),Pt(!dt)},children:dt?"Show less":"View all"})]}),d.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${dt?"flex-1 overflow-y-auto":""}`,children:W.slice(0,dt?void 0:3).map(p=>d.jsxs("div",{className:"group relative",children:[d.jsxs(Jh,{type:"button",className:mt(Te({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>Wa(p),children:[d.jsx("span",{className:"text-xs truncate",children:p.title}),d.jsx("div",{className:"ml-2 flex items-center",children:d.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:za(p.updatedAt)})})]}),d.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:b=>{b.stopPropagation(),_a(p._id)},"aria-label":"Delete conversation",children:d.jsx(yt.X,{className:"h-3 w-3"})})]},p._id))})]}),d.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[d.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Gt.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&d.jsx("div",{className:"mb-6",children:o}),d.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),C.length>0&&d.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:d.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(V?C:C.slice(0,10)).map(p=>d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ye(p.sampleUsage),ne.current?.focus()},children:p.friendlyName})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium",children:p.description}),d.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[d.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&d.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),C.length>10&&!V&&d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsxs(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!0),children:["+",C.length-10," more"]})}),d.jsx(le,{children:d.jsxs("div",{className:"max-w-xs",children:[d.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),d.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:C.slice(10).map(p=>d.jsxs("div",{children:[d.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),d.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),d.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),V&&C.length>10&&d.jsx(ts,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>O(!1),children:"Show less"})]})})]}):d.jsxs(d.Fragment,{children:[Gt.map(p=>{const k=p.parts.filter(L=>L.type==="text").map(L=>L.text).join("");let N=p.parts;p.role==="assistant"&&p.parts.some(U=>U.timestamp)&&(N=[...p.parts].sort((U,B)=>{const pt=U.timestamp||0,ht=B.timestamp||0;return pt-ht}));let R=[],$=new Map,Z=[],K,et=!0;if(p.role==="assistant"){const L=N.filter(ht=>ht.type==="text"&&ht.text),U=[],B=[];L.forEach(ht=>{const{citations:ie,citationMap:St,groupedCitations:Mt,referencesText:oe}=Yi(ht.text);R.push(...ie),U.push(St),Mt&&B.push(...Mt),oe&&(K=oe)}),U.forEach(ht=>{ht.forEach((ie,St)=>{$.has(St)||$.set(St,ie)})}),Z=Array.from(new Map(B.map(ht=>[ht.url,ht])).values()).sort((ht,ie)=>(ht.numbers[0]||0)-(ie.numbers[0]||0)),et=!(Ot==="streaming"&&p.id===Gt.at(-1)?.id)}return d.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:d.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?d.jsx(Zh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:k}):d.jsx("div",{className:"space-y-2",children:N.map((L,U)=>{if(L.type?.startsWith("tool-")){const B=L.type?.replace("tool-","")||"",pt=Sn.find(St=>St.name===B),ht=L.state==="input-available",ie=L.state==="output-available";if(ht&&en.has(B),ht){if(en.has(B))return null;const St=gs(L.input);return d.jsx(Dn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:d.jsx(ef,{toolName:B,description:pt?.description||"",args:St,onApprove:async()=>{if(Ze.has(L.toolCallId))return;Kt(oe=>new Set(oe).add(L.toolCallId));const Mt=An.get(B);if(Mt)try{const oe=await Mt(...Object.values(St));be({toolCallId:L.toolCallId,tool:B,output:oe})}catch(oe){be({toolCallId:L.toolCallId,tool:B,output:`Error: ${oe}`})}},onDeny:async()=>{Ze.has(L.toolCallId)||(Kt(Mt=>new Set(Mt).add(L.toolCallId)),be({toolCallId:L.toolCallId,tool:B,output:"User denied tool execution"}))}})},`${L.toolCallId}-${U}`)}else if(ie){const St=L.output==="User denied tool execution",Mt=gs(L.input);return d.jsx(nf,{toolName:B,args:Mt,isDenied:St,isSafe:en.has(B)},`${L.toolCallId}-${U}`)}return null}if(L.type==="text"&&L.text&&pe){const{processedText:B}=Yi(L.text),St=!N.slice(U+1).some(Mt=>Mt.type==="text"&&Mt.text)&&et&&$.size>0;return d.jsx(gf,{text:B,citations:R,citationMap:$,groupedCitations:St?Z:void 0,referencesText:St?K:void 0,ResponseComponent:pe,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:E,showReferences:St},`${p.id}-${U}`)}return L.type==="reasoning"&&L.text?d.jsxs(Fa,{className:"w-full",isStreaming:Ot==="streaming"&&U===p.parts.length-1&&p.id===Gt.at(-1)?.id,children:[d.jsx($a,{}),d.jsx(Ba,{children:L.text})]},`${p.id}-${U}`):null})})})},p.id)}),d.jsx("div",{ref:Xe})]})}),kr&&d.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",kr.message]}),d.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[d.jsx(vu,{mode:"wait",children:(Ot==="streaming"||Ot==="submitted")&&d.jsxs(Dn,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[d.jsx(Dn,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),d.jsx("p",{className:"text-xs text-muted-foreground",children:Hn})]})}),d.jsxs("form",{onSubmit:Mr,className:"relative",children:[d.jsx(to,{ref:ne,value:se,onChange:Ya,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Mr(p))}}),Ot==="streaming"||Ot==="submitted"?d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"button",className:mt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Cn,children:d.jsx(yt.Square,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Escape"})," to stop"]})]}):d.jsxs(ae,{children:[d.jsx(ce,{asChild:!0,children:d.jsx("button",{type:"submit",className:mt(Te({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!se.trim(),children:d.jsx(yt.ArrowRight,{className:"h-4 w-4"})})}),d.jsxs(le,{children:[d.jsx(Rr,{children:"Enter"})," to send"]})]})]})]})]}),d.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[d.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),d.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),d.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[d.jsx(yt.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),d.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):d.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:d.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function un(t){if(typeof t=="string")try{const e=JSON.parse(t);return un(e)}catch{return t}if(Array.isArray(t))return t.map(un);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=un(s);return e}return t}function bf(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return un(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?un(t):{}}function wf({apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:e="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:u=[],conversationId:l,state:h,onStateChange:f,allowStateEdits:g=!0,onToolCall:S,onFinish:T,sources:w,ragConfig:y,ragFilters:v}={}){const x=m.useMemo(()=>y!==void 0?y:v?{enabled:!0,filters:v}:w&&w.length>0?{enabled:!0,organizationId:w[0],autoExecute:!0,filters:void 0}:{enabled:!1},[w,y,v]),[M,j]=m.useState(n||null),E=m.useRef(n||null),[D,A]=m.useState(null),[F,I]=m.useState(null),X=m.useRef(null),[Y,q]=m.useState([]),[G,it]=m.useState(l||(typeof window<"u"?crypto.randomUUID():null)),[_,J]=m.useState(!1),[nt,ot]=m.useState(new Set),st=h!==void 0,[Jt,ke]=m.useState({}),xt=m.useRef({}),Zt=st?h||{}:Jt;st&&h?xt.current=h:st||(xt.current=Jt);const[Bt,Me]=m.useState(!1),[zt,Qt]=m.useState(null),te=m.useRef(!1),Ee=m.useCallback(async(C,P=3)=>{if(!G||!E.current)return;const V=async()=>{const W=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:G,updates:C},format:"json"})});if(!Q.ok){if(Q.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const H=await Q.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${Q.status} ${H}`)}};for(let O=0;O<P;O++)try{await V(),Qt(null);return}catch(W){if(O===P-1){const H=W instanceof Error?W:new Error(String(W));throw Qt(H),console.error("Failed to sync state to Convex after retries:",W),H}await new Promise(H=>setTimeout(H,Math.pow(2,O)*100))}},[G,t,E]),ee=m.useMemo(()=>function(){return xt.current},[]),Vt=m.useMemo(()=>async function(P){const V={...xt.current,...P};xt.current=V,st||ke(V),f&&f(V);try{await Ee(P)}catch(O){throw O}},[Ee,f,st]);m.useEffect(()=>{st&&h&&(xt.current=h)},[st,h]);const tt=m.useMemo(()=>x?.enabled?async function(P,V=20,O){const W={...x.filters,...O};if(w&&w.length>1){const H=w.map(at=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...E.current?{Authorization:`Bearer ${E.current}`}:{}},body:JSON.stringify({q:P,k:Math.min(V,100),organizationId:at,...Object.keys(W).length>0?{filters:W}:{}})}).then(rt=>rt.ok?rt.json():null)),wt=await Promise.all(H),dt=[];for(const at of wt)at?.candidates&&dt.push(...at.candidates);dt.sort((at,rt)=>{const Re=at.scores?.rerank||at.scores?.dense||0;return(rt.scores?.rerank||rt.scores?.dense||0)-Re});const Pt=dt.slice(0,V).map((at,rt)=>{const Re=at.citation||at.url;return{rank:rt+1,doc_id:at.doc_id,block_id:at.block_id,url:at.url,citation:Re,title:at.title||"Untitled",snippet:at.snippet,score:at.scores?.rerank||at.scores?.dense||0,metadata:{site:at.metadata?.site,lang:at.metadata?.lang,contentType:at.metadata?.content_type}}});return{success:!0,query:P,total:dt.length,results:Pt,summary:`Found ${dt.length} relevant results across ${w.length} source(s) for "${P}". Top result: ${Pt[0]?.title||"N/A"}`}}const Q=x.organizationId&&x.organizationId!=="default"?x.organizationId:w&&w.length>0?w[0]:void 0;try{const H={q:P,k:Math.min(V,100)};Q&&(H.organizationId=Q),Object.keys(W).length>0&&(H.filters=W);const wt={"Content-Type":"application/json"};E.current&&(wt.Authorization=`Bearer ${E.current}`);const dt=await fetch(`${t}/search`,{method:"POST",headers:wt,body:JSON.stringify(H)});if(!dt.ok){const rt=await dt.text();return{success:!1,error:`Search failed: ${dt.status} ${rt}`}}const Pt=await dt.json(),at=Pt.candidates.map((rt,Re)=>{const ge=rt.citation||rt.url;return{rank:Re+1,doc_id:rt.doc_id,block_id:rt.block_id,url:rt.url,citation:ge,title:rt.title||"Untitled",snippet:rt.snippet,score:rt.scores?.rerank||rt.scores?.dense||0,metadata:{site:rt.metadata?.site,lang:rt.metadata?.lang,contentType:rt.metadata?.content_type}}});return{success:!0,query:Pt.query,total:Pt.total,results:at,summary:`Found ${Pt.total} relevant results for "${P}". Top result: ${at[0]?.title||"N/A"}`}}catch(H){return{success:!1,error:H instanceof Error?H.message:"Unknown error occurred"}}}:null,[x,t,E]),It=m.useMemo(()=>x?.enabled?async function(P,V){const O=x.organizationId&&x.organizationId!=="default"?x.organizationId:w&&w.length>0?w[0]:void 0;try{const W={"Content-Type":"application/json"};E.current&&(W.Authorization=`Bearer ${E.current}`);const Q=await fetch(`${t}/fetch`,{method:"POST",headers:W,body:JSON.stringify({doc_id:P,block_ids:V,...O?{organizationId:O}:{}})});if(!Q.ok){const wt=await Q.text();return{success:!1,error:`Fetch failed: ${Q.status} ${wt}`}}const H=await Q.json();return{success:!0,blocks:H.blocks||[],fullContent:H.fullContent||"",pageUrl:H.pageUrl||"",pageTitle:H.pageTitle||"",summary:`Fetched ${H.blocks?.length||0} blocks from ${H.pageTitle||P}`}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Unknown error occurred"}}}:null,[x,t,E]),Ct=m.useMemo(()=>{const C=[...o,...i,ee];return(!st||g)&&C.push(Vt),x?.enabled&&(tt&&C.push(tt),It&&C.push(It)),C},[o,i,ee,Vt,tt,It,x,st,g]),kt=m.useMemo(()=>Oa(Ct,a),[Ct,a]),bt=m.useMemo(()=>{const C=new Map,P=new Map(kt.map(V=>[V.name,V]));return C.set("getState",ee),(!st||g)&&C.set("setState",Vt),x?.enabled&&(tt&&C.set("searchDocs",tt),It&&C.set("fetchDocContent",It)),Ct.forEach(V=>{if(V===ee||V===Vt||V===tt||V===It)return;const O=V[_t];if(O){const Q=P.get(O);if(Q){C.set(Q.name,V);return}}const W=kt.find(Q=>Q.name===V.name);W&&C.set(W.name,V)}),C},[Ct,kt,ee,Vt,tt,It,x,st,g]),De=m.useMemo(()=>new Set(kt.map(C=>C.name)),[kt]),He=m.useMemo(()=>{const C=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!st||g)&&C.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const P=[];return x?.enabled&&P.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...kt,...C,...P]},[kt,x,st,g]),me=m.useMemo(()=>He.filter(C=>C.name==="getState"?!0:C.name==="setState"?!st||g:x?.enabled&&(C.name==="searchDocs"||C.name==="fetchDocContent")?!0:De.has(C.name)),[He,De,st,g,x]),Ne=m.useMemo(()=>{const C=new Set;return C.add("getState"),C.add("setState"),x?.enabled&&x.autoExecute!==!1&&(C.add("searchDocs"),C.add("fetchDocContent")),i.forEach(P=>{for(const[V,O]of bt.entries())if(O===P){C.add(V);break}}),C},[i,bt,x]);m.useEffect(()=>s||n?void 0:((async()=>{try{const P=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!P.ok)throw new Error("Failed to fetch token");const V=await P.json();j(V.clientToken),E.current=V.clientToken,I(V.expiresAt),A(null)}catch(P){console.error("[useAgent] Token fetch failed:",P),A(P instanceof Error?P.message:"Failed to fetch token")}})(),()=>{X.current&&clearTimeout(X.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!F||s||n)return;X.current&&clearTimeout(X.current);const C=Math.floor(Date.now()/1e3),P=F-C,O=Math.max(0,P-5);return X.current=setTimeout(async()=>{try{const W=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!W.ok)throw new Error("Failed to refresh token");const Q=await W.json();j(Q.clientToken),E.current=Q.clientToken,I(Q.expiresAt),A(null)}catch(W){console.error("[useAgent] Token refresh failed:",W),A(W instanceof Error?W.message:"Failed to refresh token")}},O*1e3),()=>{X.current&&clearTimeout(X.current)}},[F,e,JSON.stringify(r),s,n]);const wn=async(C,P={})=>{const V=P.headers?new Headers(P.headers):new Headers;V.delete("user-agent"),V.delete("User-Agent"),console.log("[useAgent] Making request to:",C),console.log("[useAgent] Method:",P.method||"GET"),console.log("[useAgent] Has Authorization header:",V.has("Authorization")),console.log("[useAgent] Client token available:",!!E.current);try{const O=await fetch(C,{...P,headers:V});if(!O.ok){console.error("[useAgent] Request failed:",O.status,O.statusText);const W=await O.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",W)}return O}catch(O){throw console.error("[useAgent] Fetch error:",O),O}},Tn=`${t}/chat`;console.log("[useAgent] Chat API URL:",Tn);const{messages:Ut,sendMessage:Xe,status:ne,error:se,stop:Ye,addToolResult:pe,setMessages:Je}=Ji.useChat({id:G||void 0,messages:u,transport:new Ln.DefaultChatTransport({api:Tn,fetch:wn,headers:()=>{const C={};return E.current?(C.Authorization=`Bearer ${E.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),C},body:()=>{const C=me.map(O=>({name:O.name,description:O.description,inputSchema:O.jsonSchema})),P=C.filter(O=>O.name==="getState"||O.name==="setState").map(O=>O.name),V=C.filter(O=>O.name==="searchDocs"||O.name==="fetchDocContent").map(O=>O.name);return P.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",P),V.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",V):x?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:C,systemPrompt:c,state:xt.current,...v&&{ragFilters:v}}}}),sendAutomaticallyWhen:Ln.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{Ut.forEach(C=>{C.role==="assistant"&&C.parts.forEach(P=>{if(!P.type?.startsWith("tool-")||P.state!=="input-available")return;const V=P.type.replace("tool-",""),O=P.toolCallId;if(nt.has(O))return;ot(Q=>new Set(Q).add(O));const W=bf(P.input);if(Ne.has(V)){const Q=bt.get(V);Q?(async()=>{try{const H=me.find(dt=>dt.name===V);let wt;if(H&&H.jsonSchema?.properties){const Pt=Object.keys(H.jsonSchema.properties).map(at=>W[at]);wt=await Q(...Pt)}else if(V==="getState")wt=Q();else if(V==="setState"){const dt=W.updates||W;wt=await Q(dt)}else wt=await Q(...Object.values(W));pe({toolCallId:O,tool:V,output:wt})}catch(H){console.error(`[useAgent] Error executing tool ${V}:`,H),pe({toolCallId:O,tool:V,output:`Error: ${H}`})}})():console.warn(`[useAgent] Tool ${V} not found in toolsMap`)}else S&&S({toolCall:{toolCallId:O,toolName:V,args:W}})})})},[Ut,Ne,bt,S,pe,nt,Vt,me]),m.useEffect(()=>{if(ne==="ready"&&Ut.length>0&&T){const C=Ut[Ut.length-1];C&&C.role==="assistant"&&T({message:C,messages:Ut,isAbort:!1,isDisconnect:!1,isError:!!se})}},[ne,Ut,se,T]);async function Hn(){if(!(!r?.id||!M)){J(!0);try{const P=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${M}`}})).json();q(P.conversations||[])}catch(C){console.error("Failed to fetch conversations:",C)}finally{J(!1)}}}m.useEffect(()=>{r?.id&&M&&Hn()},[JSON.stringify(r),M,t]),m.useEffect(()=>{if(!G||!E.current)return;(async()=>{Me(!0),Qt(null);try{const P=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:G},format:"json"})});if(!P.ok){const W=await P.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${P.status} ${W}`)}const O=(await P.json())?.value||{};xt.current=O,st||ke(O),f&&f(O),te.current=!0}catch(P){console.error("Failed to fetch state:",P);const V=P instanceof Error?P:new Error(String(P));Qt(V),te.current||(xt.current={},st?f&&f({}):(ke({}),f&&f({})),te.current=!0)}finally{Me(!1)}})()},[G,t,st,f]);async function Xn(C){it(C),J(!0);try{const P=await fetch(`${t}/conversations/${C}/messages`,{headers:{Authorization:`Bearer ${E.current}`}});if(!P.ok)throw new Error(`Failed to fetch messages: ${P.statusText}`);const O=(await P.json()).messages||[];Je(O)}catch(P){console.error("Failed to load conversation messages:",P)}finally{J(!1)}}async function Ze(C){if(M)try{await fetch(`${t}/conversations/${C}`,{method:"DELETE",headers:{Authorization:`Bearer ${M}`}}),q(Y.filter(P=>P._id!==C)),C===G&&Kt()}catch(P){console.error("Failed to delete conversation:",P)}}function Kt(){const C=crypto.randomUUID();it(C),Je([]),ot(new Set),xt.current={},st?f&&f({}):(ke({}),f&&f({})),te.current=!1}function Yn(C){pe(C)}async function Jn(C){const P={...xt.current,...C};xt.current=P,st||ke(P),f&&f(P);try{await Ee(C)}catch(V){throw V}}return{id:G,messages:Ut,status:ne,error:se,sendMessage:Xe,stop:Ye,addToolOutput:Yn,setMessages:Je,conversations:Y,loadConversation:Xn,deleteConversation:Ze,startNewConversation:Kt,isLoadingConversations:_,clientToken:M,tokenError:D,state:Zt,setState:Jn,isStateLoading:Bt,stateError:zt}}exports.verifyToken=fc.verifyToken;exports.ARCTEN_ORIGINAL_NAME=_t;exports.ArctenAgent=vf;exports.preserveToolName=Qh;exports.useAgent=wf;